Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the server does not distribute django + gunicorn + nginx static
On my ubuntu 20.04 I am trying to deploy a Django 3.2.8 project using nginx and gunicorn. The problem is that the server cannot find the static. Because of this, the pages are displayed without css and images. I tried many solutions from the internet but nothing helped me. Thank you in advance for your time! at first im start this script (start_gunicorn.sh) #!/bin/bash source /root/myapps/zhanna_first_web/env/bin/activate exec gunicorn -c /root/myapps/zhanna_first_web/zhanna/gunicorn_config.py lawyer> gunicorn_config.py: command = '/root/myapps/zhanna_first_web/env/bin/gunicorn' pythonpath = '/root/myapps/zhanna_first_web/zhanna' bind = '185.46.8.164:8001' workers = 3 user = 'root' limit_request_fields = 32000 limit_request_field_size = 0 raw_env = 'DJANGO_SETTINGS_MODULE=lawyer.settings' /etc/nginx/sites-enabled/default server { listen 80; server_name 185.46.8.164; location /static { autoindex on; root /myapps/zhanna_first_app/zhanna/static; } location / { proxy_pass http://185.46.8.164:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; add_header Access-Control-Allow-Origin *; } } Ubuntu responds to the launch of the start_gunicorn script with this output. [2022-01-09 09:53:31 +0300] [76583] [INFO] Starting gunicorn 20.1.0 [2022-01-09 09:53:31 +0300] [76583] [INFO] Listening at: http://185.46.8.164:8001 (76583) [2022-01-09 09:53:31 +0300] [76583] [INFO] Using worker: sync [2022-01-09 09:53:31 +0300] [76585] [INFO] Booting worker with pid: 76585 [2022-01-09 09:53:31 +0300] [76586] [INFO] Booting worker with pid: 76586 [2022-01-09 09:53:31 +0300] … -
annotate an extra field but show just once in api response in django rest
I have to add an extra field using annotate in the get api. The field is something like count of a field of all the objects, not a particular object. And I want it to appear just once in the response of get api. If I use annotate, it appears on all the objects response. How can it be achieved?? My model: class Package(models.Model): location = models.CharField() bought_times = models.IntegerField(default=0) /....................../ Now if I use annotate something like this: qs = Package.objects.filter(....).annotate(whole_bought_counts=Sum("bought_times") or some logic) In the response it will come like: { id = 1, localtion = Paris, bought_times = 22, whole_bought_counts =72, } { id = 1, localtion = Miami, bought_times = 16, whole_bought_counts =72, } id = 1, localtion = Switzerland, bought_times = 24, whole_bought_counts =72, } I need the whole_bought_counts to appear just to appear once, because the count is used for the dashboard info only. Appearing several times will make it appear 100+ times which makes the api quite slow. isnt it?? -
Modal popup for Django DeleteView
I'm trying to have a modal popup asking for confirmation before deleting the object using DeleteView. So far, I've tried solutions from this thread using the following code. views.py class SessionCancelView( SuccessMessageMixin, LoginRequiredMixin, UserPassesTestMixin, DeleteView ): model = Session success_url = "/profile" success_message = "Session was cancelled successfully" # FIXME: success message not showing - eh maybe not necessary tho def test_func(self): session = self.get_object() if self.request.user == session.student: return True return False def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) profile.html <!-- Modal --> <div class="modal fade" id="sessionDeleteModal" tabindex="-1" role="dialog" aria-labelledby="sessionDeleteModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Cancel Session</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to cancel this session? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button class="btn btn-outline-danger" type="submit">Yes, Cancel</button> <form method="POST" action="{% url 'session-cancel' session.id %}"> {% csrf_token %}<input type="submit" value="DELETE"> </form> </div> </div> </div> </div> . . . {% for session in user_sessions %} {% if session.is_upcoming %} <div class="card bg-light mb-3" style="width: 18rem;"> <div class="card-header">{{ session.date|date:"F d [l]" }}</div> <div class="card-body"> <h5 class="card-title">{{ session.get_timeblock_display }}</h5> <h6 class="card-subtitle mb-2 text-muted">{{ session.weekday }}</h6> <p class="card-text">{{ session.helptype }}</p> <a class='btn btn-outline-secondary btn-small … -
Django: Unique IDs for each sub-model of a Model
I'm fairly new to Django, but I believe my question is more towards designing databases regardless of the framework or platform. Let me explain using following quick pseudo. I have following two models: class Issue(models.Model): title = models.CharField(max_length=60) status = models.IntegerField(choices=Status.choices, default=Status.OPEN) ... class Comment(models.Model): issue = models.ForeignKey(Issue, on_delete=models.CASCADE, related_name="comments") text = models.TextField() ... In my web app, I'm building a collection of Issues. Each issue is assigned a django's auto-generated unique ID number (pk), which is perfect. And for each issue there is a property comments which holds a collection of comments specific to this issue. Each comment also has a system-generated unique ID, but the sequence of this ID is not specific to the Issue model. Means if I create 3 comments in Issue #1 (comment #1, #2, #3), and then I create a comment under Issue #2, that comment's ID is set as #4 instead of #1. I understand that this is the way the data models are defined. What I would like to have is that whenever a new issue is created and a comment added, its ID should start from 1. I cannot define comment IDs manually by incrementing over the previous comment ID because … -
How to control the size of div by adding class using jquery?
sorry if the question isn't clear enough but let me explain what is happened to me. now I have 5 graphs that have been created by Pandas and want to use jquery to affect on grid system in bootstrap. all the divs have the following class "col-md-6" except the last child which has "col-md-12", what I would like to do is: to add "col-md-6" to the last child in case of the length of graphs are even number and remove the "col-md-12" from the last one. actually, this process is working and the class becomes added to the last child after the document is ready, however, the last graph does apply "col-md-12" and does not apply "col-md-6" even though, it has "col-md-6" but when I do a resize for the page the graph starts to apply "col-md-6" on it. the question is How can I apply the "col-md-6" dynamically without doing resize for the page? you can see the behavior before and after resize to understand what I mean exactly:- before do resize after doing a resize The code is like so:- ... <div class="col-md-6 error-graph"> {% if regular_group %} <div style=""> <div style="max-width: 100%;max-height: 100%"> {{ regular_group|safe }} </div> … -
How to call a object instance with string in Django/Wagtail?
I have a view need to generate different form in the same template. Is possible to use string be a object instance? like this: def register(request, form_name): form = form_name(data=request.POST) return render(request, 'template', {'form':form}) -
Django access site name/url in template - views, contexts and settings
(It feels like "best practices" type of question, sorry if these don't belong here) I'm building a website which has user registration and password reset feature, both of which would send email to the user with a link to click to complete the respective process. While testing on a staging box, I used a dirty workaround in order finish the Proof Of Concept - hardcoded the website address in the template ) Needless to say, I want to fix this sooner rather than later. Searching around, found references to django.contrib.sites, which looks like a possible solution, though one thing bothers me - technically there's but one site, but with two stages, staging and production. I don't want to swim against the current, potentially abusing "sites", where another solution might apply. I've then considered another approach - add respective URLs to corresponding settings.py files, of which I already have a grasp - one for local, one for staging, and one for prod. The issue here is probably obvious - I don't think it's proper (or possible) to read the settings.py from templates, and trying to keep the solution as simple as possible, I'm using a few standard views, which means I … -
GET Request causes net::ERR_CONNECTION_REFUSED (Django/PostgreSQL)
My POST and GET requests are generally working and not throwing errors but there is a specific GET Request that causes the following error: net::ERR_CONNECTION_REFUSED And closes my development server. There is no traceback suggesting an error the server simply closes and I have to restart it. def marker_info(request): template_name = 'testingland/electra.html' neLat = request.GET.get('neLat', None) neLng = request.GET.get('neLng', None) swLat = request.GET.get('swLat', None) swLng = request.GET.get('swLng', None) ne = (neLat, neLng) sw = (swLat, swLng) xmin = float(sw[1]) ymin = float(sw[0]) xmax = float(ne[1]) ymax = float(ne[0]) bbox = (xmin, ymin, xmax, ymax) print(bbox) geom = Polygon.from_bbox(bbox) qs = mapCafes.objects.filter(geolocation__coveredby=geom) //this is where it appears to fail print(qs) return JsonResponse([ [cafe.cafe_name, cafe.cafe_address, cafe.geolocation.y, cafe.geolocation.x, cafe.source, cafe.venue_type, cafe.id] for cafe in qs ], safe=False) I'm not quite sure where to go next in terms of debugging this problem. -
elementui datepicker+django: how to pass the user selected date value to the backend view.py
How to get the el-date-picker date value and pass it to django view.py. pickup_date = request.POST.get() is not working how to make the date picker a required field that user must choose a date html: <!DOCTYPE html> <html lang="en"> <head> <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">--> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> </head> <style> </style> <body> <form> <div id='app'> <el-date-picker v-model="value" type="date" placeholder="select date" value-format="yyyy-MM-dd" :picker-options="pickerOptions"> </el-date-picker> </div> <button type="submit">submit</button> </form> </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.6/dist/vue.min.js"></script> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <script> var Vue = new Vue({ el: '#app', data: { value:'', pickerOptions: { disabledDate(time) { return time.getTime() <= Date.now() } }, }, created() { }, mounted() { }, methods: { } }) </script> </html> -
Django Rest get link to related object in OneToOne relation
How can I get the related object link under OneToOne relation. I have 2 models: class Model1(models.Model): title = models.CharField(max_length=255, null=False) class Model2(models.Model): mymodel1 = models.OneToOneField(Model1, on_delete=models.CASCADE) In the Model1Serializer, how can i get the link to MyModel2 related object ahd get a result as follows: [ { "title": "My obj title" "link2mymodel2": "http://myhost/model2/pk" } ] where pk is the relared object -
How to send mail using django
So im trying to send a gmail in my django project. But every time i press the submit button i get html 405 error page. Views: def send_email(request): if request.method == "POST": name = request.POST.get("name") email = request.POST.get("email") message = request.POST.get("message") send_mail(name, email, message, ["aleksalav123@gmail.com"]) return HttpResponseRedirect("dashboard/") HTML: <form action="" method="POST"> {% csrf_token %} <input type="text" class="form-control" name="message_name" placeholder="Full name" id="full_name"> <input type="text" class="form-control" name="message_email" placeholder="Email" id="login-email"> <input type="text" class="form-control" name="message" placeholder="Poruka" id="text"> <input type="submit" value="Pošalji" class="login-button"> </form> -
How to create a test-only Django model in general (and with pytest-django specifically)
General issue: I have an abstract model that I want to test with a real model instance, however I don't want to have to completely restructure my project/test format. See these two answers for reference: First answer Second answer I want to A) Define models inside each test app folder and not define them inside the actual apps B) Not have an additional/separate apps.py and settings.py configuration for each test folder. I know this is possible because the django project has a very similar test structure like this, but they use a test run script that I can't entirely decipher. The test/ folder mirrors the app structure I have (which are blog/, projects/, richeditable/). backend ├── projects ├── blog ├── richeditable ├── tests │ ├── __init__.py │ ├── conftest.py │ ├── blog │ │ ├── ... │ ├── projects │ │ ├── ... │ └── richeditable │ │ ├── __init__.py │ │ ├── test_model.py │ │ ├── models.py <-------------- This defines a model that inherits from richeditable.models # richeditable/models.py class Draftable(models.Model): blah = models.IntegerField() class Meta: abstract = True # tests/richeditable/models.py class DummyDraftable(Draftable): additional_field = models.BooleanField() # class Meta: # app_label = "some_app" # ^--- Django does not seem to … -
ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
Currently on MacOS Monterey working with Django 4.0 and Python 3.10.0. After running the command python3 manage.py runserver I get this error ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/tonyingle/.local/share/virtualenvs/total-weather-backend-nYZrqAi-/lib/python3.10/site-packages/psycopg2/_psycopg.cpython-310-darwin.so, 0x0002): symbol not found in flat namespace '_PQbackendPID' I have already installed pyscopg2 and psycog2-binary in the pipenv shell and outside of it. The weird part about it is that everything worked fine until I realized I had to configure my settings.py file to fix my cors issue and then everything went haywire. Maybe some relevant settings in settings.py ALLOWED_HOSTS = [ "https://total-weather-backend.herokuapp.com/", "http://127.0.0.1:8000/"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', 'djoser', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', ... ] CORS_ORIGIN_ALLOW_ALL = True -
Django add reply messages
<div class="form-group row"> <form class="reply-form" method="post" action="."> {% csrf_token %} <input type="hidden" name="{{ message.id }}" value="{{ message.id }}"> <div class="form-group"> <textarea name="text" cols="60" rows="2" maxlength="4096" required="" id="id_text"></textarea> </div> <input type="submit" value="Submit" > </form> </div> I am trying to use the above to reply to a message. How would I use the message id to add a reply to that message from the action using views? models.py class Messages(models.Model): sender = models.ForeignKey(Profile,related_name='sender',on_delete=models.CASCADE) receiver = models.ForeignKey(Profile,related_name='receiver',on_delete=models.CASCADE) subject = models.CharField(default='',max_length=100) text = models.CharField(default='',max_length=4096) time = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='contact_parent') def get_children(self): return Messages.objects.filter(parent=self) def __str__(self): return '{} to {} :{}'.format(self.sender,self.receiver,self.text) I created a message like so class MessageForm(forms.ModelForm): subject = forms.CharField(max_length=100, required=False, help_text='Optional.') text = forms.CharField(max_length=4096, required=True, help_text='Required.') class Meta: model = Messages fields = ('receiver','subject','text',) views.py elif 'sendMessage' in request.POST: sendMessageForm = MessageForm(request.POST or None,) if sendMessageForm.is_valid(): sendMessageFormUser = sendMessageForm.save(commit=False) sendMessageFormUser.sender = request.user sendMessageFormUser.save() unreadMessagesCount = Messages.objects.filter(Q(receiver=request.user) & Q(read=False)).count() context['unreadMessagesCount'] = unreadMessagesCount return redirect('home') Expanded html for any use <div class="col-md-12"> <div class="accordion" id="accordionExample"> {% for message in Inbox %} <div class="card"> <div class="card-header" id="heading{{ forloop.counter }}"> <h5 class="mb-{{ forloop.counter }}"> <button class="btn" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{ forloop.counter }}" aria-expanded="false" aria-controls="collapse{{ forloop.counter }}"> {{ message.sender }} … -
Cant apply django migration that changes primary key name
I am trying to rename some models and fields that have names I do not like. I am using an mssql database. I have a very simple model. An example would look something like this: class RootProblem(models.Model): rootproblemid = models.AutoField(db_column="RootProblemID", primary_key=True) description = models.CharField( db_column="Root Problems", unique=True, max_length=255, blank=False, null=True ) I would like to rename the primary key from "rootproblemid" to something like "id". But when I change the name, run makemigrations, and then try to apply the new migration I get an error that says: execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 338, in database_forwards schema_editor.alter_field( File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 571, in alter_field self._alter_field(model, old_field, new_field, … -
Create multiple class based view querysets django
I'm trying to make/define multiple querysets in a view so that I can organize my HTML. I have a model with one specific part I'm trying to sort by class SomeClass(models.Model): ... variable = models.Charfield(max_length=15, choices = VAR_CHOICE) ... I'm using a ListView class. As each variable is from a choice list in my model, I want to be able to query each one so I can organize my template. class SomeClassView(ListView): model = SomeClass template_name = 'some-class.html' Using this answer here Display Multiple Queryset in List View I tried the following which doesn't work. class SomeClassView(ListView): model = SomeClass template_name = 'some-class.html' context_object_name = 'var' def get_queryset: queryset = { 'var1': SomeClass.objects.all().filter(variable='var1') 'var2': SomeClass.objects.all().filter(variable='var2') .... } return queryset Then my template is not rendering: {% for object in var.var1 %} {{ object.attribute_1 }} - {{ object.attribute_2 }} ... {% endfor %} {% for object in var.var2 %} {{ object.attribute_1 }} - {{ object.attribute_2 }} ... {% endfor %} The output will be organized in tables but there needs to be separate tables based on var1, var2, etc. Is there a better way to be doing this? Or how can I get this part to work? -
Field 'id' expected a number but got 'Free'
i'm trying to add a form, so users can post thier own articles , but when i hit publish button it shwos Field 'id' expected a number but got 'Free'. . i wasn't adding the package_category field to the forms because i have set a default value for it in my models.py package_category = models.ForeignKey(Package_Category, on_delete=models.DO_NOTHING, verbose_name="Package Category", null=True, default="Free") when i now add the package_category field to the forms.py fields = [...] it now shows this error Field 'id' expected a number but got 'Free'. . i don't really know what is going models.py class Elements(models.Model): title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title") slug = models.SlugField(unique=True, max_length=1000) image = models.ImageField(upload_to="vectors-images/%Y/%m/%d/", default="default.jpg", verbose_name="Image Cover") vec_file = models.FileField(upload_to='vector-uploads/%Y/%m/%d/', null=True, blank=True, verbose_name="Upload File") category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, verbose_name="Category", default="vector") package_category = models.ForeignKey(Package_Category, on_delete=models.DO_NOTHING, verbose_name="Package Category", null=True, default="Free") file_format = models.ForeignKey(Format, on_delete=models.SET_NULL, null=True, blank=True, default="EPS") Views.py @login_required def CreateElement(request): user = request.user categories = Category.objects.all() info = Announcements.objects.filter(active=True) if request.method == "POST": form = CreateElementForm(request.POST, request.FILES) if form.is_valid(): form.instance.creator = request.user element = form.save(commit=False) # ← no commit=False element.slug = slugify(element.title) # element.package_category == "Free" element.save() messages.success(request, f'Hi, Your Element have been sent for review and would be live soon!') return redirect('creators:dashboard') else: form … -
IntegrityError - NOT NULL constraint failed in the `models.DecimalField`
I'm trying to build a models.DecimalField which will set to 50 and will have a range (from 50 to 9000) with a step 50. I have read that I can use choices: "A sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field. If choices are given, they’re enforced by model validation and the default form widget will be a select box with these choices instead of the standard text field.". I have no idea how to fix it. For sure error is in quantity = models.DecimalField. My code: from django.db import models # Create your models here. class ProductInquirie(models.Model): email = models.CharField(null=False, blank=False, max_length=120) # max_lenght required tittle = models.TextField(null=False, blank=False) quantity = models.DecimalField( null=True, blank=True, decimal_places=0, max_digits=4, default=50, choices=[(i, i) for i in range(50, 9000, 50)] ) target_price = models.DecimalField(null=False, blank=True, decimal_places=2, max_digits=7) # Why decimal not float: https://docs.python.org/3/library/decimal.html#module-decimal one_time = models.TextField(default="client didn't provide information, or want constant supply") constant_need = models.TextField(default="no information") how_soon = models.TextField(default="no information") Error: Expected behaviour: It should look like this: Unfold, like this: ...but, without errors when saved(till now the error appears when the "save" button is pressed):) -
How to update a foreign key's attribute after creation of object in Django Model
I'm creating a REST API using Django that has two models that relate to each other: Item and Attribute. An Item has Attribute as a foreign key. The Attribute model has a field called number_of_uses which stores the number of items that attribute has associated it with. I wanted to know how I can update that number on the creation of a new Item. How can I update the field after the creation of the item, but before the API returns a response to the caller? -
Django : Celery configuration with Rabbit MQ inside docker
First of all, i've already got a rabbitmq container that launches with my django vm. That's the docker-compose.yml file : version: "3.8" services: web: build: ./src ports: - "${PORT}:${PORT}" depends_on: - message tty: true stdin_open: true container_name: ${COMPOSE_PROJECT_NAME}_app expose: - ${PORT} links: - message env_file: - .env restart: unless-stopped volumes: - ./src:/code message: container_name: ${COMPOSE_PROJECT_NAME}_broker image: rabbitmq:3.9.12-management ports: - "5672:5672" - "15672:15672" restart: always volumes: - ./data:/var/lib/rabbitmq/ env_file: - .env environment: - RABBITMQ_DEFAULT_USER=${RABBITMQ_DEFAULT_USER} - RABBITMQ_DEFAULT_PASS=${RABBITMQ_DEFAULT_PASS} So after installing celery with pypi and following the First Steps, i've created a file **celery.py ** wich are in the same folder that urls.py and settings.py and reading the docs i've used the same rule to _init.py. celery.py : from __future__ import absolute_import import os from celery import Celery from django.conf import settings # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.base') app = Celery('project') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') init.py : from __future__ … -
My cookies are not setting, when i make request in insomnia my cookies are set
When i send request in Insomnia cookies are set, but on client (Vue) i make request to my backend (django) cookies are not set Expected Behaviour: Cookie is set Actual Behaviour: Response status is 200, but the cookies is not set and shows only in developer tools int the network tab Vue request: methods: { loginUser: function () { fetch(`http://127.0.0.1:8000/auth/login/`, { method: "POST", headers: { "content-type": "application/json", }, credentials: 'include', body: JSON.stringify({ username: this.username, password: this.password, }), }) .then((res) => { return res.json(); }) .then((data) => { window.location.replace(data.url); }) .catch((err) => console.error(err)); }, Django EP: @csrf_exempt def loginUser(request): if not request.method == "POST": return HttpResponse(status=405) data = json.loads(request.body.decode('utf-8')) user = authenticate(request, username=data['username'], password=data['password']) request.session.set_test_cookie() if user is not None: login(request, user) return HttpResponse(json.dumps({'url': 'http://localhost:8081/#/notes'})) else: print('Invalid login') return HttpResponse(status=404) test cookie not working (request.session.set_test_cookie()) def getloggeduser(request): print(request.session.test_cookie_worked()) return JsonResponse({'name': ''}) my setting: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'notesapp.apps.NotesappConfig', 'authentication.apps.AuthenticationConfig', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True -
TemplateDoesNotExist at / index.html (Django)
I'm currently trying to get my full stack app (React and Django 4.0) to deploy on Heroku, but when I load the landing page, I get a TemplateDoesNotExist at / index.html error on the page. Like so: However, I can get the django admin page to load just fine. From what I've seen so far, I think my current problem is in my TEMPLATES settings in my settings.py file, but nothing I have changed has worked for me yet. Here is some of the settings.py file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I was following a tutorial since I'm new to Django and I changed my file structure from two directories (one for front-end and one for back-end) to just one like below: My index.html is still located in the public directory and I'm not quite sure if I need to make a templates folder and relay that path in my settings or not. Here's my urls.py: from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from django.conf import … -
Search Engine Optimisation for a Django website
I made a website with Django but I'm stuck with something. How can handle the SEO? Is there any Django module that can help me achieve that. If there isn't, how can I achieve on my own -
Настройка docker-compose.yaml для vue, redis и django [closed]
Я планирую запускать приложение одной командой из терминала. Однако при конфигурировании docker-compose.yaml столкнулся со множеством проблем и пробелов в своих знаниях. Составив наконец этот файл понял что работает только redis а остальное не запускается. Сам Django работает на postgresql, а redis нужен только для нормальной работы celery, которого я пока не хочу добавлять в docker Структура приложения docker-compose.yaml src/web/static/museum/(фронт приложения на vue.js) src/manage.py python/Dockerfile vue-js/Dockerfile python/Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN pip install poetry==1.1.8 && poetry config virtualenvs.create false WORKDIR /app COPY pyproject.toml . RUN poetry install COPY . . RUN python src/manage.py collectstatic --no-input EXPOSE 8000 CMD python src/manage.py migrate && python src/manage.py runserver 0.0.0.0:8000 vue-js/Dockerfile FROM node:lts-alpine WORKDIR /app/src/web/static/museum RUN npm run serve CMD ["npm", "run", "serve"] docker-compose.yaml version: '3' services: redis: image: redis:6-alpine ports: - 6379:6379 vue: image: node:lts-alpine build: context: ./vue-js dockerfile: Dockerfile ports: - 8080:8080 restart: always app: image: django3.2:latest build: context: ./python dockerfile: Dockerfile depends_on: - redis environment: DB_USER: user DB_NAME: name DB_PASSWORD: password CELERY_BROKER_URL: redis://redis:6379/0 restart: always при запуске docker-compose.yaml выдает ошибку app_1 | connection = Database.connect(**conn_params) app_1 | File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect app_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) app_1 | django.db.utils.OperationalError: could not connect to server: Connection refused … -
Django get queryset through Many To Many extra field
i have a Many-to-Many Relationship between two classes object, i need get queryset filtered by a Many-To-Many extra field that are my 3 classes class Card(models.Model): title = models.CharField(max_length=250 ) tags = models.ManyToManyField(Tag, through='Cards_Tags') class Tag(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) class Cards_Tags(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) card = models.ForeignKey(Card, on_delete=models.CASCADE) field = models.CharField( max_length=25, blank=True ) if i use that it works, but it returns a queryset of Cards_Tags i need same result as Tags objects developers = Cards_Tags.objects.filter(card=obj, field='developer') how i can get Tags queryset where m2m relationship in Cards_Tags have field='developer' ?