Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to put a margin in sidebar using CSS properly in Django>
I tried to put margin to separate text and icon using this code {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/styles.css'%}"> <!-- <link href="{% static 'css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="{% static '/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> --> <link href="{% static 'css/bootstrap.min.css'%}" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="{% static 'fontawesomefree/js/all.min.js' %}"></script> <title>Document</title> </head> <body> <div class="sidebar"> <header>Menu</header> <a href="#" class="active"><i class="fas fa-qrcode"></i><span>Dashboard</span></a> <a href="#"><i class="fas fa-link"></i><span>Data Entry</span></a> <a href="#"><i class="fas fa-stream"></i><span>List</span></a> </div> </body> </html> CSS code a.active,a:hover{ border-left: 5px solid #019321; color: #bfeb74; } .sidebar a i{ margin-right: 300px; enter image description here It should look like this. Same code that put in codepen.io. enter image description here -
Django RF ModelSerializer get current user's userid
I want to move all my create,update method from my views to serializer.py, I read keep your views thin while serializer fat. class APIClerkView(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] serializer_class = ClearanceItemSerialize def perform_create(self, serializer): serializer.save(recorded_by=self.request.user.userid) here I have simple create that save the current user userid to recorded_by, How can I do that in my ModelSerializer -
How to make a fullstack mobile application which handle comments like Facebook
I have a huge question, Do you have any ideas how to make infinite comments area in a flutter mobile application ? For the backend it's seems quiet easy to structure the database. But for the flutter part, I am struggling with the fact that I have to create 'comment' widget dynamically when the user is using the app (when he clicks on 'show more' for example). I think that I should use indexes to structure all the datas and retrieve them in my Flutter application so I can call my backend with the right Id to fetch data. But after when i receive the data how could I incorporate it dynamically in the right place and right order. My casual way to handle things in Flutter is to have a provider how actualize the data everytime I fetch some but I am always fetching all the datas that my provider need. I need to find a way to fetch only few comments and insert them between other comments. I don't know how I can store those potentials infinite data for my comments. With basics Flutter class it seems hard, I was also thinking about making functions which render the … -
Nginx error: 502 Bad Gateway nginx/1.23.2 on Docker + Django + Postgres
So this is the error I got from my log 2022/11/15 04:30:08 [error] 29#29: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.80.1, server: mysite.local, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://192.168.80.3:3000", host: "mysite.local", referrer: "http://mysite.local/" And I cannot figure out what's the issue. I manage to get Docker up and running and nginx , postgres, and django runs. This is my mysite.local file . I am practicing/learning. server { listen 80; server_name mysite.local; root /app/mysite_proj; index index.php; # https://www.if-not-true-then-false.com/2011/nginx-and-php-fpm-configuration-and-optimizing-tips-and-tricks/ # Deny access to hidden files location ~ /\. { access_log off; log_not_found off; deny all; } # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /app/mysite/media; # your Django project's media files - amend as required } location /static { alias /app/mysite/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { include /etc/nginx/uwsgi_params; uwsgi_pass django:3000; } } My docker-compose.yml: version: '3.9' services: django_api_backend: container_name: django platform: linux/amd64 build: docker/python restart: always expose: - "127.0.0.1:3000:3000" volumes: - .:/app depends_on: - local_db environment: POSTGRES_DB: ${DB_NAME} POSTGRES_HOST: ${DB_HOST} POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} SETTINGS_MODULE: ${SETTINGS_MODULE} nginx: container_name: nginx … -
where can i find some good Django projects?
Mainly to learn 1.signals 2.serializers 3.class based views in detail trying to build a Django project from scratch . -
Django channels consumer async
I am trying to make a private chat by django channels. The problem here is after using sync_to_async my private chat room is creating in database. but it is throwing error in next line because it can't find the private room id. Error line isn't sync_to_async. If i send another request it isn't throwing any error as room already created. self.me = self.scope.get('user') await self.accept() self.other_user = self.scope['url_route']['kwargs']['username'] self.user2 = await sync_to_async(User.objects.get)(username=self.other_user) self.private_room = await sync_to_async(PrivateChat.objects.create_room_if_none)(self.me, self.user2) self.room_name = f'private_room_{self.private_room.id}' -----> error here(None type object has no id) await sync_to_async(self.private_room.connect)(self.me) is there any way to solve that problem? -
Django rest_framework perform_update
I trying to move my def update from my serializer.py to my views.py, What it does is well after updating an Item it also saves a log to transaction_log class ClearanceItemSerialize(serializers.ModelSerializer): class Meta: model = ClearanceItem fields = '__all__' def update(self, instance, validated_data): instance.resolve = 'True' instance.resolve_date = timezone.now() instance.save() TransactionLog.objects.create(cl_itemid=ClearanceItem.objects.get(cl_itemid=instance.cl_itemid), trans_desc="Resolve Clearance Item", trans_recorded=timezone.now()) return instance views.py class APIClerkUpdate(generics.RetrieveUpdateAPIView): permission_classes = [IsAuthenticated] queryset = ClearanceItem.objects.all() serializer_class = ClearanceItemSerialize def perform_update(self, serializer): """ What to put here """ hope someone help thank you. -
Fill data from database to Word (Django Python)
I don't know how to get data and fill into my word template. It's actually a long list, and I need to fill it on my table on word document. Am I doing it right? Here is my code: def save_sample_details(request): sample = SampleList.objects.all() doc = DocxTemplate("lab_management/word/sample_template.docx") context = { 'SNAME' : sample.sample_name, 'STYPE' : sample.sample_type, 'HVER' : sample.hardware_version, 'SVER' : sample.software_version, 'CS' : sample.config_status, 'NUM' : sample.number, 'SNUM' : sample.sample_number, } doc.render(context) doc.save('lab_management/word/sample.docx') return redirect('/lab/sample/details/') So if I run this, it shows 'QuerySet' object has no attribute 'sample_name' etc. -
Updating post is not saving in the database
hello i'm a beginner to django, i made an edit button where i can edit a post, but the problem is it's not saving in the database[[enter image description here](https://i.stack.imgur.com/ZEtVa.png)](https://i.stack.imgur.com/mfr8g.png) i tried everything i could went to youtube but nothing -
Different conditions for various choicefield in django rest framework
I've a model that has some attributes like gender choices,leave type choices,leave time choices like half day, full day choices and many other choicefields, i want to know how to make different conditions for all those various choices. For example in leave type if employee apply for casual leave, i need to make condition like he can avail monthly once or cl can be carry forward for 3 cl after that 3 cl will be expired and from overall 12 cl ,3 cl will be reduced, whenever cl is availed it should be reduced, where to write this logic in serializers or views in django rest api. Someone please guide through this. Sorry for that i didn't have the code -
No thumbnail migrations appear - Django 2.2
I did step by step to implement sorl-thumbnail in my django project. But no migrations thumbnail created so images do not get added via sending form but still get added by admin interface. I use: Python 3.9 Django 2.2.16 Pillow 9.3.0 sorl-thumbnail 12.9.0 What I did. pip install pillow, sorl-thumbnail In INSTALLED_APPS added 'sorl.thumbnail' In template -
when POST order summary, how do i assign quantity to each product mentioned
Im building e-commerce app. During checkout, the id of products inside the cart (and other info) get POSTed to ORDER table on my backend. My ORDER table has many-to-many relation with PRODUCT table, I cant figure out a smart way of saving on the server, how much of each product was in the cart during the checkout I was thinking of adding a second HelperORDER table where i would combine quantity and product.id but that doesnt seem very elegant. Here is how the structure of ORDER looks when you GET it "id": 11, "product": [ { "id": 1, "name": "gloomhaven" }, { "id": 2, "name": "mtg" } ], "order_date": "2022-11-14", "notes": "testaasdasdsadadadaaaaORDER", ideally it would look like this but i cant figure out how to handle it elegantly "product": [ { "id": 1, "name": "gloomhaven" "quantity" 2 }, { "id": 2, "name": "mtg" "quantity" 3 } ], -
django model database authorization
Hi i try to create an todo app which user can login and register.All of my user will be able to access to others 'task' just by changing the id of the 'task' in the url. let say testuser1 have 3 task in database which is /task/1/ , /task/2/ and /task/3 testuser2 have 2 /task/4/ and /task/5/. while i login into testuser2 i could just change the url to /task/2/ to view the task from testuser1 . how can i avoid that? models.py ` from django.db import models from django.contrib.auth.models import User # Create your models here. # one user can have many tasks (ONETOMANY) class Task(models.Model): priority_status = [ ('3', 'Prior'), ('2', 'Medium'), ('1', 'Low'), ] user = models.ForeignKey(User, on_delete = models.CASCADE,null =True , blank =True) title = models.CharField(max_length=100) description = models.TextField(max_length=255, null=True ,blank=True) priority = models.CharField(max_length=20,choices=priority_status, default='1') complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['complete','-priority'] views.py ` from django.shortcuts import render ,redirect from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView,DeleteView, FormView from django.urls import reverse_lazy from django.contrib.auth.views import LoginView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login from .models import Task # … -
DRF How to save current user
I'm Trying to save an Item with the user's officeid but it's throwing me an error ValueError: Cannot assign "<CustomUser: admin@gmail.com>": "ClearanceItem.office" must be a "Office" instance. My customuser has id of 1 while the email is admin@gmail.com lastly the officeid = 'OSA' this is my models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) userid = models.CharField(null=True, max_length=9) officeid = models.ForeignKey('Office', models.DO_NOTHING, db_column='officeid', blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('Office', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(default='False', blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.CharField(max_length=8, blank=True, null=True) record_date = models.DateField(auto_now_add = True, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' class Office(models.Model): office_id = models.CharField(primary_key=True, max_length=50) office_name = models.CharField(max_length=200) office_head = models.CharField(max_length=8, blank=True, null=True) designation = models.TextField(blank=True, null=True) office_parent = models.CharField(max_length=50, blank=True, null=True) deptlogo = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'office' this is my views.py class APIClerkView(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] serializer_class = … -
Grouping by category in DRF
I am trying to do something like this stack overflow question: Django RestFramework group by But I am trying to follow the instructions and it just isn't working for me. Here's my view: class ArticleListView(generics.ListAPIView): queryset = Page.objects.select_related().all() serializer_class = GroupPageListSerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter) pagination_class = LimitOffsetPagination ordering_fields = ['date'] filter_class = ArticleMultiValue And here is my serializer. I can include my GroupPageSerializer serializer too, but I don't think it might be relevant? class GroupPageListSerializer(serializers.ModelSerializer): image = Base64ImageField(max_length=None, use_url=True) category = serializers.PrimaryKeyRelatedField( many=True, queryset=Category.objects.all()) url = serializers.CharField(allow_null=True, required=False, default=None, allow_blank=True) english = serializers.CharField(source="base", required=False, allow_blank=True) per_language = PerLanguageCondensedSerializer(many=True, required=False, read_only=True) foreign = serializers.CharField(required=False, allow_null=True, allow_blank=True) base = serializers.CharField(required=False) def to_representation(self, data): iterable = data.all() if isinstance(data, models.Manager) else data return { category: super().to_representation(Page.objects.filter(category=category)) for category in Category.objects.all() } class Meta: model = Page fields = ['per_language', 'date','base', 'foreign', 'english', "id", "category", "title", "image", "sound", "url", "slug"] How do I get an output like this: [{"CategoryName1":[ { "id": 5, ... }, { "id": 6, ... }, { "id": 7, ... } ] }, ... ] -
How can I do to access to a foreign key in the other side using Django and GraphQL?
I am working a on projects using Django. Here is my models.py : ` class Owner(models.Model): name = models.CharField(max_length=200) class Cat(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) pseudo = models.CharField(max_length=200)` My schema.py : `class Query(graphene.ObjectType): owner = graphene.List(OwnerType) def resolve_owner(self, info): return Owner.objects.first().cat_set.all()` But my problem is when I do that graphQL query : query{ owner{ name cat{ pseudo } } } it does not work whereas I would like something like that : ` `{ "data": { "owner": [ { "name": "Peter", "cat": { "pseudo": "miaou" } } ] } }`` How can I do that ? Thank you very much ! -
Restrict access per customer in django
I an trying to restrict access to records based on each customer so users cant access each others data through URL. I have added this but its restricting everything. Please help. if request.user.customer != Infringement.customer: return HttpResponse('Your are not allowed here!!')" views.py @login_required(login_url='login') def infringement(request, pk): if request.user.customer != Infringement.customer: return HttpResponse('Your are not allowed here!!') infringement = Infringement.objects.get(id=pk) notes = infringement.note_set.all().order_by('-created') if request.method == "POST": note = Note.objects.create( customer=request.user.customer, user = request.user, infringement = infringement, body=request.POST.get('body') ) return redirect('infringement', pk=infringement.id) context= {'infringement': infringement, 'notes': notes} return render(request, 'base/infringements.html', context) -
ModuleNotFoundError: No module named 'authlib'
I am trying to import the Authlib JTW token validator using from authlib.oauth2.rfc7523 import JWTBearerTokenValidator to integrate Auth0 into my Django app however I keep getting a ModuleNotFound error. I have Authlib already installed and have confirmed this using pip freeze so I am unsure why I keep getting this error. I have uninstalled and tried different versions of Authlib and am still encountering the same error. -
How can I insert in Wagtail the buttons to add and edit foreign key value like Django admin panel?
I would like to have in my Wagtail Admin Panel these buttons that are present in the Django Admin Panel. DjangoAdmin buttons Unfortunately I didn't find anything related. -
How is "secret_key.txt" more secure in Django project?
I apologize if this is a duplicate question but I can't find an answer online. In Django Checklist Docs I see the following to keep secret key secure. with open('/etc/secret_key.txt') as f: SECRET_KEY = f.read().strip() My project is deployed with AWS EBS. I've created a separate file called "secret_key.txt" which holds the key. How is this more secure than keeping the key in the settings.py config file? If someone can access my projects settings.py file to access the key, would they not be able to access the "secret_key.txt" file as well? How is creating a "secret_key.txt" file more secure? I've checked Google and Stack Overflow for reasoning but can't find an answer. Currently all sensitive information is protected using an .env file and including this file in .gitignore. -
Correct way to close down RabbitMQ and Celery?
I'm using Django to call a Selenium script through Celery and RabbitMQ as a message broker. The problem I'm having is often changes I make to my Selenium script aren't actually changing anything when I rerun my Django server. It sounds weird but I feel like something is still using my old code, not the one with the changes I make. My guess is that this is something to do with RabbitMQ being kept running while I make changes to my Selenium script? Do I need to 'refresh' it somehow each time I make changes or re-start the process? Also, I just ctrl+C to close everything when I'm finished, is there a 'proper' way to close down each time? -
Save customer in the background on django forms
Hi I am trying to automatically save the customer on post without having to list it in the forms. It currently shows the drop down and saves correctly but if I remove customer from forms.py it doesn't save anymore. I think I need to add something in the views but not sure what I am missing? views.py @login_required(login_url='login') def createInfringer(request): customer=request.user.customer form = InfringerForm(customer=customer) if request.method == 'POST': form = InfringerForm(customer, request.POST) if form.is_valid(): form.save() return redirect('infringer-list') context ={'form': form} return render (request, 'base/infringement_form.html', context) forms.py class InfringerForm(ModelForm): def __init__(self, customer, *args, **kwargs): super(InfringerForm,self).__init__(*args, **kwargs) self.fields['customer'].queryset = Customer.objects.filter(name=customer) self.fields['status'].queryset = Status.objects.filter(customer=customer) class Meta: model = Infringer fields = ['name', 'brand_name','status','customer'] -
How to assign django permissions for object creators?
is it possible to allow editing on django admin site of objects in database only for creators of these objects? is extension django-guardian essential for this case? as i understood with django guardian i need manually assign permissions for each db objects and it seems not effective I tried to use django-guardian for this case, but documentation for it is not very clear for me and I am not sure this extension solve this case -
How do I get uuid foreign key to save in a form in django?
I have built a model with a uuid as the primary key. When I try to update using the uuid to identify the entry I am getting a valuetype error which says the object_id needs to be an integer. My Model: class IPHold(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) CHOICES = [ ('1', 'Book'), ('2', 'Documentary'), ('3', 'Graphic Novel/Comic'), ('4', 'Journalism'), ('5', 'Merchandise'), ('6', 'Podcast'), ('7', 'Stage Play/Musical'), ('8', 'Video Game'), ] media_type = models.CharField(max_length=1, choices=CHOICES, blank=False) title = models.CharField(max_length=255, blank=False) author_creator = models.CharField(max_length=255, blank=True) production_company = models.CharField(max_length=255, blank=True) artist = models.CharField(max_length=255, blank=True) composer = models.CharField(max_length=255, blank=True) publisher = models.CharField(max_length=255, blank=True) producer = models.CharField(max_length=255, blank=True) director = models.CharField(max_length=255, blank=True) year_published = models.ForeignKey(YearHold, on_delete=models.CASCADE, related_name='year_published', blank=True) # published_through = models.ForeignKey(YearHold, on_delete=models.CASCADE, related_name='published_through', default='0') ip_image = ResizedImageField(blank=True, size=[360, 360], force_format='JPEG', upload_to='media/ips/%Y/%m/') logline = models.TextField(blank=True) summary_description = models.TextField(blank=True) BOOKS = [ ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10+'), ] series_length = models.CharField(max_length=2, choices=BOOKS, blank=True) episodes = models.PositiveSmallIntegerField(default=0) other_formats = models.BooleanField(default=False) genres = TaggableManager(through=TaggedGenreHold, verbose_name='Genres', blank=True) tags = TaggableManager(through=TaggedTagHold, verbose_name='Tags', blank=True) AVCHOICES = [ ('1', 'Available'), ('2', 'Optioned'), ('3', 'Purchased'), ('4', 'Public Domain'), ] availability = models.CharField(max_length=1, choices=AVCHOICES, blank=True) minimum_option_price = models.PositiveIntegerField(default=0) … -
Django: Custom User Model with Autoincrementing Id
I am trying to use Django Authentication and I want to create a custom model for the user that has an autoincrementing integer as id. I know about uuid library, but I want the id to be an integer number, that is why I want to avoid it. My code looks like: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, email, username, avatar, password=None): if not username: raise ValueError('User must have an username') if not avatar: raise ValueError('User must have an avatar') user = self.model( email=self.normalize_email(email), username=username, avatar=avatar, first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, email, username, avatar, password): user = self.create_user( email=self.normalize_email(email), username=username, avatar=avatar, password=password, first_name=first_name, last_name=last_name ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True) avatar = models.CharField(max_length=200) # required is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'id' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'email', 'avatar'] objects = MyAccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, add_label): return True The …