Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"<Order: Order object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used
So I'm trying to add multiple products or order items into a product and I'm using many to many relationship for that but when I try to create that order I get "<Order: Order object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. error, My code for adding and saving that order is like: userObject = UserLogin.objects.get(token=finalUserToken).user objects = OrderItem.objects.filter(user=userObject) FinalOrder = Order(user=userObject, order_id=another_token) for orderObject in objects: FinalOrder.products.add(orderObject.id) FinalOrder.save() The error screen is pointing to this line FinalOrder.products.add(orderObject.id) I have also tried this FinalOrder.products.add(orderObject) but this gives the same result too -
Cron in docker container with django
I have django project and make managment command for django. This command delete some objects from db. So If I run it manually "docker-compose exec web python manage.py mycommand" it works fine, but when I try add task into cron using crontab (cron located in django container): */1 * * * * path/to/python path/to/manage.py mycommand >> cron.log 2>&1 django raise: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP connections on port 5432? Tasks without db connection work fine. Problem is that tasks executed by cron can`t connect to db. Any ideas how to change crontab file or docker-compose.yml? docker-compose.yml version: '3' services: web: container_name: web env_file: - .env.dev build: context: ./ dockerfile: Dockerfile volumes: - .:/domspass - "/var/run/docker.sock:/var/run/docker.sock" command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" depends_on: - db db: image: postgres:13.2 container_name: db restart: always env_file: - db.env.dev volumes: - ./postgres:/var/lib/postgresql/data ports: - "5432:5432" volumes: postgres: -
Django Dependencies and Versions
I'm trying to find the list of dependencies Django requires when installing on a per version basis. Is this located in the codebase anywhere? -
django - A object have pk of B (ex 2) but B.objects.get(pk=2) not exists
django - A object have pk of B (ex 2) but B.objects.get(pk=2) not exists why B objects not exists pk2 B objects deleted How make A.objects.filter(???) i have written that A.objects.filter(B__id__isnull=False) but not working -
Does the Backend Distinguish Different API Requests from Different Users in SSR Mode? (Nuxt.js / Django Rest Framework)
I know that the title might be a little bit confusing, so I'll explain my question with an example. I'm using Nuxt.js in SSR mode for frontend, and Django Rest Framework for backend. Consider an API endpoint in DRF that has a rate throttling of 1 request per minute for anonymous users. And imagine that this endpoint is called in a certain page by axios in the frontend, in both SPA and SSR modes. Imagine 2 different users with different IPs request the page in SSR mode (new tab), user A in time t and user B in time t + 2seconds. Now that the frontend server requests the backend for the data, would the rate limiting give 429 - too many requests to user B's request? Or is there some kind of forwarding pattern that prevents this behavior?? Obviously, if user A and B request the page in SPA mode, they would both get their responses. -
Edit AutoSlugField value
Is there any way I can edit the value of an AutoSlugField? I just noticed it added a '-2' to the end of the slug and I'd like to remove that. slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') -
Ajax request not triggering progress event on HTTPS port 443 in Django
I have a Django website served by UVICORN, the ajax request works fine however, the progress event is not triggered when using HTTPS on port 443. For example, when I change port number to anything other than 443, the progress event starts working! It also works when using port 443 on HTTP. I tried HYPERCORN as well, but nothing changed. Below is the configuration I use to run UVICORN. uvicorn ****.asgi:application --host 0.0.0.0 --port 443 --ssl-certfile cert.crt --ssl-keyfile key.key --ws websockets Any help would be appreciated. -
In django project, python says Pillow is not installed but it is installed
after upgrading python 3.8 to 3.9 this error has happened and says pillow is not installed. I tried to uninstall and reinstall pillow, but it did not worked. the image is attached to see the detail. I'm using Django 3.1 on a windows 10 pro. the output of pip freeze is attached too. here is the error message: ERRORS: magazine.Magazine.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". post.Posts.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". post.Sample.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". post.Workers.avatar: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". product.Products.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". -
<ul class="errorlist"><li>discipline<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li>
I used Django to developed a web app. When I submit my form , error occurs: disciplineSelect a valid choice. That choice is not one of the available choices.semesterSelect a valid choice. That choice is not one of the available choices. HTML: <form action="/content_checklist_name_url/" method="POST" onsubmit="return confirm('Do you want to confirm entries?');"> {% csrf_token %} <label> Discipline: </label> <select id="discipline" name="discipline"> {% for discipline in query_results %} <option value="{{ discipline.name }}" selected disabled hidden>--Select--</option> <option value="{{ discipline.name }}">{{ discipline.name }}</option> {% endfor %} </select><br> ... </form> view.py def content_checklist_name_url(request): discipline = 'NA' query_results = 'NA' print(request.method) if request.method == 'POST': print(request.POST) # Create a form instance and populate it with data from the request (binding): Course_Form = ContentChecklistForm(data=request.POST) # Check if the form is valid: if Course_Form.isvalid(): # process the data in form.cleaned_data as required (here we just write it to the model due_back field) discipline = Course_Form.cleaned_data["discipline"] courseCode = Course_Form.cleaned_data["course_code"] courseTitle = Course_Form.cleaned_data["course_title"] type = Course_Form.cleaned_data["Course_Type"] semester = Course_Form.cleaned_data["presenting-semester"] postgraduate_course = Course_Form.cleaned_data["postgraduate-course"].map({'Yes': 1, 'No': 0}) Presentation_pattern = Course_Form.cleaned_data["Presentation_pattern"] ContentChecklist.objects.create(discipline=discipline, course_code = courseCode, course_title = courseTitle, type=type, semester=semester) id = Discipline.objects.only('id').get(name=discipline).id CourseInfo.objects.create(code=courseCode, title=courseTitle,postgraduate=postgraduate_course, type=type, discipline_id=id, pattern=Presentation_pattern) form.py: class ContentChecklistForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = … -
django.db.utils.InternalError: Packet sequence number wrong - got 45 expected 0
py migrations give this error: "django.db.utils.InternalError: Packet sequence number wrong - got 45 expected 0" and I have not made any changes to my connection.py file. All the information I am getting on this talks something along the lines of multi-thread connections to the db. All I did to connect to db is in settings.py file as of the below. Anyone with useful help? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'address_dbname', 'USER': 'address_dbname', 'PASSWORD': 'pAssWrd/0', 'HOST': '68.65.122.89', 'PORT': '21098', } } -
How to read a file from Django MEDIA_ROOT and let the user download it in the front-end?
I have a view as follows: def import_data(request): if request.method == "GET:: column_names = network_asset._meta.fields #network_asset is the Model name column_names = [x.name for x in column_names] with open(os.path.join(MEDIA_ROOT, 'excel_templates', 'template.csv'), 'w+', newline = '') as file: writer = csv.writer(file) writer.writerow(column_names) Now, I want to pass in the file as context to the HTML page and download it using an <a> tag. <a href="{{ myfile }}" download > Download {{ myfile }}</a> My settings.py has # Media files (Excel templates, downloadable files) MEDIA_ROOT = os.path.join(BASE_DIR,'media/') MEDIA_URL = '/media/' My Models has: class netowrk_asset(models.Model): #### code here ####### class ExcelTemplate(models.Model): file = models.FileField(upload_to="excel_templates", default = "") Thanks in Advance -
how to break python infinite loop with XMLHttpRequest abort
I'm working on a project in which one button holds processing for hours with a loop and I want to break the loop with XMLHttpRequest but I haven't found anything useful... let me share a simple example Ajax request $.ajax({ type: 'POST', url: '', data: { csrfmiddlewaretoken: '{{ csrf_token }}',text:text }, xhr: function(){ const xhr = new XMLHttpRequest() // I guess solution can be write here } success: function(data){ console.log(data.done) spin.classList.add('not-visible') }, error: function(error) { console.log(error) }, }) Views.py def next_trick(request): if request.is_ajax(): while True: print('infinite loop') sleep(3) return JsonResponse({'done':'hell yeah'}) return render(request, 'uploader/next_trick.html',context) how can I break this while loop with XMLHttpRequest? -
Don't use field name in DRF serialization (there is only one field)
I want the serialization of a nested model not to include the field name for every instance, since there is only one field in the serialization. I have the following models in models.py: class Language(models.Model): name = models.CharField(max_length=32) code = models.CharField(max_length=32, unique=True) class Person(models.Model): name = models.CharField(max_lenght=128) languages = models.ManyToManyField(Language, blank=True) # the languages this person speaks languages is a ManyToManyField since one person can speak many languages and one language can be spoken by many people. I have for them the following serializers in serializers.py: class LanguageSerializer(serializers.ModelSerializer): class Meta: model = Language fields = ['code'] class PersonSerializer(serializers.ModelSerializer): languages = LanguageSerializer(many=True, required=False) class Meta: model = Person fields = ['name', 'languages'] Currently the serialization into a JSON looks like something like this: {"name": "Elizabeth II", "languages": [{"code":"en"}, {"code":"fr"}]} but I would like it to look like this: {"name": "Elizabeth II", "languages": ["en", "fr"]} And this will should not cause a problem, because there is only one field in the serialization of language and there will never be another field, so the "code" field name is redundant. How can this be achieved? -
Using specific fields from Model A on Model B. Circular import error
I was trying to use coverage_amount, policy_length on models/User.py from models/Policy.py and when I import it using "from .policy import Policy" I'm encountering circular import because there is already an import in Policy.py which is "from .user import User" **class Insuree(TimeStampedModel):** user = models.OneToOneField( 'User', related_name='insuree', null=False, on_delete=models.CASCADE, primary_key=True) #coverage_amount = models.ForeignKey(Policy, on_delete=models.CASCADE, max_length=256, blank=True, null=True) #policy_length = models.ForeignKey(Policy, on_delete=models.CASCADE, max_length=2, blank=True, null=True) **class Policy(TimeStampedModel):** policy_length = models.FloatField(max_length=2, blank=True, null=True) coverage_amount = models.FloatField(max_length=256, blank=True, null=True) Now, how can I use the coverage_amount, policy length from policy.py on user.py. I was trying to make a POST endpoint -
Django MultiSelectField how to have disabled=True in the form
I am using django MultiSelectField for storing multiple choice fields in db. In my forms.py I make many fields as read only by setting disabled=True: xyz = forms.IntergerField(disabled=True) This doesnt work with MultiSelectField. I tried the following but it gives error when saving the updated form : def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['working_days'].widget.attrs['disabled'] = True Error: Fields required I would like to show MultiSelectFields as it is in a disabled state, but when saving the edited form in django view, I want django to use old values for this field. -
File upload progress Django chat application
How to show the progress of large file upload in chat using Django channels. I just saw a method using ajax but I'm using web socket channels, so I can't use ajax for sending the image. -
How to pass variable from classes to methods in Django for every object
I'm manually creating an OTP authenticator using django. I have created a class which creates an otp and sends it to the user by email. I've not written the code to send email. I'll complete it by send_email() inbuilt function. Please look after the code in views.py, I would like to use another function to verify the otp. But once I create the same object in the second function it reinitializes the variable. def register(request): """ Other stuffs like password matching goes here """ """ This will be provoked first in production """ g=globals() g["user" + str(request.POST['username'])] = OTPclass() g["user" + str(request.POST['username'])].send_otp() def verify(request): """ This method will be provoked once the user enters the OTP received in the email """ g=globals() g["user" + str(request.POST["username"])] = OTPclass() #In this part the value reinitializes to 0, but I must get the otp which was sent to the user if(int(request.POST['otp']) == g["user" + str(request.POST["username"])].the_otp): return redirect(login) else: print(g["user" + str(request.POST["username"])].the_otp) return HttpResponse("<html><body><h2>OTP mismatch</h2></body></html>") class OTPclass: the_otp = 0 def send_otp(self): self.the_otp = random.randint(1000,9999) """ send_email() will be used here to send the otp to the user """ Kindly suggest a way to get the value which was sent to the user in … -
Getting Application error on Heroku but no errors while deployment
Getting Application error, no errors though. Can anyone explain what I am missing ? -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No change in requirements detected, installing from cache -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 Skipping installation, as Pipfile.lock hasn't changed since last deploy. -----> Installing SQLite3 -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 72.1M -----> Launching... Released v11 https://newspaper-shaunak.herokuapp.com/ deployed to Heroku -
Reload page after session expire in Django
I have followed some of SO's answers about the Django session. Many of them are Django session in 5 minutes and SESSION_EXPIRE. The code I tried works when I reload the page after the set of specific times. I got two problems here: It doesn't auto-reload the page and doesn't go back to the login page. Settings.py INACTIVE_TIME = 1*60 SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = INACTIVE_TIME SESSION_IDLE_TIMEOUT = INACTIVE_TIME SESSION_SAVE_EVERY_REQUEST = True middleware.py from django.contrib.auth import logout import datetime from settings import SESSION_IDLE_TIMEOUT class SessionIdleTimeout(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: current_datetime = datetime.datetime.now() if 'last_active_time' in request.session: idle_period = (current_datetime - request.session['last_active_time']).seconds if idle_period > SESSION_IDLE_TIMEOUT: logout(request, 'base/login.html') request.session['last_active_time'] = current_datetime response = self.get_response(request) return response The above code redirects to login page after the session expires. But it is manual and users have to load this page. I expect to reload automatically and redirect to the login page whenever the session is expired. Any help will be appreciated. -
Apache + django + windows долгая загрузка
Good afternoon. When deploying the project, there was a problem with the response speed, it's not that the page does not load, but that it is unstable, specifically the page can load in a second or hang for a minute and to no avail, while if you open the page http://localhost/123di123423WA/ that is, it always loads instantly. example of uploading via localhost example of uploading via example.com/ Это прописано в Apache httpd.conf LoadFile "c:/python37/python37.dll" LoadModule wsgi_module "c:/python37/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/python37" WSGIScriptAlias / "c:/django_project/kors/kors/wsgi.py" WSGIPythonPath "c:/python37;C:/django_project/kors/" WSGIPassAuthorization On <Directory "c:/django_project/kors/kors/"> <Files "wsgi.py"> Require all granted Alias /static "C:/django_project/kors/kors/static" <Directory "C:/django_project/kors/kors/static"> Options Indexes FollowSymLinks AllowOverride None Require all granted Alias /media "C:/django_project/kors/kors/static/media" <Directory "C:/django_project/kors/kors/static/media"> Options Indexes FollowSymLinks AllowOverride None Require all granted I tried different options but unfortunately not searching or reading all the posts similar to mine did not give results. Maybe someone has encountered this problem. Brandmaster and other things are disabled. -
Django - return each model value without field
The Priority model has three values, for each of them values I'm returning an inlineform which allows the user to set a score for each priority & then save with the Project. This is what it currently looks like: Current view My problem is: how can I automatically show all the priority values and allow the user to enter the score but not have to pick the Priority. Is it possible to show it like the image below? What I'm trying to do. Views.py class ProjectCreateview(LoginRequiredMixin, CreateView): model = Project form_class = ProjectCreationForm login_url = "/login/" success_url = '/' def get_context_data(self, **kwargs): PriorityChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('project', 'priority', 'score'), can_delete=False, extra=Priority.objects.count(), ) data = super().get_context_data(**kwargs) if self.request.POST: data['priorities'] = PriorityChildFormset(self.request.POST) else: data['priorities'] = PriorityChildFormset() return data def form_valid(self, form): context = self.get_context_data() prioritycriteria = context["priorities"] form.instance.creator = self.request.user self.object = form.save() prioritycriteria.instance = self.object if prioritycriteria.is_valid(): prioritycriteria.save() return HttpResponseRedirect(self.get_success_url()) Models.py class Priority(models.Model): title = models.CharField(verbose_name="Priority Name", max_length=250) def __str__(self): return self.title class Project(models.Model): name = models.CharField(verbose_name="Name", max_length=100) details = models.TextField(verbose_name="Details/Description", blank=False) creator = models.ForeignKey(User, on_delete=models.CASCADE) class ProjectPriority(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) priority = models.ForeignKey(Priority, on_delete=models.CASCADE) score = models.CharField(max_length=1000, choices=priority_choices) class Meta: verbose_name = "Priority" verbose_name_plural = "Priorities" Template <table … -
ValueError: Unable to configure filter "'request_id'"
I was trying to run the python3.8 manage.py runserver Im having the request_id defined in INSTALLED_APPS and request_id.middleware.RequestIdMiddleware added in MIDDLEWARE under setting.py This is the traceback > Exception ignored in thread started by: <function > check_errors.<locals>.wrapper at 0x7fe56c1d78b0> Traceback (most > recent call last): File > "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 228, > in wrapper > fn(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/core/management/commands/runserver.py", > line 116, in inner_run > autoreload.raise_last_exception() File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 251, > in raise_last_exception > six.reraise(*_exception) File "/usr/lib/python3/dist-packages/django/utils/six.py", line 685, in > reraise > raise value.with_traceback(tb) File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 228, > in wrapper > fn(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/__init__.py", line 22, in setup > configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/lib/python3/dist-packages/django/utils/log.py", line 75, in > configure_logging > logging_config_func(logging_settings) File "/usr/lib/python3.8/logging/config.py", line 808, in dictConfig > dictConfigClass(config).configure() File "/usr/lib/python3.8/logging/config.py", line 553, in configure > raise ValueError('Unable to configure ' ValueError: Unable to configure filter 'request_id' Im running this using python3.8 but not sure why python3 is referred in traceback. -
Django cannot start project
I tried to start a new project in Django but I can't because it kept saying the python 2.7 does not exist on my computer. It does not exist on my computer because I uninstalled it. I have python 3 installed but for some reason, Django keeps linking it to python 2 which I had uninstalled.enter image description here -
Django customization of loading a foreign key
Assume I have three related classes such as: class A: ... class B: ... a = models.ForeignKey(A, ...) class C: ... b = models.ForeignKey(B, ...) I want to customize accessing b on C object to load a immediately. It means whenever I called c.b a select_related query call a too. There are also other scenario which I need to be able to use prefetch_related. I am using django 3.1.1 -
How can I personalize an URL path in Django?
I am trying to build an website which renders some books and the corresponding pages. I want to make possible to access a page like this: path('/<str:book_pk>-<int:book_page>/', views.TestClass.as_view(), name='book-test') I want a user to access it very simple, something like: mysite.com/5-12/ - which redirects him to the book nr 5 at page 12. The problem is that when I access this page from the website itself, using href, the real path becomes: mysite.com/%2F5-13/ If I want to write in the browser, the following path: myste.com/5-13/, it throws me 404 page not found, because the real path is mysite.com/%2F5-13/ . This is pretty obvious, but my question is: How can I stick to my initial path, and make it possible to be accessed via myste.com/5-13/? For some reason, Django URL Patterns, adds an extra %2F string at the beginning. Can somebody explain me why, and how to solve this issue? I much appreciate your time and effort! Thank you so much!