Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python - adding price to total from different class
I would like to ask how to add attribute Price inside of class "Service" to Total Value attribute in class of "Order" . class Service(models.Model): Handyman = models.ForeignKey(Handyman, on_delete=models.CASCADE) name = models.CharField(max_length=500) short_description = models.CharField(max_length=500) image = models.ImageField(upload_to='service_images/', blank=True) price = models.IntegerField(default=0) class Order(models.Model): ORDER = 1 READY = 2 ONTHEWAY = 3 DONE = 4 STATUS_CHOICES = ( (ORDER, "Order"), (READY, "Ready"), (ONTHEWAY, "On the way"), (DONE, "Done") ) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) Handyman = models.ForeignKey(Handyman, on_delete=models.CASCADE) address = models.CharField(max_length=500) total = models.IntegerField() status = models.IntegerField(choices = STATUS_CHOICES) created_at = models.DateTimeField(default = timezone.now) picked_at = models.DateTimeField(blank = True, null = True) def __str__(self): return str(self.id) -
Django raise forms ValidationError not working
This could be a repeated question, however I did not found a solution for my issue. Issue is with my UserLoginForm validation. "raise forms.ValidationError" is not working and not throwing error. Everything else is perfectly working. My Form validation block def clean(self): cleanedData= super(UserLoginForm, self).clean() username= cleanedData.get('username') password = cleanedData.get('password') if User.objects.filter(username=username).exists() is False: print("User not available Validation should trigger") raise forms.ValidationError('User does not exists.') else: user = authenticate(username=username, password=password) if user is None: print("Authentication Failed Validation should trigger") raise forms.ValidationError('Invalid Credentials.') To catch errors I am using all 3 ({{ form.non_field_errors }}, {{ form.source.errors }}, {{ form.source }}) in my HTML template. I am able to see "User not available Validation should trigger" and "Authentication Failed Validation should trigger", but raise VailidationError not working. -
Django + Vue integration: Is using axois good for that?
Is using axois with django bad practice? And why? If not, should I use vuejs in django templates, or separate project in vue cli? Where's differeces? (Ps. for now I have 2 separate projects with communication via axois) -
Django2.1 global template variable
When I use django, I need to use some templates with user information and some data to display, but I can't request user information every time I render. I want to put this data in the template global variable, how can I solve it, I am using Django 2.1. Can you elaborate a little more? I have inquired a lot of ambiguity. Thank you -
django custom field accept and store decimal but return ouput as integer
I have problem statement where I need that my field should store the value as decimal, but while calling it the field should return a rounded Integer value Example mymodel.myfield = 12.61 mymodel.save() Input mymodel.myfield Output 13 and if it is possible mymodel.myfield.get_raw Output 12.61 Can I use django custom model field? class MyField(models.DecimalField): def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): super(MyField, self).__init__(*args, **kwargs) def get_raw(self, value): return value def to_python(self, value): if value is None: return value try: return decimal.Decimal(value) except decimal.InvalidOperation: raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) -
Django Validity day counter
in my app users are able to create posts which have a validity of 100 days. Now i want to display the user how many days are left until his post gets deleted. im currently solving the actual deletion of the post by a celery job which is working greate. My question is only about how to display the number until the validity runs out. In my opinion i only need a IntegerField with the validity in days and substract it from the creation date. is there a pratical way to do this? models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=40) content = models.TextField(verbose_name="Post Content", max_length=5000) tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) post_type = models.CharField(default='Free', editable=False, max_length=4) postattachment = fields.FileField( verbose_name="Post Attachment", blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[file_extension_postattachment, file_size_postattachment] ) postcover = fields.ImageField( null=True, blank=True, upload_to=get_file_path_user_uploads, validators=[default_image_size, default_image_file_extension], dependencies=[FileDependency(processor=ImageProcessor( format='PNG', quality=99, scale={'max_width': 700, 'max_height': 700}))]) up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0) down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0) published_date = models.DateField(auto_now_add=True, null=True) thanks and kind regards -
Declare object of derived class initialising properties of base class
Base class- class Base: x = models.CharField(max_length=10) Derived class- class Derived(Base): ... How do I declare an object of Derived class which initialises x like given below without adding constructor in Derived class. This syntax gives the error: x is not a member of Derived. obj = Derived(x='foo') -
how to query posts by category in django in function based view
I have a Post and Category model. Here I want to list posts By category. Category name will be title of the page and post with same category will be rendered under this. And I have no idea of how to do this. This is my model from django.db import models from django.utils import timezone from slugger import AutoSlugField from django.contrib.auth.models import User from django.urls import reverse # Create your models here. def upload_location(instance, filename): return "%s/%s" %(instance.slug, filename) class Category(models.Model): title = models.CharField(max_length= 60) slug = AutoSlugField(populate_from='title') parent = models.ForeignKey('self',blank=True, null=True ,related_name='children',on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=120) slug = AutoSlugField(populate_from='title') image = models.ImageField( upload_to=upload_location, null=True, blank=True, ) category = models.ForeignKey(Category, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self, slug=None): return reverse("posts-detail", kwargs={"slug": self.slug}) -
DRF | How to set serializer class to custom action?
I have a custom viewset action: @action(detail=True, methods=['post'], name = 'Verify Vendor', permission_classes = [permissions.isAdminOrSuperAdmin,]) def verify_vendor(self, request, pk=None): """ Change the status of a vendor as verified. """ serializer = serializers.VerifyVendorSerializer(data=request.data) if serializer.is_valid(): This works fine but causes an irritating bug in browsable API i.e the Browsable API does not deetct the form input fields until after submitting. ( because serializer is being set inside the action ) . As you can see below the actual fields (id) is not detected until after first submit. So I'm guessing this could be fixed if I can somehow set serializer in the @action decorator itself like permission_classes. Is there any way to do this? -
Dynamic html attribute naming
I have a list of banking transactions that I'm listing. I'm currently using bootstrap for my HTML/CSS. I found some template code that works well enough for what I want to do, but I've run into a problem: there's no way to know the id of the collapsing div element for the parent element. It's easier to see the html than to explain: {% for key, value in transactions.items %} <div id="accordion"> <div class="card"> <div class="card-header" id="heading-1"> <h5 class="mb-0"> <a role="button" data-toggle="collapse" href="#whatid" aria-expanded="true" aria-controls="whatid"> {{ key }} </a> </h5> </div> {% for key2, value2 in value.items %} <div id="whatid" class="collapse show" data-parent="#accordion" aria-labelledby="heading-1"> <div class="card-body"> <div id="accordion-1"> <div class="card"> <div class="card-header" id="heading-1-1"> <h5 class="mb-0"> <a class="collapsed" role="button" data-toggle="collapse" href="#collapse-1-1" aria-expanded="false" aria-controls="collapse-1-1"> {{ key2 }} </a> </h5> </div> {% for tr in value2 %} <div id="collapse-1-1">{{ tr.description }}</div> {% endfor %} </div> </div> </div> </div> {% endfor %} </div> </div> {% endfor %} The attributes href, aria-controls and the id of the child div element can't be known ahead of time and therefore can't be collapsed. Is it possible to do this? It's a bit of a chicken before the egg problem, so I don't really know what there is … -
Link column with a static text using django-tables2
I cannot find a replacement for the LinkColumn in the new versions of django-tables2. Author states that LinkColumn is deprecated and shouldn't be used. But the new linkify solution is poorly documented and doesn't have all the features of the old version. For example, I have this column: edit = tables.LinkColumn( 'wagtailadmin_pages:edit', args=[A('page.pk')], text='Edit' ) It displays a link to the wagtail admin edit page called Edit. There's simply no way to achieve the same using linkify because linkify only works if you have valid accessor on the column. But accessor cannot return same static text for all rows (unless I modify the model to add a dummy property - but this particular model is in the 3rd party package and it would feel like a duct tape solution anyway). In all other cases, column will not display a link. I've studied the source code and it seems that such case is simply not supported by the django-tables2 > 2.0.0. Is there any clean and understandable way to construct a link column with a static link text using linkify? -
Too many open files when using django-eventstream
We are using django-eventstream for sending out events to clients. You can think of our workflow to be celery like use case but a very simple one. Things were working flawlessly until we hit the 'too many open files' error (Redhat 7.4). We tracked which processes are opening the files using 'lsof' and found python was shooting several threads which loaded the required libraries (mostly .so files). We are using gunicorn as our server which spawns uvicorn workers. Tried to fall back to 'runserver', but faced the same issue. On trying out the 'time' and 'chat' examples, we saw the same behavior. On every refresh of the page (same machine, same browser, same tab) a new thread is spawned and 'lsof' lists an increment of about 2k files on every refresh of the page. We tried to recreate the same issue on two other different machines with the same OS. Saw the same behavior, expect in 1 machine. This was a laptop with 4GB of RAM and the rest are servers with 256GB of RAM. Interestingly everything works absolutely fine in the laptop, but not in the servers. Maybe because of the relative sparsity of resources, OS is closing the … -
Heroku: HTTPError at / HTTP Error 403: Forbidden
Need a desperate solution. Traceback. http://dpaste.com/16YNZB9 For Reference :- https://stockerdemo.herokuapp.com/ Cheers! -
How do create a custom save method for an existing m2m field. (Django)
I have a profile model which contains education and created a many to many relation i.e many profiles can have many educations. I have a template called Profile settings which contains multiple forms like Education CreateView, Education UpdateView and Education ListView. I'm using bootstrap modals to display these forms. Hence the they share same template. Problem is whenever I save education form, it saves form in database and it shows in the education multiselect field of that profile in django admin but unselected, it does not create a m2m link between profile and education. I overrided the save() method to create the link as suggested by the community but I'm not able to get the current profile. Getting this error after saving. ('EducationForm' object has no attribute 'request') Models class Profile(models.Model): phone = models.CharField(max_length=11, null=True, blank=True) education = models.ManyToManyField(Education, null=True, blank=True, related_name="education") full_name = models.CharField(max_length=30, null=True, blank=True) class Education(models.Model): degree = models.CharField(max_length=100, null=True, blank=True) school = models.CharField(max_length=100, null=True, blank=True) edu_start_date = models.DateField(null=True, blank=True) edu_end_date = models.DateField(null=True, blank=True) View class EducationView(CreateView): model = Education form_class = EducationForm pk_url_kwarg = 'pk' template_name = "profile_settings.html" class ProfileSettingsView(UpdateView): model = Profile form_class = ProfileSettingsForm pk_url_kwarg = 'pk' context_object_name = 'object' template_name = 'profile_settings.html' def … -
Django model form field to have a user dropdown list based on the designation
In a Django Modelform (Product_definition), i want to have a dropdown(Merchant name) which will show users only if the their designation in User form is "Merchant". is it possible that I could get the list of users for the dropdown based on this condition .Please note that i don't require it to be a foreign key as connecting the models is not required. This is the form which contains the Designation : from django.contrib.auth.models import User class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE) #extra UserAttribute MERCHANT = 'MR' FABRIC = 'FR' WASHING = 'WS' PRINT = 'PR' PLANNER = 'PL' DESIGNATION_CHOICES =( (PLANNER,'Planner'), (MERCHANT,'Merchant'), (FABRIC,'Fabric'), (WASHING,'Washing'), (PRINT,'Printing'), ) Designation =models.CharField( max_length = 20, choices = DESIGNATION_CHOICES, default= 'PLANNER' ) def __str__(self): return self.user.username and this is the form with Merchant Name where I want the names of all merchants to appear. class Product_definition(models.Model): Order_number = models.CharField(max_length=25,unique = True, blank = True, null = True) style_name = models.CharField(max_length=15, blank = True, null = True) color = models.CharField(max_length=15, blank = True, null = True) Order_qty = models.PositiveIntegerField() SMV = models.FloatField() MERCHANT = models.ForeignKey(UserProfileInfo,on_delete= models.CASCADE,default='Select') def __str__(self): return self.Order_number I have created a foreign key for now but I don't require it and … -
Django Cannot assign "'Pizza'": "Order.Food_Name" must be a "Foods" instance
Hello Guys I am working on a restaurant project which allow user to select food item and book an order but i am getting this error as i try to book an order "Django Cannot assign "'Pizza'": "Order.Food_Name" must be a "Foods" instance." I am using drop down menu to select food items i am using django version 2.1.5 . Please Help views.py def place_order(request): name = request.POST["user"] food_items = request.POST['food_item'] qty = request.POST['qty'] rating = request.POST['ratings'] price = Foods.Food_Price order = Order(Date=datetime.date, Name_of_Person=name,Food_Name=food_items, Qty=qty, Total=price, Ratings=rating) order.save() return render(request, "index.html") model.py from django.db import models class Foods(models.Model): Food_Number = models.IntegerField(null=False,) Food_Name = models.CharField(max_length=30, primary_key=True, null=False) Food_Qty = models.CharField(max_length=10) Food_Price = models.IntegerField() def __str__(self): return f"{self.Food_Number} - {self.Food_Name} {self.Food_Price}" class Order(models.Model): Order_id = models.AutoField(null=False, primary_key=True) Date = models.DateField() Name_of_Person = models.CharField(null=False, max_length=40) Food_Name = models.ForeignKey(Foods, on_delete=models.CASCADE) Qty = models.CharField(max_length=10) Total = models.IntegerField() Ratings = models.IntegerField() def __str__(self): return f"{self.Order_id} - {self.Name_of_Person} |{self.Food_Name} |{self.Total}" What can i do solve this error -
Django queryset filter based on parent of parent
Say I have the models Teacher, Course, Student. Student model has a foreignKey one-to-many- to Course, and Course has a foreignKey one-to-many to Teacher. When getting a queryset of all Student objects, is there a way to query them based on Teacher? -
django send email using EmailMultiAlternatives
I have a need for sending an email using django EmailMultiAlternatives, and after long hours of research I found a way to customize the host, port, user and password, but, when execute my code there is a really weird error 'EmailBackend' object is not iterable Here is my Settings ACCOUNT_EMAIL = os.environ['ACCOUNT_EMAIL'] ACCOUNT_PASSWORD = os.environ['ACCOUNT_PASSWORD'] EMAIL_PROVIDER = 'krishna.hosting-mexico.net' EMAIL_SERVER_PORT = 465 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' Extra variables EMAIL = settings.ACCOUNT_EMAIL PASSWORD = settings.ACCOUNT_PASSWORD EMAIL_PROVIDER = settings.EMAIL_PROVIDER EMAIL_SERVER_PORT = settings.EMAIL_SERVER_PORT EMAIL_BACKEND = settings.EMAIL_BACKEND connection = get_connection(host=EMAIL_PROVIDER, port=EMAIL_SERVER_PORT, username=EMAIL, password=PASSWORD, use_tls=True) And here my function def send_driver_welcome_email(user_email): from_email_address = EMAIL from_email_address_password = PASSWORD htmly = get_template('driver_welcome_email.html') html_content = htmly.render(None) msg = EmailMultiAlternatives('Bienvenido a TAXI 2.0', html_content, from_email_address, [user_email], connection) msg.attach_alternative(html_content, "text/html") msg.send() I have tried to not specify the EMAIL_BACKED, but the error still shows up, also this it's the closer that had get to send a custom "site" as an email, it has some images and two different stylesheets and I dind't find any other way, if you have one, then your suggestion will be welcome. -
Django: cannot send variables via AJAX
I've a template that renders correctly my variable {{ product.category.slug }} and {{ product.slug }}. I can even alert there variables like: alert("{{ product.category.slug }}"); alert("{{ product.slug }}"); But for some reason I cannot send them via AJAX: (in my view when getting and printing the variables their values are None). $("#send_review").click(function () { alert("{{ product.category.slug }}"); alert("{{ product.slug }}"); $.post("{% url 'shop:make_review_view' %}", { category_slug: "{{ product.category.slug }}", product_slug: "{{ product.slug }}", review: get_user_comment(), stars: get_review_stars(), }, ).done(function () { alert("Gracas por su review"); }) }); </script> Or retrieve them correctly in my view: View: @csrf_exempt def make_review_view(request): print("Make_Review_View gets called") user = request.user print(user) # prints "ogonzales" category = request.GET.get('category_slug') print(category) # prints "None" product = request.GET.get("product_slug") print(product) # prints "None" review = request.GET.get("review") print(review) # prints "None" stars = request.GET.get("stars") print(stars) # prints "None" try: category = Category.objects.get( slug=category , ) product = Product.objects.get( slug=product, ) review = Review.objects.create( user=user, category=category, product=product, review=review, stars=stars ) if not review: print("Review Object wasn't created") else: review.save() print("Review saved in DB") except Review.DoesNotExist: print("No se creo el Review") return HttpResponse("Hi") -
NoReverseMatch at / Reverse for 'store' not found. 'store' is not a valid view function or pattern name
i am trying to make a simple home page which will have a link to another page named store.html.This is my views.py in store app from django.shortcuts import render, get_object_or_404, redirect def home(request): return render(request, 'store/home.html') def store(request): return render(request, 'store/store.html') This is my urls.py in store app from django.urls import path from . import views app_name = 'store' urlpatterns = [ path('', views.home, name ='home'), path('store/', views.store, name = 'store'), ] home.html here i have put href="{% url 'home' %}". but i found reverse not match error. but everything is looking good. {% extends './base.html' %} {% block content %} <body> <h1>home</h1> <a class = 'btn' href="{% url 'store' %}">store</a> </body> {% endblock %} Please help me how to use fix this to make the link so that when clicking on that it will open another page. I am new to django and i am using version 2.1.7 -
Need to pick individual elements from different lists and store them in a dictionary
I'm working with Python3.6 (especially Django) and have the following situation to tackle. I have a dictionary of lists that is being returned to me as the output returned from a previously used function, which is something like this: {'sensor_state_list': ['in_service', 'in_service'], 'rx_sensor_delta_list': [0, 321144], 'tx_sensor_delta_list': [0, 321144], 'discard_sensor_delta_list': [0, 321144], 'time_list': ['2019-03-08 10:30:11.049860+00:00', '2019-03-08 12:47:16.722241+00:00']} As you can see, it contains 5 lists which hold a collection of similar data. What I intend to do is pick up one instance from each list simultaneously and store them as a set for that particular instance and store that as a dictionary, so I can pass that as my API output and use it for charting. The output is desire would be something like: {'instance1' : {'sensor_state' : 'in_service', 'rx_sensor_delta': 0, 'tx_sensor_delta': 0, 'discard_sensor_delta': 0, 'time': '2019-03-08 10:30:11.049860+00:00'}, 'instance2': {'sensor_state' : 'in_service', 'rx_sensor_delta': 321144, 'tx_sensor_delta': 321144, 'discard_sensor_delta': 123451, 'time': '2019-03-08 12:47:16.722241+00:00'} and so on as the number of instances increase in the source list. I'm pretty sure I'm missing something really basic but at this point I'm exhausted of ideas and I really need somebody's help in fixing this; my submission deadline is creeping up fast. Thank you kind ladies and … -
Django Formview Edit Form using Formview
I have created a form for editing particular post using generic formview, instead of overriding the object it creates an another instance and saving it in the table ..Need help class showprofile(generic.FormView): form_class=ProfileForm template_name="blogs/profile_student.html" success_url=reverse_lazy('blogs:student_profile') def get(self,request,*args,**kwargs): action=self.request.GET.get('action') pk=self.request.GET.get('pk') print pk if action =='edit': data={} data=super(showprofile,self).get_context_data(**kwargs) fill=Profile.objects.filter(id=pk).first() data['url']=fill.profile_pic fill.profile_pic="" print data['url'] data['form']=ProfileForm(instance=fill) return render(request,self.template_name,data) else: data=Profile.objects.filter(id=pk) print data args={'form':self.form_class,'list':data} print args return render(request,self.template_name,args) def post(self,request,*args,**kwargs): form.save() return render(request,self.template_name) -
ModuleNotFoundError: No module named 'C:\\Users\\user\\Anaconda3\\Lib\\site-packages\\django_extensions'
while "python manage.py runserver" it says ModuleNotFoundError but I have checked in the path 'C:\Users\user\Anaconda3\Lib\site-packages\django_extensions' the django_extension exists and still it is giving error. Just so you know i also tried pip install django_extensions it said installed successfully but when again i did "python manage.py runserver" it gave me the same error.... messed up right now....please help -
How to reduce the number of database hits while querying in Django
I have three tables 1. User, 2. Device and 3. Log I want filter the logs based on devices and logs. I'm using the following querying which iterates over the users and devices in order to get the logs. I feel this will become a performance hit. Can anyone suggest me a way to reduce the number of database hits. for user_obj in User.objects.all(): device_qs = Device.objects.filter(user=user_obj) if device_qs.exists(): for device_obj in device_qs: log_count = Log.objects.filter(user=user_obj, device=device_obj, created_at__range(from_date, to_date)).count() -
Django and React.js Production
I added a React to my Django project. It seems everything works. But if I refresh the page in the browser, I get an error: enter image description here I understand that Django is trying to find an appropriate view, but how to make it so that the React?