Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set the default vaue for ForeignKey
I have this field graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False,blank=False) and GraduationYear class is. class GraduationYear(BaseModel): label = m.CharField(max_length=255) year = m.CharField(max_length=255,unique=True) def __str__(self): return self.label Now I want to set the GraduationYear object where year=2022 as the default value of graduation_year So, I am guessing I should embed sql to here below. graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False,blank=False,default='select GraduationYear where year=2022') Is it possible? -
Django: Send agency data in a context dictionary and use it to build markers on map
I have an agency app in my project with a model in which I save company's sale agenies' data including their name and contact info and their coordinates. My agency model: class Agency(models.Model): English = "En" Persian = "Fa" Arabic = "Ar" LANG_CHOICE = [ (English, "English"), (Persian, "Persian"), (Arabic, "Arabic"), ] language = models.CharField( max_length=2, choices=LANG_CHOICE, default=Persian, ) province = models.ForeignKey( Province, on_delete=models.SET_NULL, default=None, null=True, ) city = models.ForeignKey( City, on_delete=models.SET_NULL, default=None, null=True, ) title = models.CharField( max_length=100, blank=True, null=True, ) owner_name = models.CharField( max_length=200, blank=True, null=True, ) address = models.CharField( max_length=500, blank=True, null=True, ) telephone = models.BigIntegerField(blank=True, null=True) mobile = models.BigIntegerField(blank=True, null=True) fax = models.BigIntegerField(blank=True, null=True) latitude = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True ) longitude = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True ) def __str__(self): return self.title Now the goal is to write a view for this model in which I'll be sending agency model data in the context dic to the front, and there, use the data to create markers for each agency side by side with a list of agencies. I have no problem writing the view, context dictionary would be something like this: This example is for 1 agency: { "AgencyList": [ { "id": 1, "language": … -
Error while deploying django project to Railway
I am getting this error while opening the deployed site on railwayError. I looked for the solution and found that we need to change the host of mysql settings, so I changed them. These are my new database settings. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db', 'USER': 'root', 'PASSWORD': 'toor', 'HOST': '0.0.0.0', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } I am still getting the error. What should I do? -
For running celery queues in docker, I want to specify multiple queues with different concurrency
Currently I am using docker compose in which I have specified celery as a service where q1,q2,q3 ,q4 and q5 are some different queues , and i want to assign each queue a different concurrency. celery: restart: always build: context: dockerfile: Dockerfile container_name: celery command: celery --app=celery:app worker --concurrency=8 --loglevel=DEBUG -Q q1,q2,q3,q4,q5 depends_on: - redis - web I read somewhere about celery multi , but dont know whether it fits my use case. -
Reading an excel file, extracting each cell value as a str and doing some action on each cell value, Python
I have uploaded an excel file, what I need to do is extract each cell value as str object from the uploaded file and run a query on the cell value. Unfortunately, nothing is working.Need urgent assistance. def read_agent_list(request): request.session.clear_expired() if request.is_ajax(): if request.method == "POST": userfile = request.FILES['userfile'].read() df = pd.read_excel(userfile,header=0) df=df.fillna('') df=df.astype(str) for index, row in df.iterrows(): agentcode=tuple(list(df['Agentcode']) ) agentlist=df.apply(lambda x: x.str.strip()) qry=getData(""" SELECT U.USER_ID AS AGENTCODE""".format() dff=getViaData(qry) -
400 error from loading fixtures onto aws s3 for django
I have a django project with aws s3 used to store images the website has. The website allows users to upload their own image, and that works just fine. When I add a model instance with a jpg, the file is uploaded to aws and can be viewed in the admin panel. The problem is, however, is that I also used fixtures to load in pre defined objects with images, but whenever I interact with the preloaded fixtures in the database, I get a 400 error. Screenshot of databse The first object named "Test" was manually added, and all of the other objects below that one were added from the fixture. Test opens normally but all of the other objects give a 400 error. I tried changing my region in the aws bucket but that did not help. Here is an example of a couple of fixtures { "model": "transfer.Workout", "fields":{ "title": "Lat Pull Downs", "notes": "dont move your back at all, pull towards chest, retract shoulder blades as you go down, let elbows go straight down", "sets": "5", "demonstration": "/demonstrations/back&bicep/back/latpulldowns.gif", "muscle": "back" } }, { "model": "transfer.Workout", "fields":{ "title": "Cable Rows", "notes": "keep shoulder neutral, pull towards abs, pull … -
Send csv file via email django
I want to attach a csv file to an email. i wrote a get method like this : def get(self, request, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), many=True) file_format = request.query_params.get("file_format", "csv") if file_format == "csv": data_file = export_to_csv( serializer.data, list(self.get_serializer().Meta.fields), "students"), ) return data_file this API generate a link to download the csv... but when I PDB the data_file I find out it is <HttpResponse status_code=200, "text/csv"> this the export_to_csv function : def export_to_csv(data, titles, file_name): #This function will export the data in the form of csv file response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = "attachment; filename={}.csv".format(file_name) writer = csv.DictWriter( response, fieldnames=titles, extrasaction="ignore", ) # create dict from translation of headers headers = {title: _(title).replace("_", " ").title() for title in titles} # write translated headers writer.writerow(headers) # write data to csv file for row in data: writer.writerow(row) return response The question is how can I attach the generated csv to the email -
When I runserver with my own IP, Why Django Sessions is not Working?
This App is deployed at LAN server. My session can work with localhost ( python manage.py runserver 8000 ), but I want to use my own IP ( python manage.py runserver < my-IP >:< port > ),then the session is not working def login(request): url_page ="pages/login.html" id = request.session.get('id') if id is not None: return redirect("homepage") if request.method == 'POST': id = request.POST.get('id',"") password = request.POST.get('password',"") data={ "id":id, "password":password } user = QueryUsers.users_get(data) if bool(user): request.session['user'] = id # not working request.session.modified = True return redirect("homepage") else: res ={ "error":True, "message":error_message.INVALID_LOGIN } return render(request,url_page,res) CUS_PARAMS = { "id": "", "name": "", "error": False, "message": "", } return render(request,url_page,CUS_PARAMS) my settings ALLOWED_HOSTS = ['*'] MIDDLEWARE = [ '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', ] My request.session.get('user') is null when I runserver with my own IP, I'm very sure that my login function has no error, because when I runserver with localhost python manage.py runserver 8000, It's able to work in local. I've tried adding SESSION_SAVE_EVERY_REQUEST in setting.py, It is not working. I want to solve this problem because I want to open this App with other device that connect the same net. -
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)