Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I properly validate a ModelForm (best practices)?
I have a ModelForm that I need to validate. I am currently overriding clean() method with custom validator functions. These validators raise a ValidationError in case something is wrong. If everything is fine - they do nothing. I have two questions: Is this approach a good practice? I am naming my validator functions the following way: ensure_SOMETHING (e.g. ensure_circular_reference_nonexistence(...), ensure_max_depth_limit_is_respected(...), etc.). Again, is this a good practice? I haven't seen others user "ensure" in their function names. To be 100% clear, this is how my clean() method looks like: def clean(self, *args, **kwargs): ensure_circular_reference_nonexistence(...) ensure_max_depth_limit_is_respected(...) return super(MyForm, self).clean(*args, **kwargs) -
How to convert a string to valid json?
Is there an easy way to convert a string such as 'username=andrew&password=password1234' to { "username: "andrew", "password": "password1234" } ? I have been trying to loop through the string and manually add it but I was curious to see if there was an easier way or a library i'm just not seeing. -
How to make queries directly on the models.py file in django, to fill the fileds with the results?
Hi I want to know If I am able to work directly with queries inside the "models.py" file to make results the default values of some fields. For example: class NewModel(models.Model): Seats = models.IntegerField(default=<some_result_of_a_query>) ... Thanks! :) -
How to overwrite the `.create` method in writable nested serializer for nested models having ManyToMany Field?
I am trying to build an endpoint using Django Rest Framework for the Device model:- Device Model class AbstractDevice(OrgMixin, BaseModel): name = models.CharField() mac_address = models.CharField() key = KeyField() model = models.CharField() os = models.CharField() system = models.CharField() notes = models.TextField(blank=True, help_text=_('internal notes')) last_ip = models.GenericIPAddressField() management_ip = models.GenericIPAddressField() hardware_id = models.CharField() Config Model class AbstractConfig(BaseConfig): device = models.OneToOneField(Device, on_delete=models.CASCADE) templates = SortedManyToManyField() vpn = models.ManyToManyField() STATUS = Choices('modified', 'applied', 'error') status = StatusField() context = JSONField() For the above models, I have created serializers as:- DeviceConfigSerializer class DeviceConfigSerializer(serializers.ModelSerializer): class Meta: model = Config fields = ['backend', 'status', 'templates', 'context', 'config'] DeviceListSerilaizer class DeviceListSerializer(serializers.ModelSerializer): config = DeviceConfigSerializer() class Meta(BaseMeta): model = Device fields = ['id','name','organization','mac_address','key','last_ip', 'management_ip','model','os','system','notes','config'] def create(self, validated_data): import ipdb; ipdb.set_trace() config_data = validated_data.pop('config') device = Device.objects.create(**validated_data) Config.objects.create(device=device, **config_data) return device Since I want to incorporate a nested serializer and to make it writable It is required to manually add the .create or .update method. and the views: Views class DeviceListCreateView(ListCreateAPIView): serializer_class = DeviceListSerializer queryset = Device.objects.all() I am having a templates field which is a SortedManyToManyField() Field, if I am not wrong then I think something has to be tweaked with that field because when I am trying … -
Allow user to download file and then redirect to other page
I have a function like: def download(requests): with open(file_path2, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path2) return response #it stop executing here as we return. os.remove(file_path2) return render(request, 'user/charts.html', {'res': 'The file has decrypted'}) So what the function needs to do is, start the file downloading and after download delete the file from system then redirect to other page. But the problem is,for implementing downloading functionality , I use return and then it stops, So how can I execute next statements ? -
How to reset the values of form using the Ajax .reset() method every time the item is added in the cart in django
** I have tried many times, used query 2, 3 and even cdn but the reset function isn't working, firstly in jqyuery 2 it was showing the error like .reset() isn't a function, but in cdn or latest query 3 the error is not appearing, but the reset is also not working ** $(document).on('submit','#addCartForm',function(e){ {#var frm = $('#addCartForm');#} e.preventDefault(); $.ajax({ type: 'POST', url: '/cart_add', {#data: frm.serialize(),#} data: { project_id: $('#project_id').val(), amount: $('#amount').val(), project_category_id: $('#project_category_id').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function () { alert("Cart Added"); $("#addCartForm")[0].reset(); {#$("#addCartForm").empty();#} {#$('#addCartForm').trigger('reset');#} {#document.getElementById("addCartForm").reset();#} {#document.getElementById("addCartForm").reset(); {# THIS reset() FUNCTION IS USED TO RESET THE VALUES INSIDE THE FORM INPUT FIELDS: #} }, error: function () { alert("Something went wrong!"); }, }); }); ** I have to add the item in the cart one by one, but it isn't moving to the next item, it still have the first item's data. it adds the same data even I trigger an other item. I searched a lot but it isn't working. ** My Template {% for project in projects %} <form class="donate-page-form" id="addCartForm"> {% csrf_token %} <h4 class="text-uppercase our-causes__title text-truncate" id="logoColor"><a href="{% url 'project-detail' project.id %}">{{ project.get_name }}</a></h4> <p>{% if project.isZakat %}{% trans "Calculate your Zakat" %}{% else %}{% trans … -
Adding User model to the StructBlock class
I'm trying to create a simple blog page with image,content,date posted and user who posted. But I don't think that wagtail allows me to put in the user model into my block. class HomePage(Page): template_name = 'home/home_page.html' max_count = 1 subtitle = models.CharField(max_length=200) content = StreamField( [ ("title_and_text_block", AnnouncementBlock()) ] ) content_panels = Page.content_panels + [ FieldPanel("subtitle"), StreamFieldPanel("content") ] def get_context(self, request, *args, **kwargs): context = super().get_context(request, args, kwargs) context['posts'] = HomePage.objects.live().public() return context; from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock class AnnouncementBlock(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text='Add your title') content = blocks.RichTextBlock(required=True, features=["bold", "italic", "link"]) image_thumbnail = ImageChooserBlock(required=False, help_text='Announcement Thumbnail') class Meta: template = "streams/title_and_text_block.html" icon = "edit" label = "Announcement" My goal is everytime user posted a new announcement his/her name should appear. not sure how i can do that since in the block i cannot add the User model so that the user's detail will be saved along with the content/image etc. something like this. from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock from django.conf import settings class AnnouncementBlock(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text='Add your title') content = blocks.RichTextBlock(required=True, features=["bold", "italic", "link"]) image_thumbnail = ImageChooserBlock(required=False, help_text='Announcement Thumbnail') #USER is not allowed here. error on the model user = … -
How to migrate a Django model into models with table inheritance
Our current Django project has a model that already has a huge amount of instances in the database. When we started the project we had only one application in mind. Due to new requirements and planning for upcoming applications, we have realized that it might be very beneficial to restructure the database using model inheritance now before it's too late. This is because we can split this model (that has a lot of data in the database) into a base model and another one inheriting from it. The benefit of doing so is that the new applications of the project will also be able to inherit this base model as it contains common fields. I know that this change would imply a table for the base model and other tables that are related to that table. I am wondering if there's a way that I can perform these changes while minimizing the impact of the data. Ideally, I would like to keep the id's intact, since customers are using the data already. Since basically all the database is of ModelA, my idea was to convert all the data of this model into a model inheriting from a base model: ModelA(BaseModel) … -
I am Unable to find what's wrong with Heroku Deployment
I have Deployed a Django Application On HEROKU (Using HEROKU free Services). At the start, it was working well but now some of my product images are not showing up. Anyone can tell me what's wrong with this or why it's happening :( -
Code cleanup for Django queries and ternary operator
How best can I clean up this code into one Django query with the ternary operator : if isinstance(self.instance, Business): agg_shares = BeneficialOwnerShares.objects.filter( parent_company=parent ).exclude( owner_company=self.instance ).aggregate( sum_shares=Coalesce(Sum('allocation_of_shares'), V(0)) ) else: agg_shares = BeneficialOwnerShares.objects.filter( parent_company=parent ).exclude( owner_person=self.instance ).aggregate( sum_shares=Coalesce(Sum('allocation_of_shares'), V(0)) ) Am trying to add the ternary operator in the exclude() function to switch between the owner_person=self.instance and owner_company=self.instance, but it doesn't work , how best can I do this ? -
Django sentry log only to sentry, not console
I have a django application with sentry integration. I have a management command that I know is gonna get quite a lot of exception, mostly due to network. I want to see the progress of the command in the console and I use tqdm for that and I dont want to see the errors in the console, but I do want to see the errors in sentry. I've set up my sentry in settings.py like so: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'sentry': { 'level': 'ERROR', 'class': 'sentry_sdk.integrations.logging.EventHandler', }, }, 'loggers': { 'devices.management.commands.send_to_device': { 'handlers': ['sentry'], 'level': 'ERROR', }, } } This is the command's code: failed = [] for obj in tqdm(lst): try: send(obj) except Exception as e: # log to sentry only (according to logging config in settings.py) logger.error(e, exc_info=True, extra={'obj': obj}) failed.append(obj) logging.getLogger('stats').warning(f'{len(failed)} failed') However, I do not get exceptions logged in sentry ... or even more weird, I a couple of them logged when I'm expecting hundreds. When I tried a simple logger.error('test') outside of the loop - it worked just fine. What am I missing? -
Elastic Beanstalk: Find package causing dependency installation error
Elastic Beanstalk returned the error Instance deployment failed to install application dependencies. after trying to deploy my Django application. I am guessing there is a package in the requirmenents.txt causing this. How do I find exactly which package is causing the installation error? -
Django DecimalField inconsistent rounding
Django 2.2, PostgreSQL database. I have a Line object with a positions property. This is an ArrayField of a DecimalField with a max_digits of 12 and decimal_places of 3. I want to store two floats as Decimals: pos = [6586.87849502, 2.04190477e-01, 7.14666669e-01] line = Line(positions=pos) line.save() line.refresh_from_db() # send it through Django's ORM piping print(line.positions) Output: [Decimal('6586.879'), Decimal('0.204'), Decimal('0.715')] Interestingly, the first position was rounded up despite its next more significant digit being below 5. The other float is rounded down as expected. The real issue is that I'm trying to predict what will come out of the database, down to the required precision of three decimal places: [Decimal(x).quantize(Decimal("0.001")) for x in pos] might yield [Decimal('6586.878'), Decimal('0.204'), Decimal('0.715')] or [Decimal('6586.879'), Decimal('0.205'), Decimal('0.714')] depending on the decimal.ROUND_* flag I pass in quantize(), but I never get consistent rounding throughout the array. How does Django round or is PostgreSQL doing something? -
Create/Update class-based view for Many-to-Many relationship with intermediate model
I'm trying to write Class-based view for class A and simultaneously provide adding values to M2M table between class A and class B. To be more precise, I will explain by following example. There is requirement to extend Many-To-Many relationship between Pizza and Toping with attribute of amount, so class Membership is also created like in code below. How to create class-base view for Pizza where user can create new Pizza and also select Toppings with amount? Also, there is one more requirement: Pizza must contain at least 3 type of Topping. First, I referenced to this solution, but this solution doesn't allow filling additional attribute(amount) of class Membership. from django.db import models class Pizza(models.Model): name = models.CharField(max_length=30) toppings = models.ManyToManyField('Topping', through='Membership') class Topping(models.Model): name = models.CharField(max_length=30) class Membership(models.Model): pizza= models.ForeignKey(Pizza, on_delete=models.CASCADE) topping = models.ForeignKey(Topping, on_delete=models.CASCADE) amount = models.IntegerField() -
Celery Beat acknowledging a task, running it but not executing it
The problem is I get the following log: celery_1 | [2021-03-15 19:00:00,124: INFO/MainProcess] Scheduler: Sending due task read_dof (api.tasks.read_dof) celery_1 | [2021-03-15 19:00:00,140: INFO/MainProcess] Scheduler: Sending due task read_bdm (api.tasks.read_bdm) celery_1 | [2021-03-15 19:00:00,141: INFO/MainProcess] Scheduler: Sending due task read_fixer (api.tasks.read_fixer) I have the following configuration for celery. Exchange is the name of my django project, which is where "celery.py" is and api is the name of my django app which is where my "tasks.py" is: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "exchange.settings") app = Celery("exchange") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() app.conf.beat_schedule = { 'read_bdm': { 'task': 'api.tasks.read_bdm', 'schedule': crontab(hour=19,minute=0), }, 'read_dof': { 'task': 'api.tasks.read_dof', 'schedule': crontab(hour=19,minute=0), }, 'read_fixer': { 'task': 'api.tasks.read_fixer', 'schedule': crontab(hour=19,minute=0), }, } Here is my tasks.py: from celery import shared_task from .models import BdmExch, DofExch, FixerExch from .helpers.bdmcrawler import parse_bdm from .helpers.dofcrawler import parse_dof from .helpers.fixercrawler import parse_fixer @shared_task(name='read_bdm') def read_bdm(): attempts=0 while attempts <3: try: result = parse_bdm() print(result) BdmExch.objects.create(time=result["date"],exch=result["exc"]) return except: attempts += 1 print("Parsing error on read_bdm") print("--------------- Parsing error on read_bdm -----------") return @shared_task(name='read_dof') def read_dof(): attempts=0 while attempts < 3: try: result = parse_dof() DofExch.objects.create(time=result["date"],exch=result["exc"]) return except: attempts += 1 print("Parsing error on … -
How to make textarea to return value?
I want to make a textarea for my website and this textarea going to return a processed value. For example, The user enters the sentence: "Anna has a great car!" the output should be represented sentence's statement. (Positive, negative or the keywords etc.) But for more information, I'm only working on this website's frontend part. So, how can I design this in HTML, CSS & JS? On the server-side, we are using Django, MongoDB and SQLite. -
Is it possible to run django migrations within a python script?
I have a django application, let's call it django_app and I can pip install django_app to get it installed. But I still need to run the migrations for this app. For one reason or another, the team's required to run the migrations within a python script. Is it possible to run the migrations within the another python script if the django application is installed via a pip command? -
How can i update django form's integerField max_value validator by giving input integer value?
I am developing a warehouse management and i want to warn if the admin gives number more than warehouse holds for a specific object. I am using crispy form by the way. -
Flask tensorflow parallel computing multiple requests
By basic calculation let's say if a python script takes 1 second to run for each user, if the script runs in a queue and the number of users is just 1000 it will take 1000 seconds(16.6 min) for the 1000th user to get their response. as my "python script" is taking almost that long, Is there any way to make it possible in Flask and/or Django for all users to get their responses in parallel? Image for better understanding the problem: Load balance in Django and/or flask thank you in advance. -
Django DFR TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use answers.set() instead
I have problem with creating model by serializers. When i using this data: data = { 'name':'Quiz12', 'questions':[ {'question_text': 'Kim jestem?', 'answers': [ {'answer_text': 1, 'correct':False}, {'answer_text': 2, 'correct':False}, {'answer_text': 3, 'correct':True}, ], }, ], } I getting error. When I create only a question using QuestionSerializer everything works good. serializers.py class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ['answer_text','correct'] class QuestionSerializer(serializers.ModelSerializer): answers = AnswerSerializer(many=True) class Meta: model = Question fields = ['question_text', 'answers'] def create(self, validated_data): answers_data = validated_data.pop('answers') question = Question.objects.create(**validated_data) for answer_data in answers_data: a1 = Answer.objects.create(question=question, **answer_data) question.answers.add(a1) return question class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) class Meta: model = Quiz fields = ['name', 'questions'] def create(self, validated_data): questions_data = validated_data.pop('questions') quiz = Quiz.objects.create(**validated_data) for question_data in questions_data: Question.objects.create(quiz=quiz, **question_data) return quiz models.py class Profile(models.Model): user = models.OneToOneField(User, null=True,on_delete=models.CASCADE) def __str__(self): return self.user.username class Quiz(models.Model): owner = models.OneToOneField(Profile,blank=True, null=True,on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=True) date = models.DateTimeField(auto_now_add=True) questions = models.ManyToManyField("Question", related_name="Question1", blank=True, null=True) students = models.ManyToManyField("Profile", related_name="+", blank=True, null=True) def __str__(self): return str(self.name) class Question(models.Model): quiz = models.ForeignKey("Quiz", null=True, on_delete=models.CASCADE) question_text = models.CharField(max_length=500, default="Pytanie") answers = models.ManyToManyField("Answer", related_name="+", blank=True, null=True) def __str__(self): return str(self.question_text) class Answer(models.Model): answer_text = models.CharField(max_length=500, default="Odpowiedź") correct = models.BooleanField(default=False) question = models.ForeignKey("Question", null=True,on_delete=models.CASCADE) … -
how to solve error "'NoneType' object has no attribute 'day'" in django application
I noticed this error in my application, "'NoneType' object has no attribute 'day'". What I have noticed about it is that. I have a model named course_schedule, the course schedule has an option of Monday to Sunday. If the course schedule is partially populated, that is I populate only some days, like 3 days out of the complete 7 days in a week, I get the error but whenever I populate the course schedule populate course schedule model completely, I don't have the error and everything works well. error log: Traceback (most recent call last): File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\sms\schoolapp\views.py", line 1754, in sir_course get_all = getall(2021, sch.day) Exception Type: AttributeError at /en/sir_course Exception Value: 'NoneType' object has no attribute 'day' models.py class Assign_teacher_to_courses(models.Model): Course_Name = models.ForeignKey(add_courses, on_delete=models.CASCADE) Teacher_Name = models.ForeignKey(add_teacher_by_manager, on_delete=models.CASCADE) def __str__(self): return self.Course_Name.Course_Name+" - "+self.Teacher_Name.teacher_ID+" - "+self.Teacher_Name.teacher_name class course_schedule(models.Model): days_choices = ( ("Mon", 'Monday'), ("Tue", 'Tuesday'), ('Wed', "Wednessday"), ('Thurs', "Thursday"), ('Fri', "Friday"), ('Sat', "Saturday"), ("Sun", "Sunday"), ) day = models.CharField(max_length=60, default="Sun") time_session = models.CharField(max_length=150, default='8:00am') end_session = models.CharField(max_length=150, default='10:00am') def __str__(self): return self.day views.py def sir_course(request): if request.method == "POST": … -
django.db.utils.OperationalError: no such column: app_commenti.sondaggio_id
i'm trying to do a school project, in this school project i would like to create an application using django, this application must allow to create pools, the users can vote and comment. i created the models, i made the migration and i did the migrate command. everething worked fine, but when i tried to add another foreignkey in 'Commenti' class django gave me problems. now the make migrations command work fine but when i try to do make migrate command the program goes into error.enter image description here -
Django-tables2 - can I pass a queryset filtered using values_list() and distinct() to my table?
I'm trying to pass a queryset to my table, but I want unique values for a set of fields. How can I use values_list().distinct() to obtain unique values for my fields, and pass this to the queryset of django-tables2? tables.py class JobTaxonLocationTable(tables.Table): result1 = tables.Column( accessor='JobResult.result1', verbose_name='Result1') result2 = tables.Column( accessor='JobResult.result2', verbose_name='Result2') class ViewJob(LoginRequiredMixin, SingleTableView): model = Model1 table_class = MyTable def get_table_data(self, **kwargs): """ ViewJob get_table_data request """ print('>get_table_data') # get job_obj from kwargs job_obj = Job.objects.get(pk=self.kwargs.get('pk')) if job_obj: self.object_list = self.object_list.filter(job_id=job_obj) # *at this point I want to restrain my object_list on unique values of result1, result2 - but self.object_list = self.object_list.values_list( "result_id__result1", "result_id__result2", ).distinct() return self.object_list else: return MyTable.objects.none() The self.object_list is now a values_list queryset so no data is now passed to django-tables2 table. Is there a way I can do this? -
Attribute Error: str object - has no attribute days. Attempting to migrate my model
Have two models that I am attempting to override the save functions (parent and Child). the models look like this: from django.db import models from django.urls import reverse from datetime import datetime, timedelta class Program(models.Model): air_date = models.DateField(default="0000-00-00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) block_time = models.TimeField(default="00:00:00") block_time_delta = models.DurationField(default="00:00:00") running_time = models.TimeField(default="00:00:00") running_time_delta = models.DurationField(default="00:00:00") remaining_time = models.TimeField(default="00:00:00") remaining_time_delta = models.DurationField(default="00:00:00") title = models.CharField(max_length=190) locked_flag = models.BooleanField(default=False) deleted_flag = models.BooleanField(default=False) library = models.CharField(null=True,max_length=190,blank=True) mc = models.CharField(null=True,max_length=64) producer = models.CharField(null=True,max_length=64) editor = models.CharField(null=True,max_length=64) remarks = models.TextField(null=True,blank=True) audit_time = models.DateTimeField(null=True) audit_user = models.CharField(null=True,max_length=32) def calculate_time(self): total_run_time_delta = timedelta(minutes=0) hold_remaining_delta = models.DurationField() for segs in self.segments.all(): total_run_time_delta += segs.length_time_delta self.running_time_delta = total_run_time_delta self.running_time = f"{self.running_time_delta}" self.remaining_time_delta = self.block_time_delta - total_run_time_delta self.remaining_time = f"{abs(self.remaining_time_delta)}" def save(self, *args, **kwargs): self.calculate_time() super().save(*args,**kwargs) def __str__(self): return f"{self.pk} : {self.title}" def get_absolute_url(self): return reverse('program_detail', args=[str(self.id)]) #return reverse('program-update', kwargs={'pk': self.pk}) class Segment(models.Model): program_id = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', #new link to Program ) sequence_number = models.DecimalField(decimal_places=2,max_digits=6,default="0.00") title = models.CharField(max_length=190) bridge_flag = models.BooleanField(default=False) length_time = models.TimeField(null=True,default=None, blank=True) author = models.CharField(max_length=64,null=True,default=None,blank=True) voice = models.CharField(max_length=64,null=True,default=None,blank=True) library = models.CharField(max_length=190,null=True,default=None,blank=True) summary = models.TextField() audit_time = models.DateTimeField(null=True) audit_user = models.CharField(null=True,max_length=32) def save( self, *args, **kwargs): program = Program.object.get(id=self.program_id) super().save(*args,**kwargs) program.save() def __str__(self): return self.author After … -
render() missing 1 required positional argument: 'data'
My Serialization Code enter image description here