Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Writing django validators. Do i need a own file for validators?
In the Django Manuel is an example for Writing validators. https://docs.djangoproject.com/en/2.2/ref/validators/ qoute For example, here’s a validator that only allows even numbers: from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_even(value): if value % 2 != 0: raise ValidationError( _('%(value)s is not an even number'), params={'value': value}, ) You can add this to a model field via the field’s validators argument: > from django.db import models > > class MyModel(models.Model): > even_field = models.IntegerField(validators=[validate_even]) qoute end But where should i put this code? from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_even(value): if value % 2 != 0: raise ValidationError( _('%(value)s is not an even number'), params={'value': value}, ) should i create a own File like validator.py or should i put this in the model? -
How to save a fileField's path without writing the file itself to reflect an external change
I have a model that includes a FileField, the path to which I want to update without writing the file itself via the storage system. Usually the file would be saved from a form upload, but when the file location is updated externally, I don't want to re-write the file in order to update the DB entry. I've tried to use the field's.save() method, but that requires the file's content to be supplied. I'd want to only change the related DB entry so that the storage system can find the file again. -
'NoneType' object has no attribute 'seventh_five' despite the existence of the object
I am creating a website where a user can create a project. Each project has 10 macro-questions. Each macro-question has sub-questions. I am trying to retrieve the answer to a macro-question. projects_id contains all the projects in my database. for project_id in projects_id: seventh_question_project = Seventhquestion.objects.all().filter(project=project_id).first() answer_seventh_five = seventh_question_project.seventh_five if answer_seventh_five == "No": unaudited_projects.append(answer_seventh_five) else: audited_projects.append(answer_seventh_five) If I use the console, I am able to retrieve answer_seventh_five: however, if load the page, I get: 'NoneType' object has no attribute 'seventh_five' Which I cannot explain since answer_seventh_five exists (as I tested it by retrieving it via console) -
Make api calls inside Serializer create vs ModelViewSet create
I have this API end point, see below: from django.contrib import admin from django.urls import path, include from rest_framework.routers import DefaultRouter from wish_list.views import WishListViewSet router = DefaultRouter() router.register('wish-list', WishListViewSet, base_name='wish-list') urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), ] My goal is to receive data from a POST request and use this data to make an API call and save these data(title and isbn_13) into my WishList object. This is my views.py import json import requests from django.core import serializers from rest_framework import status from rest_framework import viewsets from rest_framework.response import Response from .models import WishList from .serializers import WishListSerializer class WishListViewSet(viewsets.ModelViewSet): serializer_class = WishListSerializer queryset = WishList.objects.all() http_method_names = ['get', 'post', 'delete', 'head'] def create(self, request, *args, **kwargs): ol_id = request.data.get('ol_id') try: wish_list_obj = WishList.objects.get(ol_id=ol_id) except WishList.DoesNotExist: return super(WishListViewSet, self).create( request, *args, **kwargs ) return Response(serializers.serialize('python', [wish_list_obj, ]), status.HTTP_200_OK) def perform_create(self, serializer): try: response = self._open_library_book_response( serializer.validated_data.get('ol_id')) except requests.exceptions.RequestException: return Response( { 'Error Message': "Could not get a valid response " "from Open library's Book API" }, status=status.HTTP_503_SERVICE_UNAVAILABLE ) parsed_response = self._parse_response(response) serializer.save( title=parsed_response.get('title'), isbn_13=parsed_response.get('isbn_13'), ) @staticmethod def _open_library_book_response(ol_id: str) -> requests.models.Response: """ Make request to open library to get the details of a specific book. """ open_library_url = … -
Why does my url return data sometimes and return error 404 not found others?
I have a django website, I have multiple INSTALLED_APPS listed in the settings.py. One being the app that I am having trouble with. This app loads properly sometimes, but randomly it returns with a 404 error. I also have an ajax call from the app which also will go to the server and get the json data sometimes but even a second later when i try again it returns a 404 error. If i run it again it will usually return the json data, but sometimes again the 404 error. There is no difference in the call to the server that returns the data or the 404 error. I can see in the debug of the 404 error response that it says "Using the URLconf defined in website.urls, Django tried these URL patterns, in this order:" and the app path is not listed in the patterns but the other installed apps are. Of course the times it works the path must be listed. It seems to fail approximately 25% of the calls. Is there something that is cached in django that reverts the URLconf to an earlier version that doesn't include the new installed app randomly? Any suggestions are welcome, … -
media files saved manually not showing ?Saving images in image fields manually and showing them in deployment?
I have a Django app where users can upload images and can have a processed version of the images if they want. and the processing function returns the path, so my approach was model2.processed_image = processingfunction( model1.uploaded_image.path) and as the processing function returns path here's how it looks in my admin view not like the normally uploaded images In my machine it worked correctly and I always get a 404 error for the processed ones while the normally uploaded is shown correctly when I try change the url of the processed from myurl.com/media/home/ubuntu/Eyelizer/media/path/to/the/image to myurl.com/media/path/to/the/image so how can i fix this ? is there a better approach to saving the images manually to the database ? I have the same function but returns a Pil.image.image object and I've tried many methods to save it in a model but i didn't know how so I've made the function return a file path. -
Django HTML-Template media links are not being served
I have a django app with which I try to serve a prebuilt html template from my python app. I can access the template, but the total layout etc. is corrupted because all src="" links are pointing to a django 404 page. My app: --> http://127.0.0.1:8000/dashboard/ (WORKS) Example media link: --> http://127.0.0.1:8000/dashboard/assets/images/avatars/1.jpg (NOT WORKING) This is my views.py: from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, 'templates/name/index.html') How can it be accomplished that django serves the complete folder with all files in it and not only the index.html page? -
Scrapy imports really slow
I am trying to use Scrapy but the setup time is really slow. start_time = time.time() from scrapy.spiders import SitemapSpider from scrapy.utils.sitemap import Sitemap, sitemap_urls_from_robots from scrapy.http import Request from scrapy.linkextractors import LinkExtractor print('Completed imports. Total time: ' + str(time.time() - start_time)) # Completed imports. Total time: 5.819392919540405 Why is this so slow? Has Scrapy cached data somewhere that it's loading each time it starts up? -
How to template tag for @property in django
I defined field in air with @property. this is my @property field: @property def points(self): if self.pk: return self.questions.all().aggregate(Sum('point'))['point__sum'] else: return 0 Then I create template tag for verbose_name in django template: from django import template register = template.Library() @register.simple_tag def verbose_name(instance, field_name): """ Returns verbose_name for a field. """ return instance._meta.get_field(field_name).verbose_name.title() When I use : {% verbose_name exam "prices" %} raise this error: Exam has no field named 'prices' How can I define verbose_name for @property and then use template tag for show verbose_name of this `@property? -
LocaleMiddleware not selecting requested available language
I am having trouble making django.middleware.locale.LocaleMiddleware set Chinese language as per the cookies/header I specify in the request. After some debugging, I have narrowed it down to the the following function, which rejects it django.utils.translations.trans_real.check_for_language all_locale_paths returns only django's locales, which do not contain 'cn'. My apps are packaged and installed separately from the project itself, and they provide their own 'cn' language files, which get discovered successfully, but since their locale directories are not specified in LOCALE_PATHS, the middleware does not check them. What is the best approach to avoid this problem? I am not adding the LOCALE_PATHS, as the app locations differ based on the different environments the project is deployed. I could import the app, and find the paths from it, but that seems like an overkill. -
Do Django aggregate functions use indexes?
I have a django model with a huge number of instances (rows) in the database (Postgres). Then I'm aggregating a decimal field of the model and averaging it. My question is, would it speed up the aggregation process to set and index for that field? Example of what I'm doing: class Blog(models.Model): name = models.CharField(max_length=10) lines_per_page = models.DecimalField() Blog.objects.all().aggregate(x=Avg('lines_per_page'))[x] Would then make the following change improve the aggregation? class Blog(models.Model): name = models.CharField(max_length=10) lines_per_page = models.DecimalField(db_index=True) Blog.objects.all().aggregate(x=Avg('lines_per_page'))[x] As I said my database is huge, only the table of the model I'm working with occupies ~6GB. -
No name 'path' in module 'django.urls'
I'm trying to set up a Django project using AWS Cloud9 - this is the first time I have used Cloud9 since it moved to AWS, although I had used it for projects previously. I thought I had created the project with no problems, but I am getting a error in urls.py relating to the import of 'path' from django.urls. I am using a virtual environment with Python 3.6.8 and Django 2.2.4, but currently I cannot run the project because of this error. On a previous Cloud9 based project, I was using Django 2.1 with Python 3.6 and had no errors with this code. This is all that is currently in urls.py: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] Trying to run the project, I get this error: Traceback (most recent call last): File "/home/ec2-user/environment/project/urls.py", line 17, in <module> from django.urls import path ImportError: cannot import name path -
How to reformat a date from an api
i am trying to get data from a weather api and save in my database using django, and whenever i want to send the date from the api to the database i get an error related to the format of the data. Django datefield expects 'YYYY-MM-DD' format. this is my models.py class Weather_data(models.Model): date = models.DateField(blank=True, null=False) min_temp = models.IntegerField(default=0) max_temp = models.IntegerField(default=0) wind = models.IntegerField(default=0) rain = models.CharField(max_length=10, null=True) def __str__(self): return self.id this is my views.py def index(request): url = "http://weather.news24.com/ajaxpro/Weather.Code.Ajax,Weather.ashx" headers = {'Content-Type': 'text/plain; charset=UTF-8', 'Host': 'weather.news24.com', 'Origin': 'http://weather.news24.com', 'Referer': 'http://weather.news24.com/sa/capetown', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36', 'X-AjaxPro-Method': 'GetForecast7Day'} payload = {"cityId": "77107"} r = requests.post(url, headers=headers, data=json.dumps(payload)) weather_data = r.json() print(weather_data) for i in range(0, 7): api_data = { 'date': weather_data['value']['Forecasts'][i]['Date'], 'min_temp': weather_data['value']['Forecasts'][i]['LowTemp'], 'max_temp': weather_data['value']['Forecasts'][i]['HighTemp'], 'wind': weather_data['value']['Forecasts'][i]['WindSpeed'], 'rain': weather_data['value']['Forecasts'][i]['Rainfall'], } Weather_data.objects.create(**api_data) context = { 'objects': Weather_data.objects.all() } return render(requests, 'weather_app/index.html', context) i am expecting to get the date in 'YYYY-MM-DD' format but the date that i have from the api is '/Date(1565301600000)/' format, i am not sure on how to reformat this date into django datefield(YYYY-MM-DD). the error that i get is this: django.core.exceptions.ValidationError: ["'/Date(1565301600000)/' value has … -
Why images can't upload them with a django2 form?
I'm trying to make a form, with the ModelForm class, for people to be recruited by a small company. So I need photo of their identity card (face and back) and their life card. The problem is that when I send the form, after selecting the photos from my computer, it does not register in the database (not even the path), and they do not a copy to the desired media folder. By cons, if I do it from the admin, it works, I can even open the image in my browser. However, they still do not upload to the media folder. models.py : from django.db import models from django.contrib.auth.models import User class UserExtention (models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null=True, verbose_name='utilisateur') phone_number = models.CharField (max_length = 10, null = True, blank=True, verbose_name='numéro de téléphone') postal_code = models.IntegerField (null = True, blank=True, verbose_name='code postal') town = models.CharField (max_length=50, null=True, blank=True, verbose_name='ville') address = models.CharField (max_length=500, null=True, blank=True, verbose_name='adresse') id_card_recto = models.ImageField (upload_to = 'pictures/id_card_recto', null=True, blank=True, verbose_name="photo du recto de la carte d'identité") id_card_verso = models.ImageField (upload_to = 'pictures/id_card_verso', null=True, blank=True, verbose_name="photo du verso de la carte d'identité") vital_card = models.ImageField (upload_to = 'pictures/vital_card', null=True, blank=True, verbose_name="photo de la … -
Django object create with one or more items (dynamically)
Is there a way to use model.objects.create(<dict>) Say my model has many optional fields. I would like to just pass a dict with whatever is there instead of manually assigning each field like: Model.objects.create(thing=data['prop'],...) Here's a more clear (pseudo code) example: Say i've got a model thats got class MyModel(models.Model): thing=models... // all these fields null=True, blank=True another=... possibly_another=... ... data = {'thing': 'value for thing', 'another': 'value for another'} MyModel.objects.create(data) In this example my data doesn't have possibly_another and maybe more. I have tried doing this but i'm getting a positional arg error... I did some google-foo and i must not have my terms correct. (I'm more of a node/js guy) Is there a way to just pass the dict and have the create method sort out what's there and not? -
No access to static files on AWS S3
On the django project I use Nginx to access static files placed on AWS S3. After successful completion of the command collectstatic the styles still didn't apply to the project. When I activate the debbugger in my browser, I can see that the requests for static files are on the right path, but they are not accessible (index):18 GET https://mysite-staging.s3.amazonaws.com/static/admin/css/icons.css net::ERR_ABORTED 403 (Forbidden) (index):37 GET https://mysite-staging.s3.amazonaws.com/static/lifeline/css/global.css net::ERR_ABORTED 403 (Forbidden) (index):24 GET https://mysite-staging.s3.amazonaws.com/static/material/js/jquery.js net::ERR_ABORTED 403 (Forbidden) How do I access it? Do you need to change Nginx settings for this purpose? My current nginx config location /s3/ { proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header Authorization ''; proxy_set_header Host mysite-staging.s3.amazonaws.com; proxy_hide_header x-amz-id-2; proxy_hide_header x-amz-request-id; proxy_hide_header x-amz-meta-server-side-encryption; proxy_hide_header x-amz-server-side-encryption; proxy_hide_header Set-Cookie; proxy_ignore_headers Set-Cookie; proxy_intercept_errors on; add_header Cache-Control max-age=31536000; proxy_pass https://mysite-staging.s3.amazonaws.com/; } -
Combine network host and bridge for Nginx and Django
I am dockerizing a Django application, using also Nginx as proxy. My problems is that the DB is running (non dockerized) on the same machine of the where the dockers are hosted. Therefore, i have to use network_mode: "host" for the django app in order to connect to the db using localhost. On the other side, if I do so, the nginx image is not able to reach the Django app anymore and gives nginx: [emerg] host not found in upstream My docker compose file is the following: version: '3.4' services: web: build: . command: sh /start.sh networks: - db_network - web_network volumes: - static_volume:/allarmi/src/AllarmiWs/static expose: - 8001 environment: - DEBUG=0 - DJANGO_SETTINGS_MODULE=AllarmiWs.settings.deploy nginx: build: ./nginx ports: - 8000:80 depends_on: - web volumes: - static_volume:/allarmi/src/AllarmiWs/static networks: - web_network volumes: static_volume: networks: web_network: driver: bridge db_network: driver: host How can I do it -
which database is best suited for django Mongodb or Mysql
help me with which database best suits for django , so that it will not affect its performance -
JavaScript MIME type warning on Firefox
I am loading the java-script file in Django template: <script type="application/javascript" src="{% static 'online-v3.js' %}"></script> It is loading properly on Chrome. But, on Firefox I get the following warning: The script from “http://127.0.0.1:8000/static/myscript.js” was loaded even though its MIME type (“text/plain”) is not a valid JavaScript MIME type. I fear that due to this problem, on some browser the JS file might not load at all. What is the possible reason for this and how can I solve this issue? -
How to append two separate forms to the end of a url in Django
I am attempting to create a django web app, and I'm running into an issue with forms. I have a simple index.html set up that has two separate regular html forms on the page. One for filtering and the other for sorting. Currently, I can get either filtering, or sorting to work, but not both at the same time. I think this is because I'm missing a fundamental understanding of django somewhere. Yes, I've done the tutorials. I've attempted manually appending the URL to my urlconfig, but that didn't work as intended. <form action="" method="get"> {% for filter in view.all_filters %} <label> <input type="checkbox" name="filter" value="{{ filter }}"> {{ filter }} </label> {% endfor %} <input type="submit" value="Apply Filters"> </form> <form action="." method="get"> <label> Sort By <select name="order_by"> <option value="name">Name</option> <option value="description">Description</option> <option value="cvssBaseScore">Cvss Base Score</option> <option value="cvssV3BaseScore">Cvss V3 Base Score</option> </select> </label> <input type="submit" value="Submit"> </form> I would like the url to be able to append something like ?filters=one&filters=two&order_by=name or something as such. -
How integrate beautifulsoup4 library into django?
Everybody knows the great library BeautifulSoup4, but how to use it with django2? The task was to create a web application that helps programmers find work. So that all logic and interface are based on django, and scraper BeautifulSoup collects information on vacancies on job search sites and displays them to the user. I couldn't find any explanation for how to put them together anywhere on the network. I know about scrapy, but it doesn't support django 2 at the moment. BeautifulSoup's documentation does not provide an answer. Thank for your attention! -
Display in HTML answers to MultiSelectField (checkboxes) without forms.py - multiselectfield.db.fields.MSFList
I created a website where a user can upload a project and answer some questions related to it. One of the questions, the initial one, involves the user to select options among two check boxes. models.py class Initialquestion(models.Model): INITIAL_ONE_CHOICES = ( ('Diagnostic', 'Diagnostic'), ('Therapeutic','Therapeutic'), ('Population health','Population health'), ('Care-based','Care-based'), ('Triage','Triage'), ('Self-care','Self-care'), ('Health promotion','Health promotion'), ('Remote Monitoring','Remote Monitoring'), ('Remote Consultation','Remote Consultation'), ('Other','Other'), ) INITIAL_TWO_CHOICES = ( ('Primary Care', 'Primary Care'), ('Secondary Care','Secondary Care'), ('Tertiary Care','Tertiary Careh'), ('Individual Care of Self','Individual Care of Self'), ('Triage','Triage'), ('For the purposes of population screening','For the purposes of population screening'), ('Other','Other'), ) initial_one = MultiSelectField(choices=INITIAL_ONE_CHOICES) intial_two = MultiSelectField(choices=INITIAL_TWO_CHOICES) developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project = models.OneToOneField(Project, on_delete=models.CASCADE) views.py @login_required def initialquestionstoanswer(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': # if request.POST['initial_one']: question = Initialquestion() question.initial_one = request.POST.getlist('initial_one[]') question.initial_two = request.POST.getlist('initial_two[]') question.developer = request.user question.project = project question.save() messages.success(request, 'Initial questions are created') return redirect('/projects/allprojects') # else: # return render(request, 'initialquestions/initialquestionstoanswer.html', {'error':'All fields are required.'}) return render(request, 'initialquestions/initialquestionstoanswer.html', {'project':project}) This allows me to save into the database the answer to initial_one and initial_two. In fact, if I check with the superuser, both fields are populated with the right value of the checkboxes. I want now to display … -
I want to replace one form field with another when the value of another field is equal to something
The thing I have here doesn't work. It will just get rid of the field once choose US and doesn't go back to the choices even if choose something else. teacher_signup.html {% block content %} <h2>Sign Up As Teacher</h2> <form method="post"> {% csrf_token %} {% for field in form.visible_fields %} {{ field | as_crispy_field}} {% if field.name == "country" %} <input type="button" value="cube" onclick="getcube()"/> {% endif %} {% endfor %} <button class="btn btn-success" type="submit">Sign Up</button> </form> <script> function getcube(){ var county=document.getElementById("id_country").value; alert(county); } $(document).ready(function() { $("#id_country").change(function(){ if (this.value=="US"){ $("#id_state").replaceWith(); } }); }); </script> {% endblock content %} forms.py class TeacherSignUpForm(SignupForm): country=CountryField(blank_label='(select country)').formfield() # this is just doing the same thing as country=forms.CharField(max_length=20, widget=forms.Select(choices=COUNTRY_CHOICES), required=True) state=forms.CharField(max_length=20,required=True) I want to replace the state field with state=forms.CharField(max_length=20, widget=forms.Select(choices=STATE_CHOICES), required=True, strip=True) if the country=="US" and if they choose something else, then it will just show the text field. -
Employee login page should redirect based on the designation.included the models and forms code
Here I added the my models. department and designation foreign key from Department and Designation models Once the Employee login with credential page should redirect based on the employee Designation and Department models.py class Department(models.Model): Name = models.CharField(max_length=50) def __str__(self): return self.Name class Meta: db_table = 'department' class Designation(models.Model): Name = models.CharField(max_length=50) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return self.Name class Meta: db_table = 'desingnation' class Emp_Profile(AbstractUser): Mobile_Number = models.IntegerField(null=True,blank=True) department = models.ForeignKey(Department, null=True, blank=True, on_delete=models.CASCADE) designation = models.ForeignKey(Designation, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.username class Meta: db_table = 'emp_table' forms.py This is my user extended Users class UserForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = Emp_Profile fields = UserCreationForm.Meta.fields + ('Mobile_Number','department','designation') -
Django Admin change list Hide one of the choices option for users
I have a model with an integer field. This field has choices option. As you can see Request has 4 available statuses. I want to display only three of them on the edit template and celery task will change status from 3 to 4th state every 12 hours. So when a user in the admin panel can change the status only to 1, 2 or third status but not to 4th one. Model code UNPROVEN = 1 IN_PROGRESS = 2 IN_LINE_FOR_DELETE = 3 DELETED = 4 _STATUS = [ (UNPROVEN, "Unproven"), (IN_PROGRESS, "In progress"), (IN_LINE_FOR_DELETE, "In line for deletion"), (DELETED, "Deleted") ] delete_user = models.ForeignKey('BoosteroidUser', on_delete=models.SET(get_deleted_user), related_name='%(class)s_delete') delete_reason = models.TextField(max_length=1024) status = models.IntegerField(default=1, choices=_STATUS, blank=False) responsible_user = models.ForeignKey('BoosteroidUser', on_delete=models.SET(get_deleted_user), null=True, blank=True, default=None)``` Code from admin ```@admin.register(UserDeleteRequest) class UserDeleteRequest(admin.ModelAdmin): list_display = ("status", "responsible_user") fields = ("delete_user", "status", "responsible_user", "delete_reason") readonly_fields = ("responsible_user", "delete_user", "delete_reason") def has_add_permission(self, request): return False def has_delete_permission(self, request, obj=None): return False def save_model(self, request, obj, form, change): if obj.status == 3 or 2: obj.responsible_user = request.user super().save_model(request, obj, form, change)``` So I expected that any user in the admin panel will be able to see and choose only first 3 statuses but not the 4th one [Expected …