Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Get current user info inside model form in django admin
I have the below code structure. I want to get the request.user information inside StaffForm. How do I pass the user info to that class class UserProfileAdmin(admin.ModelAdmin): class UserProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): pass class StaffForm(UserProfileForm): def __init__(self, *args, **kwargs): pass class Meta: model = models.UserProfile fields = () class SuperUserForm(UserProfileForm): def __init__(self, *args, **kwargs): pass class Meta: model = models.UserProfile fields = () search_fields = [ 'email', 'name' ] def get_form(self, request, obj=None, **kwargs): if request.user.is_superuser: return self.SuperUserForm else request.user.is_staff: return self.StaffForm -
how to limit foreign key choices in the form page?
below are my models, I want to display only those groups in post form in which the user is joined in. Example: if I joined in "mcu" group then only that group should be displayed, how should I do that?? GROUP MODEL class Group(models.Model): name = models.CharField(max_length=200, unique=True) description = models.TextField(blank=True, default='') members = models.ManyToManyField(User, through='GroupMember') class GroupMember(models.Model): group = models.ForeignKey(Group, related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups',on_delete=models.CASCADE) class Meta: unique_together = ('group', 'user') POST MODEL User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length=250,default='') message = RichTextField() group = models.ForeignKey(Group, related_name='posts', null=True, blank=True,on_delete=models.CASCADE) class Meta: ordering = ['-created_at'] unique_together = ['user', 'message'] -
i can't connect between app URLs in Django
I have a small problem with URLs file in Django, I'm trying to connect between app URLs, review, and the main urls I have python 3.9.1 Django 3.2.0 I have been searching and try many things on StackOverflow but still, I don't find why the server doesn't work just when I put this line with a red arrow on the comment, please help!! -
How to make a python date time object based on model object values?
Here I have a Task model. Which has start and end datetime fields. User will have a option to set the notification setting while creating Task. (e.g. send notification before 30 minutes/1 hour). TaskNotification model has OneToOne relation with the Task model.Which is responsible for creating notification. The notification created at the time of task model creation. Now problem is while sending notification. I got stuck while sending notification to the users at the right time . I tried to run the task_notification function in background but stucked while getting the right time. Is it a good approach for my use case or is there any better approcah ? class Task(): title = models.CharField(max_length=255) desc = models.TextField(blank=True, null=True) users = models.ManyToManyField(User, blank=True) start_datetime = models.DateTimeField(default=timezone.now) end_datetime = models.DateTimeField(default=timezone.now() + timezone.timedelta(minutes=30)) class TaskNotification(): notification_options = [ ('minute', 'minute'), ('hour', 'hour'), ('day', 'day'), ] task = models.OneToOneField(Task, on_delete=models.CASCADE=) send_before = models.PositiveIntegerField(default=10) notification_option = models.CharField(max_length=10, default='minutes', choices=notification_options) is_viewable = models.BooleanField(default=False) function def task_notification(): tasks = Tasks.objects.filter(is_viewable=False) task_notifications = TaskNotification.objects.filter(task__in=tasks) for notif in task_notifications: event_start_time = notif.task.start_datetime notif_send_before = notif.send_before # will be an integer notif_time_option = notif.notif_time_option # minutes/hour/days if notif_send_req_time: # stucked here how to implement the logic notif.is_viewable=True notif.save() I will … -
Display choices from model (without using django forms)
We have an old django application developed, unfortunately it does not use django forms. It has many dropdowns implemented as follows (and form data is getting stored to the backend using ajax) <div class="form-group" data-enquiry-flag="2"> <label class="form-custom-label">Possession</label> <div class="btn-group" role="group"> <select name="possession_month" id="possession_month" class="form-control btn possession-btn btn-primary"> <option value="">----Select----</option> <option value="Jan" {% if enquiry.possession.possession_month == "Jan" %} selected {% else %} {% endif %}>Jan</option> <option value="Feb" {% if enquiry.possession.possession_month == "Feb" %} selected {% else %} {% endif %}>Feb</option> ... <option value="Dec" {% if enquiry.possession.possession_month == "Dec" %} selected {% else %} {% endif %}>Dec</option> </select> <select name="possession_year" id="possession_year" class="form-control btn possession-btn btn-primary"> <option value="">----Select----</option> <option value="2020" {% if enquiry.possession.possession_year == "2020" %} selected {% else %} {% endif %} >2020</option> <option value="2021" {% if enquiry.possession.possession_year == "2021" %} selected {% else %} {% endif %} >2021</option> ... <option value="2035" {% if enquiry.possession.possession_year == "2035" %} selected {% else %} {% endif %} >2035</option> </select> </div> </div> Earlier its model was something like this: class Possession(models.Model): possession_month = models.CharField(_('Possession Month'), max_length=5, blank=True) possession_year = models.IntegerField(_('Possession Year'), blank=True, null=True) # ... Other fields class Enquiry(models.Model): possession = models.ForeignKey(Possession, verbose_name=_("Possession"), null=True, blank=True, on_delete=models.CASCADE) Which I am modifying like this, from its accepted … -
Django: How to view all registered user Information in HTML template while login user have access to view anything, but user is not admin / superuser
i am new to Django: I am Creating a Website in which i want to show to All user Profiles in a Template to log-in user and when log-in user click to any user name visible in table field, information related to specific user will visible to log-in user .. In HTML Templates.. all registered user is visible in a table where i added the profile view link ***But in my scenario while i click the user name where i added view profile link the link is only showing log-in user information not the clicked user information *** My Project is Ecommerce My App are : Indenter, Login, Logout, Purchaser, Register, Supplier. - Ecommerce. URLs : from django.contrib import admin<br /> from django.urls import path, include urlpatterns = [ path('', include('Register.urls')), path('Login', include('Login.urls')), path('Logout', include('Logout.urls')), path('Purchaser', include('Purchaser.urls')), path('Intender', include('Intender.urls')), path('Supplier', include('Supplier.urls')), ] - Ecommerce.Register.URLs : urlpatterns = [ path('(?P<username>\w+)/profile_detail', views.profile_detail, name="profile_detail"), ] - Ecommerce.Register.views.py : This view i am calling in the Template to view the User information. def profile_detail(request, username): u = User.objects.get(username=username) user = request.user return render(request, 'profile_detail.html', {'user': user, 'user_url': u, }) tempaltes/indenter_home.html In this template in the table where all user is visible in usernaem field … -
What is the scope of global variables in the views.py?
If I declare a global variable myglobalvar in my views.py myglobalvar = "value" def home(request): print(myglobalvar) def thatOneLink(request): myglobalvar = "different value" When someone calls thatOneLink what is the scope of the change? Will myglobalvar = "different value" only for this request? Or only for the session? Or until the server restarts? In JSP by default there were settings on the scope. Django seems to have another package for that: https://pypi.org/project/django-scopes/ But in the very default case without any additional packages, how does Django handle scopes? Or do they have different names or definitions? -
overwite create method in djoser serializers
I am trying to overwrite create method after inheriting UserCreateSerializer from Djoser, but it does not get called when user-created serailizers.py djoser settings