Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Media File is not found on production (404)
I have wondered around lot of other stackoverflow issues to see if there is a solution but i couldn't work around it. So here is the issue: Nginx.conf location /media/ { alias /root/server/media/; } location /static/ { alias /root/server/static/; } urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static/'),) STATIC_ROOT = os.path.join(BASE_DIR, '/static/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' wsgi.py application = WhiteNoise(application, root=os.path.join(BASE_DIR, 'static')) application = WhiteNoise(application, root=os.path.join(BASE_DIR, 'media')) I have set everything as necessary, i check the directory (root/server/media) and images are there. But when i enter the link : media/images/1.png , it gives me 404 (Not found) error. Does anybody know why? -
How to make nginx check authentication status from the old backend in the new backend?
I have two Django backends (old and new): Old backend (old endpoints worked with authentication system based on jwt tokens) New backend (new endpoints without any authentication system) I can't add authentication system for the new backend for some reasons, so I want to check user authentication status from the old backend and give access for the new backend new endpoints if this user logged. So, I tried to use ngx_http_auth_request_module, but I get 404 error instead of json response after succeded case: [error] 32#32: *6 "/etc/nginx/html/v2.0/private/index.html" is not found (2: No such file or directory) while sending to client, client: 172.18.0.1, server: , request: "POST /v2.0/private/ HTTP/1.1", host: "localhost" nginx.conf: server { listen 80 default_server; location /v1.0/ { proxy_pass http://old_backend:8000; } location /v2.0/ { proxy_pass http://new_backend:8002; } location /v2.0/private/ { auth_request /v1.0/profile/; } location = /v1.0/profile/ { proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_pass http://old_backend:8000/v1.0/profile/; } Can I solve my problem with ngx_http_auth_request_module or do I need to find anouther solution? -
Django - Displaying alert messages in base template
I am displaying alert messages in my base template with a simple for loop. My issue is that when the message gets displayed it pushes down the div for whatever page is getting the alert. Obviously this is because for the alert I am creating a new div and inserting it at the top of the page but I was wondering if there was a better way to do this? I could solve this issue but just hard coding the message inside of the div into the specific pages where I want the message to be displayed but I would prefer leaving it in the base template if possible. Is there some way with css that I could possibly make the div display on top of another div maybe? Or maybe simply just changing how my messages displayed will fix it? I have tried a few different solutions and fit for what I need. Any help is greatly appreciated! base template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %} {% endblock %}</title> {% block extra_head %} {% endblock %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> {% block css_files %} … -
How to increment slot field when booking an appointment
Doctor model class Doctor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) qualifications = models.CharField(max_length=100) expertise = models.CharField(max_length=100, default='Cardiac') fee = models.IntegerField(default=500) slots = models.IntegerField(default=0) def incSlots(self): self.slots = self.slots + 1 Appointment model class Appointment(models.Model): appointment_id = models.AutoField(primary_key=True) patient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blood_pressure = models.CharField(max_length=10) BMI = models.CharField(max_length=10) blood_sugar = models.CharField(max_length=10) HB = models.CharField(max_length=10) platelets = models.CharField(max_length=10) date = models.CharField(max_length=30) time = models.CharField(max_length=30) detail = models.TextField() doc = models.OneToOneField(Doctor, on_delete=models.CASCADE) Appointment view def appointment(request): docname = request.POST.get('doc_name') if request.method == 'POST': form = AppointmentForm(request.POST) if form.is_valid(): form.doc.incSlots() form.save() return redirect('success') else: print(form.errors) form = AppointmentForm(initial={"patient":request.user, "doc_name": docname}) return render(request, 'appointment.html', {'form': form}) I want to increment "slot" field when booking an appointment, I have no idea how to do it, i am new to django, i'll appreciate any help Thank you. -
How to get the limit value from the django API URL
from the below Url, I need the limit, to do some operations in my view http://127.0.0.1:8000/emp/?limit=10&offset=5 I tried using the below things but no luck if request.limit>5: do something... if kwargs['limit'] >5: do something.... -
Relation does not exist error in Django after postgresql integration
I used sqlite3 during development, then changed my database settings to postgresql: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test2', 'USER': 'postgres', 'PASSWORD': 'aman', 'HOST': 'localhost', 'PORT': '5432', } } Regardless of any command I write, it gives me the error: django.db.utils.ProgrammingError: relation "taksist_category" does not exist LINE 1: ...st_category"."id", "taksist_category"."name" FROM "taksist_c... Category model exists inside taksist application. If I take back my database settings to sqlite3, then application runs successfully. I cannot even run my server. Even if there is a problem with my model taksist/Category, my application should run. Here strange thing is whatever command is written, I got this error. I cannot do makemigrations, migrate, runserver. What did I do to solve the issue: deleted migrations folder, and tried makemigrations I created empty migrations folder with init.py inside, and tried makemigrations python manage.py migrate --fake none of above worked. Any help of yours is appreciated. thank you in advance. -
Download a zip file with Django, no errors showing but nothing happens
I'm currently developping a django web application and I'm struggling for downloading a zip file I'm trying to create a zip with nifti binary files. I get the path of my data with this form : <form action="" method="POST" id="form-sequence"> {% csrf_token %} <input type="hidden" name="data-path" id="data-path" value=""> </form> And I use jquery for posting the form like that (the variable data-path is an array of path) : document.getElementById("data-path").value = data_path; var form = $("#form-sequence"); var posting = $.post(form.attr('action'), form.serialize()); posting.done(function(data) { console.log("Exported !") }); As a result I got a 200 response from this request (I linked a screenshot of the response) With Django, in my view, I get the form data like this : if (request.POST.get('data-path')): data_path = request.POST.get('data-path').split(",") print(f"{data_path = }") zip_dir = "C:/dir/to/zip/" zip_path = os.path.normpath(os.path.join(zip_dir, "data.zip")) zip_file = zipfile.ZipFile(zip_path, "w") for file in data_path: filename = os.path.normpath(file) zip_file.write(filename) zip_file.close() # wrapper = FileWrapper(open(zip_path, 'rb')) # response = HttpResponse(wrapper, content_type="application/zip") response = HttpResponse(open(zip_path, 'rb'), content_type="application/zip") response["Content-Disposition"] = "attachment; filename=data.zip" print(response) return response As you can see, I tried to use FileWrapper without success. I also printed the response in the view file and I always got : <HttpResponse status_code=200, "application/zip"> But unfortunately, the Windows popup for … -
Django : How to get month data in week wise format in django( Eg : I need last 50 days of data in 10 , 10 , 10, 10 , 10 format )
Django query : Get last 50 days of data from database in ( 10 days, 10 days etc.. ) format -
Usage django.template.engine.Enginge.get_default
What for Enginge.get_default method? Do i need to call it if i want to render a string? What does i mean: from django.template import Template, Context template_code = "Hello, {{ friend_name }}" context = Context({"friend_name": "Andrew"}) Template(template_code).render(context) Or from django.template.engine import Enginge get_template = Enginge.get_default().from_string template_code = "Hello, {{ friend_name }}" context = Context({"friend_name": "Andrew"}) get_template(template_code).render(context) I am writing a reusable application and want to know if using Enginge.get_default is similar to get_user_model (in case of redefinition). If yes, should get_default be constantly called? Or only need to get the value once by storing the value in a namespace variable. -
Django can't load ckeditor in the admin page
This is my settings.py file INSTALLED_APPS = [ 'search.apps.SearchConfig', 'user.apps.UserConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django_node_assets', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_BASEPATH = "./search/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "/media/" This is the models.py file from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField class Content(models.Model): heading = models.ForeignKey(SubTopics, on_delete=models.CASCADE) content = RichTextField() def __str__(self): return self.heading.heading This rich text editor is not showing on the admin page. Even no text field is shown on the page, just blank space. -
No User matches a given query Django
While trying to display post-detail template in a blog app, I get an error No User matches a given query. In my models I am inheriting from User model. What seems the problem? # Third party imports. from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils import timezone class Post(models.Model): """ Creates Model for a post in the database. """ title = models.CharField(max_length=100) sub_title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """ A string representation of the post model. """ return self.title def get_absolute_url(self): """ Creates the absolute url for a particular post. """ return reverse('blog:post-detail', kwargs={'pk': self.pk}) views.py class PostDetailView(DetailView): """ View for a post's details """ model = Post template_name ='blog/post_detail.html' context_object_name = 'posts' paginate_by = 3 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') home.html {% extends 'blog/base.html' %} {% load static %} {% block crumb %} {% for post in posts %} <div class="post-preview"> <a href="{% url 'blog:post-detail' post.id %}"> <h2 class="post-title">{{ post.title }} </h2> <h3 class="post-subtitle">{{ post.sub_title }} </h3> </a> <p class="post-meta" style="font-weight: 300;"> Posted by <a class="text-muted">{{post.author}} on {{ post.date_posted|date:"F d, Y" }}</a> </p> </div> <hr class="my-4" /> {% endfor %} {% … -
How to add status to registered accounts with google account
I want to add status to the accounts registered with the google / facebook account in the postgreSql database, I added the status column in the database. What I do: When I register with my google / facebook account I direct the user to a page where he has a status to choose and depending on the status to be sent to a page, but no status is saved in the database. Any ideas? In the Python language with Django framework. Thanks -
django how to disable & enable email verification in admin panel
I'm working on a Django project and i want to be able to disable or enable email registration verification in admin panel, with a radio button, if it's set to ON, when user registers to site need to verify email, but if it's set to OFF user account activate after registration and don't need to activate account with email verification -
I am having trouble in passing a specific image in my template from Django models
Models.py class BaseLogo(models.Model): logolabel = models.CharField(max_length = 100, null = False, blank = False) logoimage = models.ImageField(null = False, blank = False) def __str__(self): return self.logolabel Views.py def base(request): baselogo = get_object_or_404(BaseLogo, pk=1) context = { 'baselogo': baselogo, } return render(request, 'pages/base.html', context) Template <a class="nav-brand" href="{% url 'main-home' %}"> <img src="{{ baselogo.logoimage.url }}" alt="VCAAT Logo" title="VCAAT Logo" style="width: 60px; height: 60px; float: left; margin-left: 20px; margin-right: 20px;"></a> Notes: It is in NavBar I have a gallery app and I also have profile pictures, so I was able to pass images before. The website is uploaded in pythonanywhere. I have an image uploaded in admin page I don't understand what is wrong why my image (logo) would not appear. -
Append server name in a API response -- Django rest framework
I have been trying to create a API with Django restframework. There is a Image field in the API which is giving a relative path. I would like to have absolute path or name of the server to append before the Image field. But its throwing an error TypeError: string indices must be integers I believe the json that I created from the ordered dict is a string and is not giving expected output. Problem: I need to access the json keys and append server name in it. I tried the following for it. views.py def get_individualmember_details(request): if request.method == 'GET': serializer = MasterIndividualMembersSerializer(MasterIndividualMembers.objects.all(), many=True) result = json.dumps(serializer.data) print(result) for row in result: if row["member_photos"]["image"]: row["member_photos"]["image"] = request.META['HTTP_HOST'] + "/" + row["member_photos"]["image"] result = json.dumps(result) return JsonResponse(json.loads(result), safe=False) expected output: [ { "individualmemberId": "1", "member_photos": [ { "id": 25, "image": "http://127.0.0.1:8000/individualmemberphotos/user.jpeg", // need to append servername here "individualmemberId": "1" } ], ... ... ] current output without the logic above: [ { "individualmemberId": "1", "member_photos": [ { "id": 25, "image": "individualmemberphotos/user.jpeg", "individualmemberId": "1" } ], ... ... ] Please suggest how to append the server name or a string before any json key. Thanks in advance! -
Using distinct() function in list. distinct function is not working in list
I am building a Blog App AND I am filtering many queries in one view. I mean, I am filtering two posts which are posted by request.user and By request.user's friends. AND appending all the filtered results in list. BUT when i append all the results then duplicate posts are showing in browser. Then i used distinct() function in list then the error is showing :- 'list' object has no attribute 'distinct' models.py class BlogPost(models.Model): user = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) title = models.CharField(max_length=500,default='') favourites = models.ManyToManyField(User, related_name='favourites ', blank=True) views.py def all_blogposts(request): ALL_POSTS = [].distinct() #Adding user's post in the list. user_post = BlogPost.objects.filter(favourites =request.user)[:5] for post in user_post: ALL_POSTS.append(post) #Adding friend's post in the list. all_posts = BlogPost.objects.all() requested = request.user.profile.friends.all() for user_p in requested: for sets in user_p.user.blogpost_set.all(): ALL_POSTS.append(sets) context = {'ALL_POSTS':ALL_POSTS} return render(request, 'all_posts.html', context) When i use distinct() and check then the error is keep showing. I also tried to use distinct() after [:5] in user_post but then it shows. Cannot create distinct fields once a slice has been taken. Many Duplicate posts are showing. Any help would be Much Appreciated. Thank You in Advance. -
How can I do a Django query where I can filter on a dict?
I am trying to do a query using Django but I got a problem, here is my query : A = User.objects.filter(country['Europe']['South']='Italy') But it does not work ... Could you help me please ? Thank you very much ! -
Exclude objects in queryset based on objects in array
Let's say I have a queryset <InheritanceQuerySet [<Object(1)>, <Object(2)>, <Object(3)>, <Object(4)>]> and an array with 2 objects that are the same objects as in the queryset arr = [<Object(2)>, <Object(4)>] I'd like to keep the 2 objects that are in the array in the QuerySet and filter all the rest out of it. -
Django : How to upload CSV file in unit test case using APIClient from rest_framework
def test_upload_csv_success(self): """Test uploading a csv file""" with open("innovators.csv", "w") as file: writer = csv.writer(file) writer.writerow(["SN", "Name", "Contribution"]) writer.writerow([1, "Linus Torvalds", "Linux Kernel"]) writer.writerow([2, "Tim Berners-Lee", "World Wide Web"]) writer.writerow([3, "Guido van Rossum", "Python Programming"]) with open("innovators.csv", "r") as file: res = self.client.post( CSV_URL, {"file": file}, content_type="multipart/form-data" ) file.close() self.assertEqual(res.status_code, status.HTTP_201_CREATED) #self.assertIn('file', res.data) #self.assertTrue(os.path.exists(self.csv_model.file.path)) Below is the error, I/m getting System check identified no issues (0 silenced). .F. FAIL: test_upload_csv_success (core.tests.test_csv_api.CsvUploadTests) Test uploading a csv file Traceback (most recent call last): File "/Users/rounaktadvi/django_rest_api_projects/csv-store-api/core/tests/test_csv_api.py", line 56, in test_upload_csv_success self.assertEqual(res.status_code, status.HTTP_201_CREATED) AssertionError: 400 != 201 -
Multiprocessing with Django - fork causes random deadlocks
i've tried to start django multiprocess pool with fork context, but without any-apparent-reason, sometimes, the main application (that control the pool) freezes, without doing anything else. This is how i start my pool: model_instances = [instance1, instance2, instance3, instancen] with multiprocessing.get_context('fork').Pool(multiprocessing.cpu_count()) as pool: pool.map(_run_par_task, model_instances) After looking at this page, i've seen that it describes my issue, and i suspect that sometimes, the fork method causes some deadlocks. So, i've tried to use the spawn method to manage my pool, as following: model_instances = [instance1, instance2, instance3, instancen] with multiprocessing.get_context('spawn').Pool(multiprocessing.cpu_count()) as pool: pool.map(_run_par_task, model_instances) ...but i'm getting this error message: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. That clearly indicates that django apps are not loaded in the child process. Basically, i need to work in the child process with Django models, so, how i can load the django app in the child spawned processes? -
How to check user is a member of model object or not in Django?
I wrote this models in model.py class Group(models.Model): MEMBERS_NUMBER = [ (2, 'Two people'), (5, '3 to 5'), (10, '5 to 10'), ] group_name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) members = models.IntegerField(choices=MEMBERS_NUMBER) people = models.ManyToManyField('Profile', through='Membership', blank = True) summary = models.TextField( 'Summary and indeas', max_length=500, help_text='Say what you want to do with your study or jub partner.' ) date_created = models.DateTimeField(default=timezone.now) and class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(blank=True, null=True) profile_picture = models.ImageField(default = 'default.jpeg', upload_to = 'profile_pics', null=True, blank = True) date_joined = models.DateTimeField(default=timezone.now, null=True, blank = True) and class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) members = models.ForeignKey(Profile, on_delete=models.CASCADE) then i created generic class-based view for every object of Group model but i want to limit access to only profiles in that Group object, this is my class-based view: class GroupDetail(UserPassesTestMixin, generic.DetailView): model = models.Group context_object_name = 'group' template_name = 'projects/group_detail.html' def test_func(self): return self.request.user.profile.group_set.filter(group_name='My-Django-Group') def get_queryset(self): return models.Group.objects.all() The test_func(self) checks if user is member of 'My-Django-Group' then show the group details to user but i want to get the object name that we are in it, i tested this: def test_func(self): return self.request.user.profile.group_set.filter(group_name=self.group.group_name) but it didn't work -
Save HTML tables locally in the Angular/Django
I'm new in full stack development and its a lot of try and error. Now I'm struggling with html tables. For explanation: I am building a simple web app that can show tables from Azure SQL Database. I am able to input the tables through backend connection (Django) to the Frontend(Angular) for representation. but, every time I reload the app, all data from the table are gone and it starts calling the tables again. it would be great to save this tables permanently because the tables are so large and it takes a long time to fetch them again. what's the best way to achieve this? -
How to get input values from a row in a django template
I have a table and want to see the elements, and some inputs in the fields which i want to edit. I have too two buttons, one to edit the row and another to delete the row. My problem is to get the id and values of only this row becouse I´m only avaliable to get the last row, no matters which button I press. Overview html: {% for zona in zonas %} <tr> <td> <input type="text" value="zona" id="{{zona.zona}}" name="zona" class="editable form-control"> </td> <td> <input type="text" value="red" id="{{zona.red}}" name="red" class="editable form-control"> </td> <td> {{ zona.soft_low }} </td> <td> {{ zona.soft_medium }} </td> <td> {{ zona.soft_high }}</td> <td style="display: grid"> <button type="submit" name='update' class="btn btn-success"><i class="fas fa-upload"></i></button> <button type="submit" name='delete' class="btn btn-danger"><i class="fas fa-trash"></i></button> <input type="hidden" name="zonaides" value="{{zona.zonaid}}"> </td> </tr> {% endfor %} -
How to host a django website in hostgator?
I want to host a my django website on hostgator but i don't know how to host a website in hostgator please help me can you please provide a link for hosting a django website on hostgator -
How to restart running task and pending task in celery once worker is forcefully shutdown?
My problem is i am running task in celery which take 10 to 15 minutes to complete but what problem come is How to i restart task which currently running in worker and also one which is currently not running but waiting for task to run while i forcefully stopped worker or in case my server got crash or stopped. What happens right now is if i start celery again it's not starting the last running task or remaining task.