Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to apply user specific permission?
I am new in Python Django.I have a question in one situation.As you see in the photos,I have an application.Firstly Users can login system and they can add new item to list.Problem is that when all users login,they are adding items to the same database.For example when 2 users login,they will see same items.I want apply specific list for each user.When each user login,they should see their own list.I know that I have to apply one to many relationship but I don't know how can I do this.I am adding screenshots of related codes. note: my item's model name is Student Application view Item database registered user for authentication from django.db import models class Student(models.Model): sid=models.CharField(max_length=7) sname=models.CharField(max_length=255) scontact=models.CharField(max_length=15) def __str__(self): return self.sname -
AttributeError: 'QuerySet' object has no attribute 'tags' when trying to save quotes and tags with ClusterableModel and ClusterTaggableManager
I am trying to save some quotes from a csv file to my django model using python manage.py shell because I could not use django-import-export to do it. I asked about it at Tags imported but relationship not imported with django-import-export but nobody answered and I could not find more things to try after googling. After reading the documentation and previous answers here about django querysets and tagging, I managed to save most of each quote but the tags are not saved. The query set does not return tags field, which causes the AttributeError. Please see shell output q: <QuerySet... below My tag model follows https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models. From django-admin, the relationships are working. So the missing piece of the puzzle is saving the tags. What query should I use to locate the tags field or what method should I use to save the tags? #The script I'm trying to run in python manage.py shell import csv from quotes.models import Quote, TaggedQuote with open("test_import1.csv", "r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: if row["book"]: item = Quote( text=row["text"], author=row["author"], source_url=row["url"], book=row["book"], ) elif not row["book"]: item = Quote(text=row["text"], author=row["author"], source_url=row["url"]) item.save() for each in row["tags"].split(", "): each = str(each).strip("'") … -
Gunicorn erros in gunicron.service gile
I have got my gunicorn.service file which doesnt seem to be starting when i run it, I have checked my django project for erros but it seems to be running fine [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/ubuntu/env/Django ExecStart=/home/ubuntu/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/env/Django/demo.sock demo.wsgi:application> [Install] WantedBy=multi-user.target when I run systemctl status gunicorn i get the following error: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2021-09-01 10:15:43 UTC; 9min ago Main PID: 30119 (code=exited, status=1/FAILURE) Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: self.stop() Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/arbiter.py", line 393, i> Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: time.sleep(0.1) Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/arbiter.py", line 245, i> Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: self.reap_workers() Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, i> Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Sep 01 10:15:43 ip-172-31-32-179 gunicorn[30119]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Sep 01 10:15:43 ip-172-31-32-179 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Sep 01 10:15:43 ip-172-31-32-179 systemd[1]: gunicorn.service: Failed with result 'exit-code'. lines 1-15/15 (END) I have tried looking for different fixes but not sure what i am doing wrong here or if i am … -
I'm testing my API through Postman and I'm using Django Rest Framework and I'm uploading a file and other data also
I want to upload file and other data through postman it is saving the file but it is an empty []. model.py class ServiceProjectAnswer(models.Model): project = models.ForeignKey(ServiceProject, on_delete=models.DO_NOTHING, related_name='project_answers') question = models.ForeignKey(ServiceQuestion, on_delete=models.DO_NOTHING, related_name='project_questions') answer = models.CharField(max_length=500, blank=True, null=True) class Meta: db_table = "pm_service_project_answer" verbose_name = 'service project answer' verbose_name_plural = 'service project answers' def project_files(instance, filename): #file will be uploaded to MEDIA_ROOT/epc/projects/<project_id>/filename return 'epc/projects/{0}/{1}'.format(instance.answer.project.id, filename) class AnswerAttachments(models.Model): # answer = models.ForeignKey(ServiceProjectAnswer, on_delete=models.DO_NOTHING, related_name='answer_attachments') answer = models.ForeignKey(ServiceProjectAnswer, on_delete=models.DO_NOTHING, related_name='attachement') attachement = models.FileField(upload_to=project_files, blank=True, null=True) class Meta: db_table = 'pm_answer_attachment' verbose_name = 'answer attachement' verbose_name_plural = 'answer attachements' serializer.py This is a attachment serializer class AnswerAttachmentsSerializer(serializers.ModelSerializer): class Meta: model = AnswerAttachments fields = '__all__' This is the answer serializer from where I am saving answer and attachment both class ServiceProjectAnswerSerializer(serializers.ModelSerializer): attachement = AnswerAttachmentsSerializer(many=True) def create(self, validated_data): attachement = validated_data.pop('attachement') answer = ServiceProjectAnswer.objects.create(**validated_data) attachment = AnswerAttachments.objects.create(answer=answer, attachement=attachement) return answer class Meta: model = ServiceProjectAnswer fields = ('project', 'question', 'answer', 'attachement') This is my view class ServiceProjectAnswerViewSet(viewsets.ModelViewSet): model = ServiceProjectAnswer serializer_class = ServiceProjectAnswerSerializer parser_classes = (MultiPartParser, FormParser,) This is my response in post man { "project": 1, "question": 3, "answer": "My name is vikrant patil", "attachement": [ { "id": 21, "attachement": "http://localhost:8000/media/%5B%5D", "answer": … -
django-ckeditor is not rendering in Heroku
I am using django-ckeditor == 6.1.0 for my django app and its working fine when I am running it locally. But after deploying it on heroku its not rendering and I am getting only the usual django form. Am I missing something? -
'list' object has no attribute 'all'
I am building a Book Blog App and I am trying to get cleaned_data in creation form and I am implementing a feature in which "User can add multiple books (like tags) in blogpost which are saved in another model" And If any of book name (Book Tag) mentioned in the form not in the Book List than It will show error "You cannot create a new book name" So I made an if else statement to check if typed book name is in existing book in Book Model BUT Than it worked perfectly BUT The Problem occurred When someone types 3 book names and one of them book name is in saved book name than , it will not see other book names which are not saved (It is saving the post), So it will not show error So I think I would access all the mentioned book names mentioned in form by .all() method ( So it will check if any of book name is not in the existing names) but this error is keep showing. 'list' object has no attribute 'all' What I am trying to do :- I am trying to check all the mentioned names … -
Why the django run command "python3 manage.py runserver" does not execute in docker-compose?
What Is The Problem? I have a Dockerfile, docker-compose.yml and a run.sh script that runs my django server with so many configurations that work just fine and everything is tested but... the server does not run at the end on python3 manage.py runserver 127.0.0.1:80 command inside run.sh bash script. I searched everywhere but didn't find any solution at all. If someone can guide me what the problem is, I would be so thankful because I literally lost two days of my life in the process of running a simple django server with docker-compose. Included Files This is my docker-compose.yml file: version: "3.9" services: backend: build: context: . dockerfile: backend.Dockerfile restart: always image: backend:latest container_name: backend networks: - net dns: backend volumes: - /project/backup:/project/backup --name backup volumes: backup: name: "backup" networks: net: name: net driver: bridge And this is my Dockerfile which you just need to read the last CMD line at the end cause the other else commands on top of it work just fine: # This is the only latest version of alpine that actually works with uwsgi FROM python:3.8-alpine3.10 # for mysql and postgres RUN set -ex \ && apk add --update --no-cache --virtual build-deps \ make \ … -
Different url path just for one article (Django)
I need to change url path just for one chosen article. This is how it looks for all of my articles: site.com/articles/some-article I would like to create some condition just for one chosen article. site.com/chosen-article is it possible? urls.py urlpatterns = [ url(r'^articles/', include('mysite.articles.urls')), ] -
Django Background task schedule using apscheduler?
I am using apscheduler for my django project background scheduling. I set the time for trigger as hours=2. But it is always triggering after 10 seconds. Now tell me what is that interval and why it is not triggering after 2 hours. Execution of job "my_scheduled_job (trigger: interval[0:00:10], next run at: 2021-09-01 15:21:40 +06)" skipped: maximum number of running instances reached (1) from apscheduler.schedulers.background import BackgroundScheduler from .jobs import my_scheduled_job def start(): scheduler = BackgroundScheduler() scheduler.add_job(my_scheduled_job, 'interval', hours=2) scheduler.start() -
Django: defining a slugify aggregator
I'd like to define a custom aggregator which would allow me to annotate in querysets a slug, this slug being generated from the object ids from a subquery ("1-12-52-34"). Any help would be appreciated. qs = my_model.objects.annotate(id_slug=Slugify(my_subquery)) -
how can get post value with key in dajngo
how can access post values with index as key in view.py in dajngo I need split values based on same key This is my post value <QueryDict: {'csrfmiddlewaretoken': ['b5cJ9z5zqWdMrUN8wyUvpQMjt7KeEy1bfWwjzia1KajUHWfI9OvXvxtOLNcB0HLW'], 'product_id': ['3'], 'include_product_id[x_808903]': ['1'], 'index_val': ['x_808903', 'x_152554'], 'product_name[]': ['ISOPURE AMINOS-(ALPINE PUNCH-10.05 OZ)', 'SYNTHA-6 EDGE-(CHOCOLATE MILKSHAKE-48 SERVING)'], 'product_qty[x_808903]': ['10'], 'product_price[x_808903]': ['1'], 'total_amount[x_808903]': ['10'], 'include_product_id[x_152554]': ['3'], 'product_qty[x_152554]': ['2'], 'product_price[x_152554]': ['2'], 'total_amount[x_152554]': ['4'], 'submit': ['Submit']}> I am trying this way to access but its not working for index in index_val: include_product_id =request.POST['include_product_id'+[index]] product_price =request.POST['product_price'+[index]] Anyone please help me -
How to add DjangoFilterBackend in APIView of Django rest framework?
I am trying to add all CRUD operations into a single endpoint using APIVIEW in DRF, as I have heard, thats what senior developers do (all apis into a single endpoint). But in get request, I have to use a Filterbackends, pagination and also some custom filter logic. I have succeeded in adding custom pagination and the custom filter logic inside the get function but have troubled to add the Filterset_class. Here is my view: class LeadsView(APIView): permission_classes = [IsAuthenticated] def get(self, request, pk=None, *args, **kwargs): id = pk if id is not None: abc = Lead.objects.get(id=id) serializer = LeadSerializer(abc) return Response(serializer.data,status=status.HTTP_200_OK) else: source = self.request.GET.get("source", None) # lead_status = self.request.GET.get("lead_status", None) if source is not None: source_values = source.split(",") if lead_status is not None: lead_status_values = lead_status.split(",") abc = Lead.objects.filter(source__in=source_values, lead_status__in=lead_status_values) else: abc = Lead.objects.filter(source__in=source_values) paginator = CustomPagination() result_page = paginator.paginate_queryset(abc, request) serializer = LeadSerializer(result_page,many=True) elif lead_status is not None: lead_status_values = lead_status.split(",") if source is not None: source_values = source.split(",") abc = Lead.objects.filter(lead_status__in=lead_status_values, source__in=source_values) else: abc = Lead.objects.filter(lead_status__in=lead_status_values) paginator = CustomPagination() result_page = paginator.paginate_queryset(abc, request) serializer = LeadSerializer(result_page,many=True) else: abc = Lead.objects.all() paginator = CustomPagination() result_page = paginator.paginate_queryset(abc, request) serializer = LeadSerializer(result_page,many=True) # return Response(serializer.data,status=status.HTTP_200_OK) return paginator.get_paginated_response(serializer.data) def … -
AttributeError: '_Environ' object has no attribute 'Env'
i am trying to host a website in google cloud in settings.py file need to write some code after writing the code i am facing below error env = environ.Env(DEBUG=(bool, False)) AttributeError: '_Environ' object has no attribute 'Env' -
Follow Public/Private user validation for serializer
I have a User and UserFollow model. Author is the following user,Profile is the user that is followed. Now i am using Token authentication to validate users for unauthorized requests. Here is what i want to put into validation but i don't know how to do it: Pseudocode if profile.public_profile == true if attrs['author'].id != self.context['request'].user: raise ValidationError('Unauthorized Request') if profile.public_profile == false if attrs['profile'].id != self.context['request'].user: raise ValidationError('Unauthorized Request') I don't know how to put multiple IF conditions under a validation. How can i do it? Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username =models.CharField(max_length=40,unique=True,default='undefinedusername') public_profile = models.BooleanField(default=True) class UserFollow(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') profile = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') Serializers.py class UserFollowSerializer(serializers.ModelSerializer): class Meta: model = UserFollow fields = ('id',"author","profile") def validate(self, attrs): attrs = super().validate(attrs) if attrs['author'].id != self.context['request'].user: raise ValidationError('Unauthorized Request') return attrs -
Cannot get data into my database using django model forms
The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to do so instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that entered is saved anywhere? Here are the files below hopeful someone can see something I'm missing. ps. I've connected my database, ran migrations and created a superuser as well but still nothing. models.py from django.db import models Media_Choices = ( ("TV", "TV"), ("Radio", "Radio"), ("Youtube", "Youtube"), ("Podcast", "Podcast"), ) class Appear(models.Model): Show = models.CharField(max_length=100) Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices) Episode = models.IntegerField() Date = models.DateField(max_length=100) Time = models.TimeField(auto_now=False, auto_now_add=False) Producer = models.CharField(max_length=100) Producer_Email = models.EmailField(max_length=254) def __unicode__(self): return self.Show + ' ' + self.Producer_Email forms.py from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Appear class AppsForm(ModelForm): class Meta: model = Appear fields = '__all__' def clean_Producer_Email(self): Producer_Email = self.cleaned_data.get('Producer_Email') if (Producer_Email == ""): raise forms.ValidationError('field cannot be left empty') for instance in Appear.objects.all(): if instance.Producer_Email == Producer_Email: raise forms.ValidationError('Please fill in correct email') return Producer_Email views.py from django.shortcuts import redirect, … -
How to simulate two parallel requests in django testing framework
I have a Django application (using uWSGI and nginx, and atomic views) with a view that creates new items of a model in the DB (postgres). Before creating anything the view checks if the record doesn't already exist in the DB, something like: ... try: newfile = DataFile.objects.get(md5=request.POST['md5']) except DataFile.DoesNotExist: newfile = DataFile.objects.create(md5=request.POST['md5'], filename=request.POST['filename']) return JsonResponse({'file_id': newfile.pk}) I noticed sometimes this doesn't work, and I get duplicates in the DB (which is easily solved with a unique constraint). I'm not sure why this happens, if there is caching or race conditions, but I'd like to at least cover the behaviour with a test in the Django test framework.However, I do not know how to simulate two parallel requests. Is there a way to fire the next request while not waiting for the first, built into the framework, or should one use multiprocessing or similar for this? -
How to send chat messages to other users
I want to send messages to other users so that I can have a discussion with them on the messenger. models.py class Message(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null = True, on_delete= models.CASCADE, related_name='user') receiver = models.ForeignKey(settings.AUTH_USER_MODEL, null = True, on_delete= models.CASCADE, related_name='receiver') message = models.CharField(max_length=300) time = models.DateTimeField(auto_now_add=True) time_seen = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['time'] def __str__(self): return self.message -
ImportError: No module named 'django' [closed]
I am using django to make my site on server. But, I get the error. from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' I try to add some code in wsgi.py, but I still can't fix it. import os, sys sys.path.append('<PATH_TO_MY_DJANGO_PROJECT>/ueuuop8591_project') sys.path.append('<PATH_TO_VIRTUALENV>/Lib/site-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ueuuop8591.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Tabulator breaks after setData is being called first time
I have a weird bug in my application using Tabulator by @Oli Folkerd: After refreshing the table I always end up with having 20 rows instead of my preset 25 rows: I checked the response from my django ViewSet and the answer always contains the right amount of objects. js Code: var table = new Tabulator("#ptable", {height:"100%", layout: "fitData", pagination: "local", paginationSize: 25, paginationSizeSelector: [50, 100], ajaxURL: "api/products", columns: cols,}); setInterval( function () { table.setData(); }, 10000); becomes: I am happy to post code on the django part as well, but I do not think thats the problem here. Also interesting: When I click on a random page number in the footer I always get to see 20 items per page - except if I choose the last one. -
Django generate PDF css error and rendering is slow
I want to print my products in Django as PDF. But because the file size is very large, it takes minutes to load. My CSS styles are not applied either. If your need another codeblocks, I will share with you. If you give me the source, I can take a look at it. def render_pdf_view(request): .......my context codes....... template_path = 'catalogmakerpdf.html' context = { 'products': products, } response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response, link_callback=link_callback) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response utils.py (imported views.py) from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result, link_callback=fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def fetch_resources(uri, rel): path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")) return path -
Django Generate List of Opposite Models
I am trying to develop a program that will determine what plants are beneficial and harmful to other plants. I want it to be able to run through a list of plants and compare and see if one plant's deters_insects_and_animals species matches the other plant's pests then it adds it to the list in ally_deter_pests_for(self): I'm not really sure how to do that. class AnimalSpecies(models.Model): common_name = CharField(max_length = 200, null = True, blank = True) scientific_name = CharField(max_length = 200, null = True, blank = True) genus = Foreign Key(Genus, null = True, blank = True, on_delete = models.CASCADE) class Meta: verbose_name = "Animal Species" verbose_name_plural = "Animal Species" def __str__(self): return self.common_name #___________________________________________________________________________________Begin Species_______________________________________________ class PlantSpecies(models.Model): #________________________Name & Relationships________________________ common_name = CharField(max_length = 200, null = True, blank = True) species_name = CharField(max_length = 200, null = True, blank = True) genus = ForeignKey(Genus, blank = True, null =True, on_delete = models.CASCADE) rotation_family = ForeignKey(RotationFamily, blank = True, null = True, on_delete = models.CASCADE) #________________________Growth & Environment________________________ annual = BooleanField(null = True, blank = True) GROWTH_HABIT_LIST = [ ("H", "Herb"), ("S", "Shrub"), ("T", "Tree"), ("U", "Succulent"), ("G", "Grass"), ("F", "Fern"), ("V", "Vine") ] growth_habit = CharField(max_length = 20, … -
How to add multiple owners to the django filer folders?
I want to add multiple owners to the django filer user created folders. Is it possible if not what can be the alternative solutions to this ? I can see here https://github.com/django-cms/django-filer/blob/master/filer/models/foldermodels.py that owner has FK with the Folder but can we change it to ManyToMany so that I can add multiple owners to the folder. Anyone out there with experience on django-filer ? -
My friend request module for my app doesnt work
I am implementing a friend module into my app and it has errors with the friend request part. I want it so that when the someone puts a username into the form and clicks submit, it POSTs the username to the same page. Then my app does quick search thru the user table and if it find the username it adds the person who sent the request to the requestee's manytomany field. But when I tried it, it did in fact succeed add the request, but for some reason it also added a friend request to the requestors m2m with it saying its from the requestee. My view for the friend requesting: def friends(request): friendreqs = request.user.friendreq.all() friends = request.user.friends.all() if request.method == "POST": try: requestee = User.objects.get(username=request.POST["username"]) requester = request.user requestee.friendreq.add(requester) return render(request, "alumnas/friends.html", { 'requests': friendreqs, 'friends': friends }) except ObjectDoesNotExist: return render(request, "alumnas/friends.html", { 'message': "User not found :(", 'requests': friendreqs, 'friends': friends }) else: return render(request, "alumnas/friends.html", { 'requests': friendreqs, 'friends': friends }) The html: {% extends "alumnas/layout.html" %} {% block body %} <div class="contain"> <h1>Friends</h1> <div class="findfr"> <p>Know anyone already? Find out if they're here and connect!</p> <form action="{% url 'friends' %}" method="POST"> {% csrf_token … -
Django: Get the ManyToMany object of ManyToManyField
I know I can fetch all authors of literature like: paper.authors.all() This works fine, but just returns me a QuerySet of Authors. But I want the ManyToMany Object like (because I want to sort after the ID's) (id (BigAutoField), paper, author) Is there a faster way to do it then: Paper.authors.through.objects.all().filter(paper=paper) Because my Database is really Large ~200 million entries, the command above is not feasible -
How to apply one to many relationship in my situation?
I am new in Python Django.I have a question in one situation.As you see in the photos,I have an application.Firstly Users can login system and they can add new item to list.Problem is that when all users login,they are adding items to the same database.For example when 2 users login,they will see same items.I want apply specific list for each user.When each user login,they should see their own list.I know that I have to apply one to many relationship but I don't know how can I do this.I am adding screenshots of related codes. note: my item's model name is Student Application view after login Models.py file(Student model is for item views.py Item database registered user for authentication