Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can i only pass "id" in POST request, despite displaying nested fields?
in my post requests to OrderProduct model, i want to only have to pass order.id and product.id and it works... untill i add a serializer to retrieve product.name. It might be because i didnt understand documentation about nested requests, but im unable to advance further into my project :( [ { "id": 2, "order": 1, "product": 1, } ] ^ here's how it looks without nested serializer, and thats the data that i wanna have to input [ { "id": 2, "order": 1, "product": { "id": 1, "name": "gloomhaven", }, }, ^ here's how it looks after i add an additional serializer. I pretty much want these nested fields to be read only, with me still being able to send simple post requests here are my serializers class OrderProductSerializer(serializers.ModelSerializer): product = Product() class Meta: model = OrderProduct fields = [ "id", "order", "product"] class Product(serializers.ModelSerializer): class Meta: model = Product fields = ( "id", "name") Is there any way for me to accomplish this? Thank you for trying to help! -
Django generic.edit CreateView and UpdateView
i am trying to set a condition for user that is not task.user himself will not be able to update the task by not showing the form .it success on the update part but while createtask the form is not showing.How can i fix it? views.py ` class TaskList(LoginRequiredMixin, ListView): model = Task #default name = {{object_list}} context_object_name = 'tasks' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) context['count'] = context['tasks'].filter(complete=False).count() search_input = self.request.GET.get('search-area') or '' if search_input : context['tasks'] = context['tasks'].filter(title__icontains=search_input) context['search_input'] = search_input return context class TaskCreate(LoginRequiredMixin, CreateView): model = Task context_object_name = 'task' fields = ['title','description','priority','complete'] success_url = reverse_lazy('tasklist') def form_valid(self, form): form.instance.user=self.request.user return super(TaskCreate,self).form_valid(form) #create a new form to exclude certain fields on model while updating class PostFormUpdate2(ModelForm): class Meta: model = Task exclude = ('user',) class TaskUpdate(LoginRequiredMixin, UpdateView): model = Task form_class = PostFormUpdate2 success_url = reverse_lazy('tasklist') task_form.html {% extends 'base/main.html' %} {% block content %} <div class="header-bar"> <a href="{% url 'tasklist' %}">&#8592; Back</a> </div> {% if request.user == task.user %} <p>{{task.user}}</p> <div class="card-body"> <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input class="button" type="submit" value="Update"> </form> {% endif %} </div> {% endblock content %} ` create and update is using the same form. -
Django ORM: Text aggregator on subquery
I banged my head on this one: I have 2 models, and I am trying to design a custom manager/queryset which will allow me to annotate to each Series the id of the linked puzzles satisfying certain conditions in the format '2,13,26'. The simplified models: class Series(models.Model): puzzles = models.ManyToManyField( Puzzle, through='SeriesElement', related_name='series') is_public = models.BooleanField(null=False, blank=False, default=False) class Puzzle(models.Model): pass my custom aggregator: from django.db.models.aggregates import Aggregate from django.db.models.functions import Coalesce from django.db.models.fields import CharField from django.db.models.expressions import Value class GroupConcat(Aggregate): """ according to https://stackoverflow.com/questions/10340684/group-concat-equivalent-in-django according to https://stackoverflow.com/a/55216659 would be compatible with MySQL and SQLite """ function = 'GROUP_CONCAT' def __init__(self, expression, distinct=False, ordering=None, **extra): super(GroupConcat, self).__init__(expression, distinct='DISTINCT ' if distinct else '', ordering=' ORDER BY %s' % ordering if ordering is not None else '', output_field=CharField(), **extra) def as_sqlite(self, compiler, connection, **extra): return super().as_sql(compiler, connection, template='%(function)s(%(distinct)s%(expressions)s%(ordering)s)', **extra) one tentative to achieve my goal: pzl_sub = apps.get_model('puzzles', 'Puzzle').objects.filter(series__id= OuterRef('id')) pzl_sub = pzl_sub.filter(series_elements__isnull=False).add_nb_public_series().filter(nb_public_series=5) pzl_ids= pzl_sub.order_by().values('id') qs = Series.objects.annotate(id_str_pzl = GroupConcat(pzl_ids)) I obtain only one puzzle.id that fit the specified conditions, instead of the concat of all of the puzzle.ids that fit the conditions Any clue on what I'm doing wrong? -
Convert template to dict
How to convert template to dict or json. with open(f"template.py") as t: template_id = Template(t.read()) new_json = eval(template_id) but I failed. -
How to calculate doeking km using property in model
I am stuck in problem ,here i want to calculate doeking km where: doeking km mean,suppose 1 day a vehicle travel 10km and 2nd day travel 20km and 3rd day travel 50km in first day it will so only 10 and second day it will sum 1st day(10)+2nd day(20) = 30km and for 3rd travel 1 day+2day+3day = 80km. here it my model .. class Log(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) date_time = models.DateTimeField( default=timezone.now, blank=True, null=True) @property def doeking_km(self): res = Logsheet.objects.filter(log=self,log__date_time__range=[self.date_time, self.date_time + datetime.timedelta(days = 1)]).aggregate(Sum("daily_km")).get("daily_km__sum") return res def __str__(self): return self.vehicle.vehicle_no + " " + str(self.date_time) and .. class Logsheet(models.Model): log = models.ForeignKey( Log, on_delete=models.CASCADE, related_name="logsheets") driver = models.ForeignKey( Driver, on_delete=models.CASCADE, blank=True, null=True) trip = models.IntegerField(blank=False, null=False) distance_from = models.FloatField(blank=True, null=True, ) distance_to = models.FloatField(blank=True, null=True, ) time_from = models.TimeField(blank=False, null=False, default=timezone.now) time_to = models.TimeField(blank=False, null=False, default=timezone.now) source = models.CharField(max_length=100, blank=True, null=True) destination = models.CharField(max_length=100, blank=True, null=True) daily_km = models.FloatField(blank=True, null=True, ) Than you ! -
Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found
I'm currently rounding up a course in full stack development with python and django, and I've been asked to clone a blog. Anytime I try to save a new post, publish a new post, or see the details of a post I get the error: NoReverseMatch at /post/7 Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?Pd+)/publish/$'] I've checked stack overflow, django documentation and a lot of blogs I haven't been able to resolve it -
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