Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Custom SQL Parameters with Django's 'get_or_create()' Method
So I have a DB with 14 columns. It is essentially storing coordinates for potential Wildfire Events across the globe. The data is being sourced from NASA. To avoid importing locally, a lot of data which could be the same event (with slightly different coordinates) I created a simple function which defines a threshold dependent on the latitude of the event (longitude distance per degree varies significantly as the latitude changes). As per the Django documentation on get_or_create(), any keyword passed with the exception of those listed in 'defaults' will be used in a get call before returning a tuple of found object with False. My query is, is it possible to use custom SQL with cursor.execute() to introduce a threshold range which can be used to manage inserts to the DB. I'm aware I could use .filter() method to do this but for purposes of modularity, I would like to do the SQL manually in a separate function housed in data_funcs.py (below). The data is first loaded in via Python Requests and stored locally as a text file then converted to a CSV. As per load.py below, I then use a csv.reader() to read in each line for 'pre … -
Django how to identify that the connection was closed from the client
Simple as is, consider that I have this view in Django rest framework: @api_view(['GET']) def test(request): time.sleep(20) try: return Response({"a": "b"}) except Exception: print("do something") Now say that I was in the browser, navigating to the URL of this view to reach it, and then after 5 seconds only (not 20) closed my browser, then, after 15 seconds, for sure I will end up by ConnectionAbortedError. My question is, how can I catch up on those unexpected Connection closed errors by the client, and do some additional actions in my catch block? -
Export csv with UTF8
I'm trying to export a csv file with utf-8 but csv.writer doesn't seems to have an encoding parameter .... any idea ? import csv response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=data.csv' writer = csv.writer(response, delimiter=';') for book in books: writer.writerow([book.author, book.title]) The string journée appears as journ@~e -
Django Object of type set is not JSON serializable
I have run it with old server is working but when i moved to new server it is not working why ? please advise. <class 'TypeError'> Internal Server Error: /lastestnews/ Traceback (most recent call last): File "/var/www/api-uat/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/var/www/api-uat/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/var/www/api-uat/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/api-uat/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/var/www/api-uat/tigergourd/tigergourd/views.py", line 211, in lastestnews return JsonResponse(json_data, safe=False) File "/var/www/api-uat/env/lib/python3.8/site-packages/django/http/response.py", line 558, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps return cls( File "/usr/lib/python3.8/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/var/www/api-uat/env/lib/python3.8/site-packages/django/core/serializers/json.py", line 104, in default return super().default(o) File "/usr/lib/python3.8/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type set is not JSON serializable -
Is there any way to get some specific fields from a serializer to another serializer?
I want all data from EmployeeLiteSerializer except designation data to BankInfoSerializer without detete get_designation_data method class EmployeeLiteSerializer(serializers.ModelSerializer): designation_data = serializers.SerializerMethodField(read_only=True) class Meta: model = Employee fields = ('first_name', 'last_name', 'code', 'designation_data') def get_designation_data(self, obj: Employee) -> Dict: try: return DesignationLiteSerializer(obj.designation).data except Designation.DoesNotExist: return {'message': 'No designation'} class BankInfoSerializer(serializers.ModelSerializer): employee = serializers.SerializerMethodField(read_only=True) class Meta: model = BankInfo fields = '__all__' def get_employee(self, obj: Employee) -> Dict: return EmployeeLiteSerializer(obj.employee).data -
apache cannot find the django.core.wsgi module
I have an apache server with mod_wsgi running a django site. When I connect to the page from the browser I get an apache 500 Internal Server Error. This morning I re-installed python and django in the virtual environment, probably I messed up or broke something. The apache logs say: caught SIGTERM, shutting down Apache/2.4.41 (Ubuntu) mod_wsgi/4.6.8 Python/2.7 configured -- resuming normal operations Command line: '/usr/sbin/apache2' Failed to exec Python script file '/var/www/framework_mc/framework_mc/wsgi.py'., referer: https://mysite/accounts/otp/ Exception occurred processing WSGI script '/var/www/framework_mc/framework_mc/wsgi.py'., referer: https://mysite/accounts/otp/ Traceback (most recent call last):, referer: https://mysite/accounts/otp/ File "/var/www/framework_mc/framework_mc/wsgi.py", line 17, in <module>, referer: https://mysite/accounts/otp/ from django.core.wsgi import get_wsgi_application, referer: https://mysite/accounts/otp/ ImportError: No module named django.core.wsgi, referer: https://mysite/accounts/otp/ Failed to exec Python script file '/var/www/framework_mc/framework_mc/wsgi.py'., referer: https://mysite/accounts/otp/ mod_wsgi (pid=118226): Exception occurred processing WSGI script '/var/www/framework_mc/framework_mc/wsgi.py'., referer: https://mysite/accounts/otp/ Traceback (most recent call last):, referer: https://mysite/accounts/otp/ File "/var/www/framework_mc/framework_mc/wsgi.py", line 17, in <module>, referer: https://mysite/accounts/otp/ from django.core.wsgi import get_wsgi_application, referer: https://mysite/accounts/otp/ ImportError: No module named django.core.wsgi, referer: https://mysite/accounts/otp/ mod_wsgi (pid=118226): Failed to exec Python script file '/var/www/framework_mc/framework_mc/wsgi.py'. mod_wsgi (pid=118226): Exception occurred processing WSGI script '/var/www/framework_mc/framework_mc/wsgi.py'. Traceback (most recent call last): File "/var/www/framework_mc/framework_mc/wsgi.py", line 17, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi mod_wsgi (pid=118226): Failed to exec …