Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i use prefetch_related in self related model
Hi i have Menu model which has ForeignKey named parent related with itself. If parent is None it means this menu is parent menu if it shows another Menu object it means it is submenu for its parent(many-to-one relation) Here is my problem i want to get all menus with its submenus using prefetch_related but i can not get it. How can i do it? Note: I do not want to get submenus going database each time in for menu Here is my model class; class Menu(models.Model): title = models.CharField(max_length=30) language = models.ForeignKey(Language) parent = models.ForeignKey("self", default=None, blank=True, null=True) href = models.CharField(max_length=255, default="#") menutype = models.CharField(max_length=50, default="gui") icon = models.CharField(max_length=100, default="chevron-right") order = models.IntegerField(default=0) target = models.CharField(max_length=50, default="_self") Here is my query; pm2 = Menu.objects.filter(parent=None, language__code=language, menutype=menutype).prefetch_related("submenus").order_by("order") for p in pm2: print(p.title) print(p.submenus) in here when i print the submenus the result is app.Menu.None -
In a Django ModelForm, how do I accept a datetime string that has milliseconds?
In a Django ModelForm's DateTimeField I want to have an input_format that accepts a datetime with milliseconds. e.g. '2018-02-26T14:46:15.704Z'. But strftime only has %f for microseconds. How do I add an input_format for to cope with this format? My field so far: class MyModelForm(forms.ModelForm): my_time = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ',]) This will match: '2018-02-26T14:46:15.000704Z' but not: '2018-02-26T14:46:15.704Z' -
Modify nginx config to reverse proxy websockets properly
Current nginx config: server { listen 443 ssl http2; server_name NAME www.NAME; charset utf-8; ssl on; ssl_certificate /etc/nginx/ssl/NAME-cert.pem; ssl_certificate_key /etc/nginx/ssl/NAME-key.pem; location /static/ { alias /home/ubuntu/NAME/static_collection/; } location /media/ { alias /home/ubuntu/NAME/media_collection/; } location / { proxy_pass http://localhost:8002; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Everything works, apart from the websockets. I suppose this is because it doesn't deal with the http upgrade header... I've looked at the docs, but I can't figure out how to modify this config without breaking anything else. -
How to implement app marketplace in Django Rest framework?
I have a CRM product built on top of DRF and I want to provide my users an option to install add-ons to perform some additional tasks like sending bulk email using mailchimp etc. ; something like Slack app directory. Are there any built-in libraries available for this? If not, what is the best way to implement this? -
how do i link a field to a multi valued field in django model
This model Profile has different information about user and also a field called quiz which is a ManytoMany field. This field shows the quizes the user has registered for. I want the total_score field to store score user obtained in each quiz he participated. How do i do it? class Profile(models.Model): user=models.OneToOneField(User,related_name='Profile', on_delete=models.CASCADE) college=models.CharField(max_length=200) phone=models.IntegerField(blank=True,default=0) quiz=models.ManyToManyField(Quiz) total_score=models.IntegerField(default=0) def __str__(self): return self.user.username -
Generate input fields based on a input and store it properly
I have a field called subjects that asks users how many subjects do they have and based on the number they input I want to generate the input fields of same number. And How and where do I store those inputs. MODELS.PY #this field will determine how many input fields to generate subjects = models.IntegerField() VIEWS.PY def generate_forms(request): no_of_fields = request.GET.get('subjects') if no_of_fields: #generate other inupts #save it in the database Besides generating the input, how do I save those data in the database. Thanks in advance -
Need some guidance on running a finished project
Million Songs Dataset So, I was initially trying to run this project on my local machine, since the requirements are not specified in this project, I guessed what all tools were required. I can see that Django, MongoDB and Hadoop are required (additional tools maybe required). So I installed Django and generally Django projects have a "manage.py" file, which this project does not contain. I am also unable to determine which version of Django was used since this project was created over 4 years ago. So if anyone could point me in the direction which I am supposed to go, it would be very helpful. Thanks in advance. -
Setting form fields in django class based generic view CreateView
I'm using django's CreateView to add images to a book. I pass the book's id to the class based view as a parameter in the url. Form fields such as book and language are not rendered on the template, rather they're obtained with the help of the book's id. # views.py class PictureCreateView(CreateView): model = Upload fields = "__all__" book_id = None def get_initial(self): initial = super(PictureCreateView, self).get_initial() initial = initial.copy() self.book_id = self.kwargs['book_id'] book = Book.objects.get(id=self.book_id) initial['book'] = book initial['language'] = language initial['uploader'] = self.request.user return initial # set book_id so it used in the template def get_context_data(self, **kwargs): context = super(PictureCreateView, self).get_context_data(**kwargs) context['book_id'] = self.book_id return context def form_valid(self, form, **kwargs): print('Form is valid') self.object = form.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return super(PictureCreateView, self).form_valid(form) def form_invalid(self, form): print('Form invalid!') print(form.errors) data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') # models.py class Upload(models.Model): image = models.ImageField(upload_to=get_upload_path, help_text='Image to process') uploader = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='uploader') language = models.ForeignKey(Language, models.CASCADE) book = models.ForeignKey(Book, models.CASCADE) The problem is that I get an error saying the form is invalid, and the fields uploader, book and language are required. How do I resolve this? -
Django model from multiple databes tables
I want to ask if there is a convenient way that allows me to create a django model from multiple tables. I am looking for solution, that can be written in similar way: class ClientTeamContacts(models.Model): attribute_1 = models.CharField(db_column='ss',db_table = 'xxx') attribute_2 = models.CharField(db_column='cc',db_table = 'yyy') I will be thankful for every suggestion that can provide some solution. -
Django: Joining on fields other than IDs (Using a date field in one model to pull data from a second model)
I'm attempting to use Django to build a simple website. I have a set of blog posts that have a date field attached to indicate the day they were published. I have a table that contains a list of dates and temperatures. On each post, I would like to display the temperature on the day it was published. The two models are as follows: class Post(models.Model): title = models.CharField(max_length=200) text = models.TextField() date = models.DateField() class Temperature(models.Model): date = models.DateField() temperature = models.IntegerField() I would like to be able to reference the temperature field from the second table using the date field from the first. Is this possible? In SQL, this is a simple query. I would do the following: Select temperature from Temperature t join Post p on t.date = p.date I think I really have two questions: Is it possible to brute force this, even if it's not best practice? I've googled a lot and tried using raw sql and objects.extra, but can't get them to do what I want. I'm also wary of relying on them for the long haul. Since this seems to be a simple task, it seems likely that I'm overcomplicating it by having … -
Django ORM: Copying a translation field from one model to another issues an error
I have the following model: class AModel(TranslatableModel): ...... other fields definitions ...... translations = TranslatedFields( name=models.CharField(max_length=100, blank=False, default=''), description=models.CharField(max_length=500, blank=True, null=True) ) I have two instances of that model: "source" and "destination". When I try to copy translatable field from the source to the destination: destination.name = source.name An exception appears: NoTranslationError: Accessing a translated field requires that the instance has a translation loaded, or a valid translation in current language (en-us) loadable from the database Is there anyway to handle that? My configuration is: django-hvad==1.7.0 Django==1.8.8 -
How to create django queryset by reusing model instances and not performing additional DB query?
In my project I have the following setup. It has Project and EntryStatus models. Each project has it's own set of Statuses. When user creates a new Project, then I have to create default statuses for this project. Here is the code for my model manager. class EntryStatusManager(models.Manager): def create_default_for_project(self, project: Project): for status in self.get_queryset().filter(project=None): status.id = None status.project = project status.save() I want to return a queryset from this method that will contain all of the created statuses. The easiest solution is to make additional query like this def create_default_for_project(self, project: Project): created_ids = [] for status in self.get_queryset().filter(project=None): status.id = None status.project = project status.save() created_ids.append(status.id) return self.get_queryset().filter(id__in=created_ids) But is there any way to avoid making additional query and simply reuse created model instances? -
Not able to retrieve primary field : Django
I am trying to retrieve an integer field which is primary in the jquery success call back Below is my Model class PostEntry(models.Model): last_name = models.CharField(max_length=20) first_name = models.CharField(max_length=20) id = models.IntegerField(editable=False, primary_key=True) def __unicode__(self): return 'Entryid=' + str(self.id) + ',text="' + self.post_content + '"' JQuery success callback shows all field expect id field, AM I missing anything? -
Django: Removing unique constraint and creating migration
I have created a model and migrated in Django with a unique key constraint in one of the colom. Now am trying to remove the constraint and generate another migration file with the new change, but it says "Nothing seems to have changed". I tried with the command python manage.py schemamigration --auto -
How to store per-user data in django permanently and efficiently
I am working on a websie in django about books, where you can post reviews, rate the books etc... I'd like to know how to store data about every user in an efficient way, as to know whether the user: Has already posted a review for a specific book Has already rated a book This way, no user could post 2 reviews and I could provide a per-user experience. I even want to limit how many times they can rate (like 3 every month). Problems: Sessions do not seem useful since the data is not stored in the db and once the user exits and reenters the page, the session is gone (I checked the django docs but the example doesn't seem useful for me). I thought about adding dicts or lists in every instance of the model, and storing there all the necessary data, but I don't know whether it is appropriate/efficient Thank you very much for your time, I hope someone knows it! -
Unit Testing Django Model Save Function
I'm creating tests to check that a custom calibration model save function updates an asset record (foreign key) if it is the latest calibration record for the asset. The save function performs exactly as expected in live dev & production server and even in the django shell, but appears to fail during testing... models.py class Asset(models.Model): ... requires_calibration = models.BooleanField() passed_calibration = models.BooleanField(default=False) calibration_date_prev = models.DateField(null=True, blank=True) calibration_date_next = models.DateField(null=True, blank=True) class CalibrationRecord(models.Model): calibration_record_id = models.AutoField(primary_key=True) asset = models.ForeignKey( "myapp.Asset", on_delete=models.CASCADE, limit_choices_to={"requires_calibration": True} ) calibration_date = models.DateField(default=timezone.now) calibration_date_next = models.DateField(null=True, blank=True) calibration_outcome = models.CharField(max_length=10, default="Pass") def save(self, *args, **kwargs): super(CalibrationRecord, self).save(*args, **kwargs) # Check if this is the latest calibration record for any asset, if so update asset.calibration_dates and status latest_asset_calibration = CalibrationRecord.objects.filter(asset=self.asset.pk).order_by( "-calibration_date", "-calibration_record_id")[0] if self.pk == latest_asset_calibration.pk: Asset.objects.filter(pk=self.asset.pk).update(calibration_date_prev=self.calibration_date) if self.calibration_date_next: Asset.objects.filter(pk=self.asset.pk).update(calibration_date_next=self.calibration_date_next) else: Asset.objects.filter(pk=self.asset.pk).update(calibration_date_next=None) if self.calibration_outcome == "Pass": Asset.objects.filter(pk=self.asset.pk).update(passed_calibration=True) else: Asset.objects.filter(pk=self.asset.pk).update(passed_calibration=False) tests_models.py example failing test class CalibrationRecordTests(TestCase): def test_calibration_record_updates_asset_cal_date_prev(self): """ All calibration records should update related Asset record's "calibration_date_prev" to calibration_date """ asset1 = Asset.objects.create(asset_description="Test Asset 2", requires_calibration=True) self.assertIsNone(asset1.calibration_date_prev) cal = CalibrationRecord.objects.create(asset=asset1, calibration_description="Test Calibration 2", calibration_date=timezone.now()) self.assertEqual(cal.calibration_date, asset1.calibration_date_prev) Error log ====================================================================== FAIL: test_calibration_record_updates_asset_cal_date_prev (assetregister.tests_models.CalibrationRecordTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\[path]\app\tests_models.py", line 159, in test_calibration_record_u pdates_asset_cal_date_prev self.assertEqual(cal.calibration_date, asset1.calibration_date_prev) … -
Django - perform a prefetch on a select related?
Is it possible to perform a prefetch on a select related query? in my view as an example below, I have a mapping table where I get all the circuits related to a site and then prefetch circuit fields. however I would also like to get circuit maintenances... the circuitmaintenance model has a foreign key to circuits only so I need something like select related circuit, then prefetch circuit maintenance in circuit, I tried just doing .prefetch_related('circuit_maintenance') \ but this gave an error due to model inheritance this is my current view: site_circuits = SiteCircuits.objects.filter(site_id=site_id) \ .exclude(circuit__decommissioned=True) \ .select_related('site') \ .select_related('circuit') \ .prefetch_related('circuit__circuit_type') \ .prefetch_related('circuit__circuitfiles') \ .prefetch_related('circuit__circuitnotes') \ .prefetch_related('circuit__provider') \ .prefetch_related('circuit__service_contacts') \ .prefetch_related('circuit__circuit_type') \ -
maximum recursion depth exceeded - Pycharm, Django, Python3
im quite new to python and im currently writing myself a blog application but i got stuck a some point. currently im facing the following error: ':'.join(parents + (url.namespace,)) for url in url_patterns RecursionError: maximum recursion depth exceeded i got two urls.py files. one at /mysite and the next one at /mysite/myapp /mysite/urls.py: from django.conf.urls import url from quickblog import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), ] /mysite/myapp/urls.py: from django.conf.urls import include from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('quickblog.urls')), ] mysite/myapp/models.py: from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title /mysite/myapp/admin.py: from django.contrib import admin from .models import Post admin.site.register(Post) I guess i'm simply doing something wrong here. Any hint would be nice :D Thank you guys -
PDF output using Weasyprint not showing images (Django)
I am trying to output PDF on Django using the Weasyprint library, but the images don't appear on the generated PDF. I have tried both relative and static URLs for the images, but even the static URL doesn't show the image. When opening the HTML itself on chrome, the images do show. Here is my pdf generation view in the views.py file: def pdf_generation(request, some_slug) stud = Student.objects.get(some_slug=some_slug) studid = stud.some_slug context = {'studid':studid} html_string = render_to_string('templates/pdf_gen.html', context) html = HTML(string=html_string) pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/detail_pdf_gen.css')]); response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="mypdf.pdf"' return response Here is the part of the HTML of the image: <DIV id="p1dimg1"> <IMG src="{% static 'img/wells.jpg' %}" alt=""> </DIV> And the CSS: #page_1 #p1dimg1 {position:absolute;top:0px;left:0px;z- index:-1;width:792px;height:1111px;} #page_1 #p1dimg1 #p1img1 {width:792px;height:1111px;} Thank you very much -
What to do when django cannot start?
I am trying to deploy django with nginx and uwsgi. Nothing works on socket. I tried to change privileges but fruitless. Err_connection_refused. In error.log nothing. How can I solve this problem? -
Development using different version of Python
I'm developing a website using a server with Debian 8.10 (Jessie) as its OS and Python 3.4.2 (the supported Python version for Debian Jessie) while my notebook is using Ubuntu 16.04 and Python 3.5.2 (I think it's also the default version for Ubuntu 16.04). I was planning to build my website using Django 1.11 which both Python versions (3.4 and 3.5) support. Is there any compatibility issues when I develop it using my Python 3.5.2 and deploy it to a Python 3.4.2 server? If any, how much the trouble it will be? I know I can install any version of Python by adding someone's repository, but it seems unofficial so I avoid doing it. And there is a workaround that come to my mind: intall a specific version of Python by download its tarball file from the official website Which will you recommend most? Upgrade my server's Python version to 3.5.2 by adding someone's repo Download Python 3.4.2's tarball and install it to my local machine Upgrade my server's OS to Debian 9 Stretch which its default Python version is 3.5.3 Or any other better idea? Or perhaps you have a way to install specific Python version? *I have some … -
ho to go in depth of data base using django rest framework
i want to build api for company like API/companies_list/ API/companies_list/{id of particular company}/ API/companies_list/{id of particular company}/departments_list/ . . . API/companies_list/{id of particular company}/departments_list/{id_of particular department}/employees_list/{employee id} can any one suggest what approach to use, i came across detail router and list router but the explanation seems not satisfying. my model has employee is child of department, department is child of company. in my present api model i have used viewsets for department, employee, company, but i am having the urls like API/companies_list/ API/companies_list/{id of particular company}/ API/departments_list/ API/departments_list/{id} API/employee_list/ API/employee_list/{id} due to this structure grouping is difficult. Thank you in advance. -
TypeError at postStream↵'bool' object is not iterable↵↵Request Method: POST↵Request
I have below code that is expected to return top 1 record where id > jquery posted value. def postStream(request): post = PostEntry.objects.filter(id > request.POST['maxpostid'])[:1] response_text = serializers.serialize('json', [post,]) return HttpResponse(request.POST['maxpostid'], content_type='application/json') Due to some reason, it gives below error. TypeError at postStream↵'bool' object is not iterable↵↵Request Method: POST↵Request I can confirm that request.POST['maxpostid'] is giving expected value. Am I doing anything wrong? -
Constantly need to reset django local settings module
I have made two settings files, one for local testing and one for production (heroku). Every time I pull and start working locally I need to run the following two commands for it to work: export DJANGO_SETTINGS_MODULE= DJANGO_SETTINGS_MODULE=projectName.settings_local Without doing so I get the error that the local settings module cannot be found. This error appeared after I tried to have both settings files in a settings folder, which I did not get to work so I put them back in the original place. Does anyone have an idea how I can fix this? -
Get vimeo video info (Python) --- Different responses on Developers API and POSTMAN
When I make authorized call to Developer API to get video info for a specific video then I get response: { ... "files": [ ... ... { "quality": "hd", "type": "video/mp4", "width": 1280, "height": 720, "link": "LINK", "created_time": "Time", "fps": value, "size": size, "md5": "value", "link_secure": "link_source" }, ... ... ], "download": [ ... ... { "quality": "source", "type": "source", "width": 1920, "height": 1080, "expires": "time", "link": "link", "created_time": "time", "fps": value, "size": size, "md5": "value" }, ... ... ] } I am using Pyvimeo==0.3.2 and Pyvimeo==1.0.0 for Vimeo. But when I hit "https://api.vimeo.com/videos/{vimeo_id}" (with Client_id and Authorization) from my server or from POSTMAN then I get only: { ... "download": [ ... { "quality": "source", "type": "source", "width": 1920, "height": 1080, "expires": "time", "link": "link", "created_time": "time", "fps": value, "size": size, "md5": "value" }, ... ] ... } There is not key "files" in API response. Why I am not getting "files" key in video response ? There is no any such update in API docs.