Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need help implementing comments in Django
More specifically, you need to rewrite the working function to the DetailView class, or offer a better implementation. And it would be great to get a solution for binding a User to a comment, since in my case I have to choose from all the existing ones. Thanks in advance! Function: def product_detail(request, pk): template_name = 'main/product_detail.html' product = get_object_or_404(Product, pk=pk) comments = product.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': form = CommentForm(data=request.POST) if form.is_valid(): # Create Comment object but don't save to database yet new_comment = form.save(commit=False) # Assign the current post to the comment new_comment.product = product # Save the comment to the database new_comment.save() else: form = CommentForm() return render(request, template_name, {'product': product, 'comments': comments, 'new_comment': new_comment, 'form': form}) Model: class Comment(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name='comments') username = models.ForeignKey(Profile, on_delete=models.CASCADE) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.username) Form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('username', 'body') Template: <!-- comments --> <h2>{{ comments.count }} comments</h2> <hr> {% for comment in comments %} <p>{{ comment.body | linebreaks }}</p> <small class="text-muted">Posted by <b>{{ comment.username }}</b> on {{ comment.created_on }}</small><br><br> … -
How to create and serialize an unmanaged model Django
I'm trying to create an unmanaged model and its associated serializer but I'm having great difficulty. My first problem is that I can't find any tutorials online on how to create an unmanaged model. I'm just looking for a very simple example on how to do this. I understand as part of the docs that you need to specify managed = False but that's just a start. So far, I've literally only found one link (that isn't very helpful): https://riptutorial.com/django/example/4020/a-basic-unmanaged-table- Right now, I've tried to combine what I've seen but I'm getting an error (probably because I don't really understand how the overall architecture is meant to work). In my situation, I currently have tables in my database to which I want to create a model that retrieves certain data from the different tables in one endpoint. For arguments sake, let's say that I've got one piece of data from one table. This is what I've got so far: UserModel from django.db import models class UserDetails(models.model): user = models.CharField(db_column="LABEL", max_length=255) class Meta: managed = False UserSerializer from rest_framework import serializers from models.user import UserModel class UserSerializer(serializer.ModelSerializer): class Meta: model = UserModel fields = "__all__" UserViewSet from rest_framewirk.viewsets import ModelViewSet from … -
How to encrypt email field in django AUTH_USER_MODEL
We are using django default user model. For security purposes, customer requested to encrypt the "email field" inside database. I am not looking for procedure of encrypting one model field, I am just looking for how can I get hold of default user model email field and encrypt it. Please note our project is in development phase, so, we can run migration from freshly. What and how is the best way to achieve it? Thanks in advance. -
django multiple database with multiple server
I have a server deploying with single database. I want to run another server(for crawling) with multiple database(existing one, new one). I will save raw data from crawling in new one(DB). After data processing, save them in existing one. So, deploying server can use them. How can I do that? -
Linking Django Path to another localhost
I am running a Django project on localhost:9001 port and I want to add path like /graphql to open localhost:8080 actually Hasura graphql is running on that url. This is the code for app_name/urls.py urlpatterns = [ path('', include('core.urls')), path('admin/', admin.site.urls), path('graphql/',include('core.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) While this is the code for app_name/core/urls.py urlpatterns = [ path('user/<slug:event>', views.UserEventView.as_view()), path('',views.upload_file,name='home'), path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)), ] I want to change graphql/ path to Hasura graphql running on localhost:8080. Can Anyone please help? -
Sum list of datetime.time
I have a list of datetime.time [ datetime.time(2, 0), datetime.time(1, 0), datetime.time(1, 0), ...] How can I do the sum of those values ? I tried to simply to sum(mylist) but I have an error "unsupported operand type(s) for +: 'int' and 'datetime.time'" -
Django - Not able to access the data from model
I am currently using django 3.2 and when I try to print the models data in the views it throws the following error My views look like this from django.shortcuts import render, HttpResponse, redirect from django.contrib.auth.decorators import login_required from user.models import Student @login_required def home(request): user = request.user student_user = Student.objects.all() student_users = [] for user in student_user: student_users.append(user.User.username) stu_user = request.user.username student_list_set = set(student_users) if stu_user in student_list_set: data = Student.objects.filter(User=request.user) print(data.Name) params = { 'data':student, } return render(request, 'dashboard/student/dashboard.html', params) When I try to print the print the data.name. It throws the following error AttributeError at / 'QuerySet' object has no attribute 'Name' My models.py file looks like this class Student(models.Model): User = models.ForeignKey(User, on_delete=models.CASCADE) Name = models.CharField(max_length=50) Profile = models.ImageField(upload_to = upload_student_profile_to, default = 'defaults/student_profile.png') class_choices = (('1','1'), ('2','2'), ('3','3'), ('4','4'),('5','5'),('6','6'),('7','7'),('8','8'), ('9','9'),('10','10')) Class = models.CharField(max_length=100, choices=class_choices) section_choices = (('A','A'),('B','B'),('C','C'),('D','D'),('E','E')) Section = models.CharField(max_length=100, choices=section_choices) Roll = models.IntegerField(blank=True) Number = models.IntegerField(blank=True) is_banned = models.BooleanField(default=False) def __str__(self): return self.Name + " of " + self.Class -
How to query a Django JSONField with a nested dictionary?
I'm using Django 3.2.3 / Python 3.7.8 / PostgreSQL 12.3 models.py class Booking(models.Model): reference = models.CharField(max_length=15, unique=True) services = models.JSONField() The services structure is: { '1':{ 'id': 3, 'name': 'Name 1' }, '2':{ 'id': 4, 'name': 'Name 2 }, '3':{ 'id': 3, 'name': 'Name 3 }, ... } How to filter the Booking with services having id 3? I tried Booking.objects.filter(services__contains=[{'id': 3}]) but couldn't get through. Kindly help. -
Remove allauth from Django project created by cookiecutter
I am at a beginning of a "company web app project". I tried a Django cookiecutter template, and so far I like what I see. What I see I won't need is the user registration, password reset, social-app logins, and so on, because I will use LDAP for my user login. Afaik the stuff I don't need is provided by that "allauth" apps (please correct me). What would be the steps needed to remove this functionality so I can have the authentication more like when starting a project via Django "starproject"? I don't have any crucial data in the DB, or any models I care about, so instructions for a fresh start would be ideal. MY idea was to remove the allauth apps from "APPS" in settings and only then do the initial migrations, but something tells me it won't be that easy. I am an intermediate python dev, but new to Django. Thank you all in advance for your ideas. -
When i redirect to signup to login page my response success message is not displaying in django using ajax submit form?
I am using Django Rest framework, Please help why my success message is not showing on signin or login page when i redirect to signup to signin page. Please check my script carefully. MY views.py file This file contains my json response in the form of success and error messages: @api_view(['GET', 'POST']) @csrf_exempt def signup(request): if request.method == 'POST': serializer = UserSerializer(data=request.data) serializer1 = ProfileSerializer(data=request.data) if serializer.is_valid() and serializer1.is_valid(): # serializer.is_valid(raise_exception=True) # serializer1.is_valid(raise_exception=True) user = serializer.save() gender = serializer1.data['gender'] birth_date = serializer1.data['birth_date'] profile = Profile(user=user, gender=gender, birth_date=birth_date) profile.save() data = {'result': 'success', 'message': 'You have registered successfully and now you can login'} return Response(data=data, status=201) elif not serializer.is_valid(): serializererrors = serializer.errors data = { 'result': 'error', 'message':serializererrors} return Response(data=data) elif not serializer1.is_valid(): serializer1errors = serializer1.errors data = { 'result': 'error', 'message': serializer1errors} return Response(data=data) if not request.user.id and request.method == 'GET': serializer = UserSerializer() serializer1 = ProfileSerializer() return render(request, 'register.html', {'serializer':serializer, 'serializer1':serializer1}) My register.html file it includes my html code: Please help why my success message is not showing on signin or login page when i redirect to signup to signin page. Please check my script carefully. {% extends 'layout.html' %} {% block body %} <!DOCTYPE html> <html> <head> <meta … -
How to convert base64 variable to plain number in django template?
Let's say, we have the following place in the django template: <a href="{% settings_value "BASE_URL" %}{% url 'password_reset_confirm' uidb64=uid token=token %}{% if link_query_params %}?{{ link_query_params }}{% endif %}" target="_blank"> How to convert uid to the plain number? -
Create django question object with 4 not same choices
I want to create a question object in django without choices repeated. Like: 1) 2 2) 5 3) 5 4) 7 2 and 3 have same value and should throw error or response(I'm using rest framework) # models.py class Question(models.Model): field = models.ForeignKey('Field', on_delete=models.CASCADE) writer = models.ForeignKey(User, on_delete=models.CASCADE) question = models.TextField(unique=True) choice1 = models.CharField(max_length=200) choice2 = models.CharField(max_length=200) choice3 = models.CharField(max_length=200) choice4 = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) ignored = models.BooleanField(default=False) any solution for this problem? -
Django Logging - Unable to set propagate to False
What I'm experiencing is getting duplicate entries in my logs. I've looked around, and it seems that I have to set 'propagate': False in my loggers configuration which I have already done. However when I printout the logger.propagate it returns True. I even tried to manually set logger.propagate = False but it still returns True and I'm receiving duplicate entries in my logs. What might be the cause of problem? import logger logger = logging.getLogger(__name__) logger.propagate = False # Getting both twice logger.error('Something went wrong!') logger.error(logger.propagate) # Returns True LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "simple": { "format": "{levelname} {message}", "style": "{", } }, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "simple", }, }, "loggers": { "app": { "level": "DEBUG", "handlers": ["console"], 'propagate': False, } }, } -
How to save history data to different database in Django?
I am using django-tenants for creating multitenant app and have successfully done it. But now I want to save history data of tenants to a different database. How to accomplish this. Please help -
python : How can I do not encode / to %/F
def redirect_login_page(request): callback_url = BASE_DIR + CALLBACK_URI return redirect( f"https://kauth.kakao.com/oauth/authorize?client_id={KAKAO_REST_API_KEY}&redirect_uri={callback_url}&response_type=code") when i use kakao-api's social login, The redirect_uri is automatically encoded :, / to %3A, %2F. So, I can't redirect the page. Is there any solution for stopping autoencoding the url character? -
Django - display list of all users from auth.models in ListView Django
Hi i am working on a Hotel website and am trying to display list of all the users from the admin site onto my dashboard in a listview class UsersListView(ListView): template_name = 'dashboard/users/userlist.html' login_url = '/login/' redirect_field_name = 'user_list' def get_queryset(self): return User.objects.filter( username=self.request.user ) The above code only displayed the logged in user not all the list. Is there a way to display the active and inactive state of the users? <thead> <tr> <th>SN</th> <th>Users</th> <th>Email</th> <th>Status</th> </tr> </thead> <tbody> {% for user in object_list %} <tr> <td>{{forloop.counter}}</td> <td>{{user.username }}</td> <td>{{user.email}}</td> <td>{{user.is_active}}</td> -
How to send a webhook request to a 3rd party application in django?
i have made an api where i am receiving an api request about the successful payment now in the same code i have to trigger a webhook to an other external application to notify about the payment with a request body.so i was trying to use python's requests to accomplish this, please help me if there is any other way @api_view(['POST']) def cashfree_request(request): if request.method == 'POST': data=request.POST.dict() print(data) payment_gateway_order_identifier= data['orderId'] amount = data['orderAmount'] order=Orders.objects.get(payment_gateway_order_identifier=payment_gateway_order_identifier) payment = Payments(orders=order,amount=amount,) payment.save() URL = "" # external application url where webhook needs to send request_data ={ order:{ 'id':order.id, 'payment_collection_status': transaction_status, 'payment_collection_message': transaction_message } } json_data = json.dumps(request_data) response = requests.post(url = URL, data = json_data) return Response(status=status.HTTP_200_OK -
How to set cookie expiration at browser close on a per-request basis using Django
I want to give users the possibility to decide to have persistent sessions. To do this I added a Remember me checkbox in the login page; if the checkbox is toggled, then the session cookie will expire after 1 week, if not toggled the cookie will expire at browser close. I am encountering some problems forcing the cookie expiration at browser close. I am using the set_expiry method of request.session object. The documentation states this: https://docs.djangoproject.com/en/3.2/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry set_expiry(value) Sets the expiration time for the session. You can pass a number of different values: - If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes. - If value is a datetime or timedelta object, the session will expire at that specific date/time. Note that datetime and timedelta values are only serializable if you are using the PickleSerializer. - If value is 0, the user’s session cookie will expire when the user’s Web browser is closed. - If value is None, the session reverts to using the global session expiry policy. Reading a session is not considered activity for expiration purposes. Session expiration is computed from … -
How to implement a yoga pose detection(basically a ML model) model on a django web app
I'm currently working on a small project and I am structed with the idea if would be possible to run a model that takes user video as input and gives correction in his pose during a yoga session , through a website ,as I'm good with Django but not be able to find out any way to do it please help and any useful resource lead would be of great help thanks in advance. -
Set up Foreign Key relationship from Django in Angular
FYI: This is very descriptive question, so I hope you will understand my problem. In my Django models.py file I have two models with a Foreign Key relationship: class Work(models.Model): job = models.CharField(max_length = 200, blank = False) def __str__(self): return self.job class Personal(models.Model): name = models.CharField(max_length = 250) work = models.ForeignKey('Work', on_delete = models.CASCADE, null = True) def __str__(self): return self.name For these models I have also set up Django Rest Framework serializers.py class WorkSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Work fields = ('id', 'bezeichnung') class PersonalSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Personal fields = ('id', 'nachname', 'dienstart') views.py class WorkViewSet(viewsets.ModelViewSet): queryset = Work.objects.all() serializer_class = WorkSerializer def list(self, request, *args, **kwargs): work = Work.objects.all() serializer = WorkSerializer(work, many = True, context = {'request': request}) return Response(serializer.data) class PersonalViewSet(viewsets.ModelViewSet): queryset = Personal.objects.all() serializer_class = PersonalSerializer # permission_classes = (permissions.IsAuthenticated, ) def list(self, request, *args, **kwargs): personal = Personal.objects.all() serializer = PersonalSerializer(personal, many = True, context = {'request': request}) return Response(serializer.data) This is working perfectly fine. I want the User to set up Personal, and select from the different options of jobs (the jobs to choose from will be set up by me in the backend). So my question is: How do … -
chart js barchart with uneven time interval datapoints, parsed from django date time
I'm having trouble parsing Date Times from django in a way that would make chart.js display the data points (as bars) in uneven time intervals that match their distance from one another. Right now the bars are always equidistant from one another. Also I would like to display the time stamps in the format HH:mm. I've tried 1) new Date("{{ d.isoformat }}") which outputs: Thu May 20 2021 04:28:31 GMT+0300 (Eastern European Summer Time) and 2) new Date("{{ d.isoformat }}").toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'}) which outputs 04:28 AM So I'm probably parsing them incorrectly in charts.js with parser: 'HH:mm', and I don't know how to do it correctly in either case. Both options result in equidistant bars. HTML/javascript: var db_labels = []; {% for d in x_val %} db_labels.push(new Date("{{ d.isoformat }}").toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'})); {% endfor %} var graphData = { type: 'bar', data: { labels: db_labels, datasets: [{ label: 'PM2.5', data: db_y, backgroundColor: [ 'rgba(73, 198, 230, 0.5)', ], borderWidth: 1 }] }, options: { scales: { xAxes: [{ type: 'time', time: { parser: 'HH:mm', format: 'HH:mm', tooltipFormat: 'HH:mm', unit: 'minute', unitStepSize: 15, displayFormats: { 'minute': 'HH:mm', 'hour': 'HH:mm' }, } }] }, } } I get this kind … -
Django imap backend does not send email to recipients
I'm using django-imap-backend to send email from gmail for activation but somehow my emails do not go to recipient mailboxes but go directly to my email only. Here's my settings EMAIL_BACKEND = 'django_imap_backend.ImapBackend' EMAIL_IMAP_SECRETS = [ { 'HOST': 'imap.gmail.com', 'PORT': 993, # default 143 and for SSL 993 'USER': 'myemail@gmail.com', 'PASSWORD': 'myapppassword', 'MAILBOX': 'django', # Created if not exists 'SSL': True # Default } ] -
Custom image URL to be added to the Django model field
I am creating a model in my app called Products which is defined below:- class Product(models.Model): # Define the fields of the product model name = models.CharField(max_length=100) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) description = models.CharField(max_length=200, default='', null=True, blank=True) image = models.ImageField(upload_to='market/static/images/products') category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) # Foriegn key with Category Model store = models.ForeignKey(Store, on_delete=models.CASCADE, default=1) Here I have an image field and I am storing images in the folder market/static/images/products. The same value is stored in my database but I want to be able to store a different URL in my database. In the database, I only want to store static/images/products. How can I change that? -
jsondecodeerror django after deploying on heroku server the django app
JSONDecodeError at /vaccine/handle_vaccine_slots/ Expecting value: line 1 column 1 (char 0) Request Method: POST Request URL: http://systemofreckoning.herokuapp.com/vaccine/handle_vaccine_slots/ Django Version: 3.2.2 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: /app/.heroku/python/lib/python3.9/json/decoder.py, line 355, in raw_decode Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Thu, 20 May 2021 09:18:42 +0000 -
Django ListView not working on the template
I am trying for hours on a problem that seems very straightforward and I tried everything but it's not working. I want to display the list of blogs on a template. So, I have these views: from django.views import generic from .models import Blog class BlogList(generic.ListView): queryset = Blog.objects.filter() template_name = 'table_of_contents.html' context_object_name = 'blog_list' class BlogDetail(generic.DetailView): model = Blog template_name = 'blog.html' And this is the table_of_contents.html template where I want to display the list of blogs: {% block table_of_contents %} <p>Just for test</p> {{ blog_list }} {%endblock table_of_contents %} I expect that would display the queryset string on the frontend, but that's not the case. I debugged BlogList using the Django shell and made sure that queryset was not empty. What is the (obvious) detail that I am missing here?