Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Converting IntegerField to ForeignKey from recovered database in Django
I'm working with a MySQL database that I connected to my django project (using python manage.py inspectdb > app/models.py) but it's not reading the relationships correctly. The ForeignKeys are IntegerFields so I cannot use the handy Django ORM lookup. Here's an example: class ChileStudents(models.Model): """ simplified version of the model """ otec = models.IntegerField(blank=True, null=True) # Here's the issue # More stuff goes here updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'chile_students' class Otecs(models.Model): """ Also a simplified version """ name = models.CharField(max_length=45, blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'otecs' As shown in the example above, the IntegerField points to the OTEC id, this is a simple one-to-many relationship. I tried converting the field into a ForeignKey like this: otec = models.ForeignKey('Otecs', on_delete=models.SET_NULL,blank=True, null=True, db_column="otec_id") But when migrating it just sets the column otec_id to NULL. Is there any way I can "convert" the field into a ForeingKey? -
Python - How to retrieve data with Django Restframework from firebase database (not the SQL db) and send to a client?
I have a Django rest API and I can perfectly fetch data from a my database to a flutter client app. But I would like to fetch data from firebase database to the client via the API. In other words I would like to send data in firebase database via my Django restframework API to the Flutter app. And I don't want to send data from my actual db SQL lite. I'm new to python and django This is what I tried so far.. views.py from rest_framework import generics from myapi import models from .serializers import ApiSerializer class ListTodo(generics.ListCreateAPIView): queryset = models.Myapi.objects.all() serializer_class = ApiSerializer class DetailTodo(generics.RetrieveUpdateDestroyAPIView): queryset = models.Myapi.objects.all() serializer_class = ApiSerializer serializer.py from rest_framework import serializers from myapi import models class ApiSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'topic', 'guides' ) model = models.Myapi models.py from django.db import models # Create your models here. class Myapi(models.Model): topic = models.CharField(max_length=200) guides = models.TextField() def __str__(self): return self.topic urls.py from django.urls import path from .views import ListTodo, DetailTodo urlpatterns = [ path('', ListTodo.as_view()), path('<int:pk>/', DetailTodo.as_view()) ] This code here retrieve a list of users that I would like to send throu API to the Flutter client app users = db.child("users").get() … -
drf ModelViewset does not validate Unique Constraint failed when unique_together is used
I am using djangorestframework==3.12.1 Here is how my code looks like:- models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=14, decimal_places=2) description = models.TextField(blank=True, null=True) def __str__(self): return self.name class Meta: unique_together = ( ("name", "user"), ) serializers.py class ProductSerializer(serializers.ModelSerializer): """serializer for Product objects.""" class Meta: model = models.Product fields = '__all__' read_only_fields = ['user',] views.py class ProductViewset(viewsets.ModelViewSet): queryset = models.Product.objects.all() permission_classes = [permissions.IsAuthenticated] serializer_class = serializers.ProductSerializer Expected Behavior The validators on the Modelserializers must raise an exception as Product with this Name and User already exists. Actual Behavior IntegrityError at /api/v1/product/ UNIQUE constraint failed: projectapp_product.name, projectapp_product.user_id How do I fix this? -
In PDF, font-face appears to be loading from URL, but is not displayed
My Django app uses WeasyPrint to generate PDFs on demand. I am using WeasyPrint 52.4 and Django 3.2. I have been using system fonts, which has been working great. Now I'm trying to use local fonts. For now, I'm loading static assets through localhost, pointing to Django's static server, so I can watch the requests come in and make sure the right things are being loaded. Here is how WeasyPrint is being called: font_config = weasyprint.fonts.FontConfiguration() css = weasyprint.CSS(url='http://localhost:8000/static/kits/static/report.css', font_config=font_config) return weasyprint.HTML( string='<h1>Hello world</h1>', encoding='utf-8', ).write_pdf( stylesheets=[css], font_config=font_config, ) Here is my CSS: @font-face { font-family: 'foobar'; src: url(http://localhost:8000/static/Oxygen-Regular.ttf) format('truetype'); font-weight: 400; } @font-face { font-family: 'foobar'; src: url(http://localhost:8000/static/Oxygen-Bold.ttf) format('truetype'); font-weight: 700; } :root { font-family: 'foobar', sans-serif; color: red; } The text is correctly colored red, so I know the CSS is being loaded. I can see from my server logs that the requests for the fonts are successful, which indicates to me that WeasyPrint is fetching the fonts correctly: 2021-04-07 09:57:32,147 INFO "GET /static/mycss.css HTTP/1.1" 200 5748 2021-04-07 09:57:32,193 INFO "GET /static/Oxygen-Regular.ttf HTTP/1.1" 200 46440 2021-04-07 09:57:32,200 INFO "GET /static/Oxygen-Bold.ttf HTTP/1.1" 200 47096 But the PDF is showing the fallback sans-serif font. What am I missing? -
How to format dinamically generated HTML with django
Im trying to create a sheet of labels to print out with a QR code a logo and phone number, the QR codes are generated sepparatly from an xlsx file and they work. my issue is formatting them in the HTML. Im not sure how to change the for loop so it creates a row for each time an image is loaded onto the label. heres the html part of the code. {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>labels</title> <style> </style> </head> <link rel="stylesheet" type="text/css" href="{% static '/css/style.css' %}"/> <table width="150" cellpadding="2" cellspacing="1"> <tr> {% for item in list_qr_images %} <img src="{% static 'inc.png' %}" align="center"/> <img src="{{ item }}" align="center"> <p style="text-align:left">(718) 280-0000</p> {% endfor %} </tr> <tr></tr> </table> </br> </html> -
Celery: How to access class-based task methods from other task?
I have implemented a class-based task that is executed periodically (celery beat) but I want to run another task (which is not periodic) after an event and call the method of the mentioned periodic task. I searched in the documentation but I didn't find. So I tried it myself and managed to solve it in the following way: class MyTaskClass(Task): def a(self): ... @shared_task(base=MyTaskClass) def periodic_task(): ... @shared_task def task(): periodic_task.a() Is this method acceptable, and is there a better one? -
How to add a dataframe to a django model (sqlite3)?
I have a data frame that has one image column and the rest character columns and is populated with 128 rows. The data in this DataFrame is scraped and will need to be continuously scraped to always have the latest records. mainline_t_shirt = pd.DataFrame({ 'Images': image, 'Titles': title, 'Prices': price, 'link': link, 'Website': 'mainlinemenswear', 'brand': brand // *not sure which file this needs to be added to }) Model in Django - /models.py class T_shirt(models.Model): image = models.ImageField() title = models.CharField(max_length=250) price = models.CharField(max_length=250) link = models.CharField(max_length=250) website = models.CharField(max_length=250) brand = models.CharField(max_length=250) Could anyone provide their expertise in showing how to move the data from the DataFrame into the sqlite3 database in Django? which file do I add this snippet of code to? -
DRF: How to find the model instance with the highest combined value of two fields?
I have a model which looks like this: class Posts(models.Model): title = models.CharField(max_length=100) creation_timestamp = models.DateTimeField(auto_now_add=True) body = models.CharField(max_length=255) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="likes",blank=True) dislikes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="dislikes",blank=True) I have added an endpoint in urls.py, so that when the url .../v1/posts/max-interaction-count is visited, the following function in views.py is run: @api_view(['GET']) def interaction_count_view(request): max_post = None max_interactions = 0 for post in Posts.objects.all(): interactions = post.likes.count() + post.dislikes.count() if interactions > max_interactions: max_post = post max_interactions = interactions return Response({"Post number " : max_post.pk, "interaction_count ": max_post.likes.count() + max_post.dislikes.count()}) This works, returning the id of the post with the maximum sum of likes and dislikes. However, I believe interaction_count_view might not be very scalable because it was written in python, rather than using built-in django methods which use SQL. Is this the case? If so, what is a better approach to counting the number of likes and dislikes associated with a post instance? -
Email field with unique constraint prevents put method of serializer from saving. django rest_framework
When creating an object in my api view it seems fine but whenever I update the object even I didn't change my email field it says user with this Email Address already exists. I am using generics.RetrieveUpdateView for my view. I thought generics.RetrieveUpdateView automatically handles this. What am I missing? my model looks like this: class User(AbstractUser): email= models.EmailField(unique=True) ... my serializer looks like this: class UserListForProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username','email','last_login', 'date_joined','is_active', 'is_student', 'is_staff', 'is_teacher', 'is_registrar', 'is_superuser'] read_only_fields = ('username','date_joined', 'last_login','is_active', 'is_student', 'is_staff', 'is_teacher', 'is_registrar', 'is_superuser') class StaffProfileDetailSerializer(CreateProfileSerializer): user = UserListForProfileSerializer(many= False) class Meta: model = StaffProfile fields = ['user','first_name', 'middle_name', 'last_name', 'gender', 'employee_number', 'date_of_birth', 'mobile_number','dob_month','dob_day','dob_year','address',] read_only_fields = ('date_joined', 'last_login',) my view looks like this: class UserProfileDetail(generics.RetrieveUpdateAPIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] serializer_class = StaffProfileDetailSerializer def get_queryset(self, *args, **kwargs): userid = self.request.user.id return StaffProfile.objects.filter(pk= userid) -
How can I use base.html like a regular template, and render to it
I have my navbar css in my base.html, and then use {% extend base.html %} to add it into my regular template. However, I want to have a login/register option in my navbar (which is in my base.html), and I want to use cookies to decide whether to put login or register in the navbar. How can I have base.html be able to request cookies, when it doesn't have a view? Also, not every webpage on my site has a view, some are a plain html with {% extend base.html %} -
Index/Dashboard/Homepage Best Practice and Customs
I'm currently developing a project to store all of my old MP3 files. This project contains multiple applications(Artist, Album, Song) and I'm simply curious to know if it is common for developers to create a separate application which may be named something like 'Dashboard' and use this to host their homepage, login/logout functionality, search features, recently uploaded items, etc. Or is it more common to just stick your homepage into an existing app? -
Insert into table from arbitrary number of checkboxes in Django
I'm building a Django application that will be used to schedule downloads. I've cleaned some government data that's pretty large, so people won't necessarily want to download all of it at the same time. They might also want to have it delivered via S3 buckets, etc. So I figured the easiest way to get the data to them would be to have a series of check boxes that iterate through what I have available and then let them press a button that would populate a database and have the server where the data they are stored on do the heavy lifting of uploading to a bucket and providing them the link, etc. Where I'm having an issue is I'm having a heck of a time figuring out how to get data from the checkboxes, of all things. Here's what I have tried so far. I've included the snippets from the files I believe to be pertinent: models.py class UserDownload(m.Model): user = m.ForeignKey( settings.AUTH_USER_MODEL, on_delete=m.CASCADE ) download_source = m.TextField(max_length=200) download_configuration = JSONField() download_queued_utc = m.DateTimeField() download_link_generated = m.DateTimeField() download_link = m.TextField() bls-download.html {% extends "base.html" %} {% load static i18n %} {% block title %}Data Sources List {% endblock title %} … -
Comment form not submitting and saving comments anymore
I am a newbie in django following a question and answer website tutorial. After loading the comment form and adding a few comments with it, I added a form for adding more answers to the same question in the details.html file and the comment form stopped submitting & saving comments. I'm not getting any error except: Uncaught SyntaxError: missing ) after argument list I after logging, I got the following error logs: DEBUG 2021-04-07 10:48:25,270 utils 17624 1040 (0.000) SELECT COUNT(*) AS "__count" FROM "main_comment" WHERE "main_comment"."answer_id" = 12; args=(12,) DEBUG 2021-04-07 10:48:25,272 utils 17624 1040 (0.000) SELECT "main_comment"."id", "main_comment"."answer_id", "main_comment"."user_id", "main_comment"."comment", "main_comment"."add_time" FROM "main_comment" WHERE "main_comment"."answer_id" = 12; args=(12,) INFO 2021-04-07 10:48:25,277 basehttp 17624 1040 "GET /detail/4 HTTP/1.1" 200 9643 WARNING 2021-04-07 10:48:25,469 basehttp 17624 1040 "GET /static/bootstrap.min.css.map HTTP/1.1" 404 1689 DEBUG 2021-04-07 10:48:37,751 utils 17624 7732 (0.000) SELECT "main_question"."id", "main_question"."user_id", "main_question"."title", "main_question"."details", "main_question"."tags", "main_question"."add_time" FROM "main_question" WHERE "main_question"."id" = 4 LIMIT 21; args=(4,) DEBUG 2021-04-07 10:48:37,756 base 17624 7732 Exception while resolving variable 'detail' in template 'detail.html'. Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'Question' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most … -
Type error when trying to fetch data Python Django
I am trying to get data from the database based on request with id u_id and x_id but I am not getting any data instead getting an error TypeError: display_data() missing 2 required positional arguments: 'u_id' and 'x_id' can you help? code def display_data(request, u_id, x_id): if request.method == 'POST': widget['data'] = Widget.objects.get(u_id = u_id, x_id = x_id) return widget -
Annotation/Join in Django
I have written a query that I want to implement in the Django ORM. A similar question has been asked here How to apply windowing function before filter in Django. The limitation is that the ORM applies the annotation before doing the filtering by the modulo operation. For now the following is working as RawSQL, but ideally we can achieve the same with the ORM. (db is PSQL) SELECT * FROM ( SELECT * FROM measurements WHERE survey_id = 123 AND id % 10 = 0 ) AS downsampled LEFT JOIN ( SELECT id, survey_id, ROW_NUMBER() OVER (ORDER BY "measurements"."timestamp" ASC) AS "rank" FROM measurements WHERE survey_id = 123 ) AS ranked ON downsampled.id = ranked.id ORDER BY timestamp; -
can we build a Geo Django web-application without using geoserver-rest
I am beginner with using spatial data and I am building geo-django web application with database postgres and its extensions postgresql and postGIS . All I want to know is that can we use Geo Django without using geoserver. -
Django: Create a JSONResponse with parent and children from the same model
I have Category model that has a parent field attributed to itself: class Category(models.Model): name = models.CharField(max_length = 50, blank = True) parent = models.ForeignKey('self', null = True, blank = True, on_delete = models.CASCADE) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name I want to send an api response using DRF with something similar to this: items: [ { id: 1, name: 'Applications ', children: [ { id: 2, name: 'Calendar : app' }, { id: 3, name: 'Chrome : app' }, { id: 4, name: 'Webstorm : app' }, ], }, { id: 5, name: 'Documents', children: [ { id: 6, name: 'vuetify', children: [ { id: 7, name: 'src ', children: [ { id: 8, name: 'index : ts' }, { id: 9, name: 'bootstrap : ts' }, ], }, ], }, { id: 10, name: 'material2', children: [ { id: 11, name: 'src ', children: [ { id: 12, name: 'v-btn : ts' }, { id: 13, name: 'v-card : ts' }, { id: 14, name: 'v-window : ts' }, ], }, ], }, ], }, ], There is an answer here using recursion, but it is for a single parent. How can … -
Avoid others to make requests to URL and modify users data [DJANGO]
in my question I mentioned django, but this is a general question over the user-interaction mechanism with the backend. I'm developing iOS application and, for instance, I want to let the user to update the email address therefore my backend is: class UpdateEmail(APIView): serializer_class = EmailSerializer def put(self, request): user_id = request.user.id new_email = request.data.get('new_email').lower() User.objects.filter(id=user_id).update(email=new_email) return Response('OK') As you can see I made a put request of this type: { "id":user_id_logged_in_mobile_device_stored_locally, "email":new_email } My question is, how can I avoid others from making a PUT request and modify some user's informations? Maybe this isn't the correct approach to the problem. -
Django post variable as model object reference
I am trying to pass a post variable into my view and use it as the model name for a query, the query will run but return nothing. I have hard coded the model name to verify the query indeed works, but the passed in post variable does not. The commented line is supposed to use passed in post variables to achieve the same result as the uncommented line. Is there something else I need to do to make this work properly? # assessment = framework_filter+".objects.filter(level__lte="+level_filter+")" assessment = Survey1.objects.filter(level__lte=level_filter) Below is the full function from my views.py file. def assessment_view(request): # assessment_level = Frameworks.objects.values("framework", "securityassurancelevel").distinct() if request.POST: framework = Frameworks.objects.all() framework_filter = request.POST.get('framework_select').split(' ')[0] level_filter = request.POST.get('framework_select').split(' ')[1] # assessment = framework_filter + ".objects.filter(level__lte="+level_filter+")" assessment = Survey1.objects.filter(level__lte=level_filter) template = "assessments/"+framework_filter.lower()+".html" data = { 'sitetitle' : "CAT - Assessments", 'framework' : framework, 'assessment' : assessment, 'framework_filter': framework_filter, 'level_filter' : level_filter, } else: framework = Frameworks.objects.all() template = "assessments/assessment.html" data = { 'sitetitle': "CAT - Assessments", 'framework': framework, } return render(request, template, data) -
Django Template syntax error (Invalid block Tag)
I want to open my booking form page in my website but I got this error: TemplateSyntaxError at /form.html/ Invalid block tag on line 61: 'end', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Here is my Code: {% if messages %} {% for message in messages %} <h2 style="color: green">{{message}}</h2> {% end for %} //the line I got the error {% end if %} -
Multiple frontend and one djanggo backend
How can I build a web application backend with multiple frontends like Shopify, Blogger? -
I would like to make a python script tha upload an image to a django server
I am trying to develop an app that users can login and also create counts. the user is able to upload an image which will be used as the profile picture. i am also using a mysql database to store the users details. i want to create a server that will hold all the profile pictures and the link the the specific images will be stored in the database on the users id which will the used by the app when displaying the image. i am told its not good practice to store the images on the database con i intend the app to have losts of users. i have managed to create a server as in this tutorial https://learndjango.com/tutorials/django-file-and-image-uploads-tutorial but i want to be able to upload the image from a kivy GUI which is in python. i would like to upload the image with a specific id which will be the users email and the server should give back the URL to the image so that i save it in the database. if possible i would also like to be able to delete the image from the server when the user changes the image -
SessionAuthentication vs. BasicAuthentication vs. TokenAuthentication django rest_framework
I'm little bit confused which should I use between the three. I read the docs regarding this, and learned that BasicAuthentication is not suitable for production, I understand nothing more. I'm having a hard time understandings docs regarding these 3. How do they work? What's the difference? I just know that in order to restrict my api pages I need to implement one of these authentications and permission_classes in my generic APIView. So what I am doing is, a web app, for a school and I don't think I will be making an ios app or android app for this web app. Which should I use? -
Django DRF RawSQL with MariaDB Versioning tables
I'm having a weird issue with Django rest framework and MariaDB versioning tables: In my DB I have a table called foods_food which is a MariaDB versioning table. I want to get a list of all the data in the table as of a specific point in time: foods = Food.objects.raw( '''SELECT * FROM foods_food for SYSTEM_TIME as of '2021-04-01 09:46:41.911590+00:00') If I print the rawSQL query I get: print(foods) # OUTPUT: <RawQuerySet: SELECT * FROM foods_food for SYSTEM_TIME as of '2021-04-01 09:46:41.911590+00:00'> I've copy pasted the SQL query into my DBMS and I can confirm that it is working as expected. Now, to return the actual data to my API endpoint I have to convert the rawQuerySet to a query set in my views.py: queryset = Food.objects.filter(pk__in=[i.pk for i in raw_queryset]) However when I return the queryset data, the versioning is completely ignored and I'm returned with the data as of the "latest version". What am I missing? -
Django or Flask for a Application that will only manipulate Excel file
I know perhaps this question is agonizing for a Senior Python Developer, but God knows I'm flummoxed about which framework I ought to use for my application. My application will take an Excel File from the front-end, and it is going to manipulate the Excel File, create a new Excel file from the input file, and return the new Excel to the front-end. For this, which Python Web framework ought I use? Ought I use Flask or Django, please help me? Moreover, which Python Library I use for Excel Data manipulation Pandas or OpenPyXL