i have issues with while rendering dynamic data for templates - python

Code below models
class Events(models.Model):
event_author=models.ManyToManyField(Author)
event_title=models.CharField(max_length=300)
event_title_image = models.ImageField(upload_to='images/', blank=True, null=False)
event_description=models.TextField(blank = True)
event_image_description = models.ImageField(upload_to='images/', blank=True, null=True)
event_release_date = models.DateField(null="false")
def __str__(self):
return self.event_title
def publish(self):
self.event_release_date = timezone.now()
self.save()
views
def Event(request):
events=Events.objects.filter(published_date__lte=timezone.now()).order_by('event_title')
return render(request, 'polls/events.html', {})
templates
<p>Events page </p>
{{ events }}
Error
FieldError at /events
Cannot resolve keyword 'published_date' into field. Choices are: event_author, event_description, event_image_description, event_release_date, event_title, event_title_image, id
while I am running a server I got an error like filed error please help out of this i am new django.

That's because you're filtering on a field which not included on your model.
events=Events.objects.filter(published_date__lte=timezone.now()).order_by('event_title')
as I can see, your published_date is correspond to field event_release_date on your model, so it supposed to be like this:
events=Events.objects.filter(event_release_date__lte=timezone.now()).order_by('event_title')

Related

How to solve url parameter problem in Django?

I have a strange problem.
I have a page that uses url parameters. Users can reach this site based on their project id and name and the group(csoport) name that stored in three models. This is a link for an example page:
/performance/monthlyfeedback/{{ request.user.profile.csoport }}
That link works fine if the name of the csoport is a number. If it is any kind of a text it gives me 404 error that I can't figure out why.
models.py
class Profile(models.Model):
def __str__(self):
return str(self.user)
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
csoport = models.CharField(max_length=100, null=True, blank=True)
class Projekt_perf(models.Model):
def __str__(self):
return str(self.projekt_perf)
projekt_perf = models.CharField(max_length=250)
jogosult_01_perf = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True, auto_now=False, blank=True)
class Performance_profile(models.Model):
def __str__(self):
return str(self.user_name)
user_name = models.ForeignKey(User, on_delete=models.CASCADE)
projekt_perf = models.ForeignKey(Projekt_perf,on_delete=models.CASCADE)
views.py
I am using raw query in the views.
def obj_results(request, projekt_perf_id, projekt_perf, user_name_id, csoport):
person = Projekt_perf.objects.raw('SELECT * FROM performance_projekt_perf INNER JOIN performance_performance_profile ON performance_projekt_perf.id = performance_performance_profile.projekt_perf_id INNER JOIN stressz_profile ON performance_performance_profile.user_name_id = stressz_profile.user_id WHERE performance_projekt_perf.id = %s AND projekt_perf = %s AND stressz_profile.user_name_id = %s AND stressz_profile.csoport = %s',[projekt_perf_id, projekt_perf, user_name_id, csoport])
context = {
'person': person,
}
return render(request, 'performance/obj-results.html', context)
urls.py
app_name = 'performance'
urlpatterns = [
path('monthlyfeedback/<int:projekt_perf_id>', login_required(views.Performance_test), name='performance_feedback'),
path('list/<int:projekt_perf_id>/<projekt_perf>', login_required(views.list), name='performance_list'),
path('obj-results/<int:projekt_perf_id>/<projekt_perf>/<int:user_name_id>/<csoport>', login_required(views.obj_results), name='obj_results'),
]
What am I doing wrong?
In urls.py:
path('monthlyfeedback/<int:projekt_perf_id>'
You have defined the “project_perf_id” as int. Change it.
Can you try with <str:csoport> but I reccomend you to use slugs.
path('obj-results/<int:projekt_perf_id>/<projekt_perf>/<int:user_name_id>/<str:csoport>', login_required(views.obj_results), name='obj_results'),

Django: the detail page is not showing(template error)

am working on a Django project where showing the details of post and amount
here is my models.py of post
class Loader_post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader")
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
receiver_name = models.CharField(max_length=150)
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse("Loader:my_job", kwargs={"pk": self.pk})
this is my second models which I inherit Loader post
class price(models.Model):
my_post = models.ForeignKey(Loader_post, related_name='prices',on_delete=models.CASCADE,
null=True, default='')
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, default='')
driver_price = models.CharField(max_length=150, null=True)
driver_name = models.CharField(max_length=150, null=True)
approved_price = models.BooleanField(default=False)
status = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse("Driver:Driverview")
def __str__(self):
return self.driver_price
this is the view.py of both list and details view
class offer_view(ListView, SelectRelatedMixin):
context_object_name = 'offern'
model = Loader_post
template_name = "offer.html"
def get_queryset(self):
qs = Loader_post.objects.filter(user=self.request.user)
return qs
class offer_view_detail(DetailView):
context_object_name = 'offernew'
model = Loader_post
template_name = "offer_detail.html"
here is my HTML page of list view ...when someone clicks on it it shows the detail of next post
offer.html
{% for my in offern %}
{{my.sender_name}} {% endfor %}
and when someone clicks on its route to the detail page .. but it shows template doesn't exist
this is my detail page ie. offer_details.hml
<p>{{offernew.sender_name}}</p>
<p>{{offernew.receiver_name}}</p>
{% for x in offernew.prices.all %}
<p>
<p>{{x.driver_name}}</p>
</p>
and this is urls.py
path('offerdetail/<int:pk>', views.offer_view_detail.as_view(),name="offerdetail"),
path('offer/', views.offer_view.as_view(), name="offer"),
Following on from comments,
In you ListView,
{{my.sender_name}}
here, the url specified is not defined in your urls.py, that's why it was showing no template doesn't exist, changing to this would solve this.
{{my.sender_name}}
Now, To show prices model in your DetailView, i would do something like this.
class offer_view_detail(DetailView):
context_object_name='offernew'
model = Loader_post
template_name = "offer_detail.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['price_model'] = self.object.prices.all()
return context
and In your Template
<p>{{offernew.sender_name}}</p>
<p>{{offernew.receiver_name}}</p>
{% for x in offernew.price_model %}
<p>{{x.driver_name}}</p>
{% endfor %}
Django Docs for DetailView

Django fields in form

I am a beginner in Django, hence this might be a simple issue. But I'm not able to get past this successfully.
This is my models.py
class Category(models.Model):
name = models.CharField(max_length=128)
abbr = models.CharField(max_length=5)
def __unicode__(self):
return self.name
class Fabric(models.Model):
name = models.CharField(max_length=128)
abbr = models.CharField(max_length=5)
def __unicode__(self):
return self.name
class Manufacturer(models.Model):
name = models.CharField(max_length=128)
location = models.CharField(max_length=128)
name_abbr = models.CharField(max_length=5, default=None)
loc_abbr = models.CharField(max_length=5, default=None)
def __unicode__(self):
return self.name
class Images(models.Model):
design_id = models.CharField(max_length=128)
file = models.ImageField(upload_to='images')
cost_price = models.FloatField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
fabric = models.ForeignKey(Fabric, on_delete=models.CASCADE)
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
selling_price = models.FloatField()
aliveness = models.IntegerField()
date_added = models.DateTimeField(default=datetime.datetime.now)
set_cat = models.IntegerField()
set_cat_no = models.IntegerField()
set_cat_name = models.CharField(max_length=50, blank=True)
I'm building an apparel management database system which contains cloth designs.
My forms.py is
class ImagesForm(forms.ModelForm):
class Meta:
model = Images
fields = ('file','cost_price','set_cat_no','set_cat_name',)
My views.py
#login_required
def uploadphoto(request):
context = RequestContext(request)
context_dict = {}
if request.method == 'POST':
form = ImagesForm(request.POST,request.FILES)
if form.is_valid():
image = form.save(commit=False)
image.save()
return render_to_response(request,'cms/upload-photo.html', {'upload_image': form})
else:
print form.errors
else:
form = ImagesForm()
context_dict = {'upload_image': form}
return render_to_response('cms/upload-photo.html',context_dict, context)
My upload-photo.html is
{% block main %}
<form id="upload_form" method="post" action="/zoomtail/upload-photo/" enctype="multipart/form-data">
{% csrf_token %}
{{ upload_image }}
</form>
{% endblock %}
The problem here is when I goto /upload-photo/ I don't see the drop-downs to the foreign keys to categories, fabric and manufacturers. I have read that it should be automatically generated but I don't see any.
And selling_price has to be calculated based on the given percentage increase from the cost_price which has to be entered in the form. How do I do this? And aliveness of an apparel has to be set by default as 1. How to do this?
set-cat field of an apparel is 1 if it belongs to a set and 2 if it belongs to a catalogue. How do I get a radio button asking whether set or catalogue and that to be captured as an integer in the database?
And design-id field of an apparel has to be a string which contains abbreviations of category, fabric, manufacturer, etc etc all the fields it belongs to. How do I do this dynamically?
I know, this is a very long question but I'm a newbie and these are literally giving me headache since days. I shall be very thankful to those who answer this.
I believe the issue with the dropdown is that you've excluded the fields from ImageForm. You have:
fields = ('file','cost_price','set_cat_no','set_cat_name',)
but should have:
fields = ('file','cost_price','set_cat_no','set_cat_name', 'category', 'fabric', 'manufacturer,)`
if that doesn't work, are there any options in your database for Categories, Fabric, and Manufacturer? If your tables are empty, the dropdown will be empty. If there are values in the database, is there HTML being generated but the label value is blank (i.e. <option>{this is blank}</option>)? In django, you can override the __str__ function to specify how the dropdown options get labeled
Override __str__ as follows:
class Category(models.Model):
name = models.CharField(max_length=128)
abbr = models.CharField(max_length=5)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
You can compute the value of selling_price and any other computed value in the block if request.method == 'POST'.
Example:
def uploadphoto(request):
context = RequestContext(request)
context_dict = {}
if request.method == 'POST':
form = ImagesForm(request.POST,request.FILES)
#- Calculate value(s) here -#
if form.is_valid():
image = form.save(commit=False)
image.save()`
Please see this post here for using radio buttons
You would do this in the same place as #2 above

Disply the list of users with total posts

How can I display the list of users with the count of total number of posts made by them in a separate HTML page ?
models.py
class Post(models.Model):
author = models.ForeignKey(User.request, on_delete = models.CASCADE)
title = models.CharField(max_length=100)
text = models.TextField()
slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1)
created_date = models.DateTimeField(default=timezone.now)
likes = models.ManyToManyField(User, related_name='post_likes', blank = True)
def get_like_url(self):
return reverse("posts:like-toggle", kwargs={"slug": self.slug})
def get_api_like_url(self):
return reverse("posts:like-api-toggle", kwargs={"slug": self.slug})
def get_absolute_url(self):
return reverse("post_detail",kwargs={'pk':self.pk})
def __str__(self):
return self.title
def count_posts_of(user):
return Post.objects.filter(author=user).count()
You have to learn MVC architecture(MVT in django).
As a beginner first create a sample project to understand this - https://docs.djangoproject.com/en/2.0/intro/tutorial01/
Learn how models.py are written - https://docs.djangoproject.com/en/2.0/topics/db/models/
and how to writeviews.py - https://docs.djangoproject.com/en/2.0/topics/class-based-views/
Then connect them in urls.py - https://docs.djangoproject.com/en/2.0/topics/http/urls/
This is my solution at the moment, but it could be done differently.
First, add count_posts_of method to your User model whatever it is.
For instance I myself created a user model and add this method to it as following:
models.py
class User(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
#property
def count_posts_of(self):
return self.post_set.all().count()
now in the view pass all the users as context:
views.py
def user_post(request):
context = {'users': User.objects.all()}
return render(request, 'future/user_post_view.html', context)
and finally in the template show the user and their posts' count:
user_post_view.html
{% for user in users %}
{{ user.name }} :
{{ user.count_posts_of }},
{% endfor %}

DJango CreateView not setting DB Key with Class-Based Views

I am using CreateView from DJango to save data to the DB. To do this, I am following the instructions here: Form handling with class-based views
According to my understanding, after the data is saved to the DB, the control is to be passed to a type of "success screen" - in this case, for my scenario, control is to be passed to a "details page". The details page is represented by the following URL:
url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(),
name='owner-contact-details'),
Below (in the class Mstrstoreheadcontact) the "details page" is being called by the get_absolute_url function (which is part of the Mstrstoreheadcontact model)
from the models.py file
class Mstrstoreheadcontact(models.Model):
tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True)
contactid = models.BigIntegerField(primary_key=True, default=0)
genderid = models.BigIntegerField(blank=True, null=True, default=0)
firstname = models.CharField(max_length=20, blank=True, null=True)
lastname = models.CharField(max_length=20, blank=True, null=True)
officephoneno = models.CharField(max_length=20, blank=True, null=True)
cellphoneno = models.CharField(max_length=20, blank=True, null=True)
class Meta:
managed = False
db_table = 'MstrStoreHeadContact'
def get_absolute_url(self):
return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid})
For me the code: return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid} is supposed to take the control to the "details page" that will display the new record that has been added to the DB.
The problem
When the code above is executed, the variable self.contactid is set to 0. See below:
This results in the following URL to be placed in the address bar:
http://127.0.0.1:8000/masterdata/owner/0/contact/details
Because of the "0", this leads to a 404 error. In the DB, the value is set - for example to 10.
Again, the data saves to the DB JUST FINE- there is no problem with
this part. The problem lies with what happens AFTER the data is saved
to the DB.
Below are some entries from the urls.py file
from the urls.py file
url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(),
name='owner-contact-details'),
url(r'^owner/(?P<tenantid>[0-9]+)/contacts/add/$', views.MstrstoreheadcontactCreateView.as_view(),
name='owner-contact-add'),
from the views.py file
class MstrstoreheadcontactCreateView( CreateView ):
model = Mstrstoreheadcontact
fields = [ 'firstname', 'lastname', 'genderid', 'officephoneno', 'cellphoneno']
def form_valid(self, form):
contact = form.save(commit=False)
contact.tenantid = Mstrauthowner.objects.get(tenantid=self.kwargs['tenantid'])
return super(MstrstoreheadcontactCreateView, self).form_valid(form)
It seems like the code is not getting the data back from the DB properly (after the data has been saved). What can I do to fix the problem?
TIA
Well, thank goodness for debuggers. The following changes resolved all the problems for me :-)
views.py
class MstrstoreheadcontactCreateView( CreateView ):
model = Mstrstoreheadcontact
fields = [ 'firstname', 'lastname', 'genderid', 'officephoneno', 'cellphoneno']
def form_valid(self, form):
form.instance.tenantid = Mstrauthowner.objects.get(tenantid=self.kwargs['tenantid'])
return super(MstrstoreheadcontactCreateView, self).form_valid(form)
models.py
class Mstrstoreheadcontact(models.Model):
tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True)
contactid = models.BigIntegerField(primary_key=True, default=0)
[... snip ..]
def get_absolute_url(self):
[... snip ...]
return reverse('masterdata:owner-contact-details', kwargs={'pk': self.tenantid.pk})

Categories

Resources