Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF: Update a specific field with a GET instead of a PATCH
Context For a specific use case I need to be able to update a single field of my Visitor model using a GET request instead of a PATCH request. My relevant Visitor model looks like this: # models.py class Visitor(models.Model): visitor_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) customers = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_visitors') audiences = models.ManyToManyField(Audience, related_name='audience_visitors') cid = models.CharField(max_length=255, unique=True) uid = models.CharField(max_length=255) cup = JSONField(null=True) def __str__(self): return self.cid class Meta: db_table = 'visitor' I am using a straightforward serializer like this: # serializers.py class VisitorSerializer(serializers.ModelSerializer): class Meta: model = Visitor fields = ('customers', 'cid', 'uid', 'cup') I am able to update just the cup field for a specific Visitor which is looked up using the unique cid field with a PATCH like this: # views.py class VisitorViewSet(viewsets.ModelViewSet): serializer_class = VisitorSerializer queryset = Visitor.objects.all() lookup_field = 'cid' def list(self, request, *args, **kwargs): instance = self.get_object() serializer = self.serializer_class(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) Problem The problem is that I am unable to update the cup field of a Visitor based on a given unique cid field using a GET request. What I tried As this answer by Uri Shalit suggested, I tried to override get_serializer() inside my VisitorViewSet and … -
APNS Private Key + Django Backend
I'm using a django backend to send push notifications to my iOS app. One method of loading in the APNS certificate is as an environment variable with the contents of the .pem file. However, I'm noticing that my certificate contains BOTH the certificate section, and the private key section. Is this correct? Or should the private key section be stripped out? -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- ... -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY----- -
how to show the created and updated date in django admin?
Is it possible to access the created date and updated date from django admin page ? I don't have these fields specified in the model. -
Not able to load static files in django template
I am learning django through this tutorial. The tutorial is kind of old but most of the code is the same. I tried adding some CSS files to the project just like the tutorial but for some reason, it is not working for me. here is my file structure... src ├── assets │ └── css │ ├── base_styles.css │ └── index_styles.css ├── core │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── settings.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ ├── views.cpython-37.pyc │ │ └── wsgi.cpython-37.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── test_app │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-37.pyc │ ├── models.py │ ├── templates │ │ └── test_app │ │ └── test_app_home.html │ ├── tests.py │ ├── urls.py │ └── views.py └── templates ├── aboutpage.html ├── base.html └── homepage.html Please note that src is the root folder. core is the name … -
Python DRF serializers custom errors
I just learn python and DRF for my project. currently I'm making some API for my mobile app. This is my plan API call response format for operation success: { "status" : 1, "message" : "success", "result" : { } } and for operation failed: { "status" : 0, "message" : "failed" "errors" : [ { "code":10001, "description":"invalid email format" } ] } I'm using serializers right now for validate the data. but serializers have they own error format. for raise ValidationError, i change it with my custom validation error handler so it will give 200 status code. class custom_ValidationError(APIException): status_code = 200 And this is what I'm doing right now with my view and serializers @api_view(['POST']) def register_user(request): serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): user = serializer.save() result = {} data['status'] = 1 data['message'] = 'user registration success.' result['id'] = user.id result['username'] = user.username data['result'] = result else: data['status'] = 0 data['errors'] = serializer.errors return Response(data) class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type':'password'},write_only=True) class Meta: model = User fields = ['email','username','password','password2'] extra_kwargs = { 'password':{'write_only':True} } def save(self): user = User( email = self.validated_data['email'], username = self.validated_data['username'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise … -
Django. Reply for comments getting posted as comments. How to have the reply for comments?
Hey I am quite new to django, I have this function for comments and replies,the problem is I can't have the reply to comments instead it is getting posted as comments. How to have this replies under respective comments? Here is my model and functions. model class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) reply = models.ForeignKey('Comment', null=True, related_name='replies', blank=True, on_delete=models.CASCADE) content = models.TextField(max_length=1000) timestamp = models.DateTimeField(auto_now_add=True) views def comment_section(request, slug): user = request.user post = get_object_or_404(Post, slug=slug) comments = Comment.objects.filter(post=post, reply=None).order_by('-id') if request.POST: comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') reply_id = request.POST.get('comment_id') #reply-section comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create(post=post, user=request.user, content=content, reply=comment_qs) comment.save() else: comment_form = CommentForm() context = { 'post':post, 'comment_form':comment_form, 'comments': comments, } if request.is_ajax(): html = render_to_string('posts/comment_section.html', context, request=request) return JsonResponse({'form': html}) html <!-- Comment showing section --> <div class="main-comment-section"> <div class="container-fluid mt-2"> <div class="form-group row"> <!-- Comment Form --> <form class="comment-form" method="post" action="{% url 'posts:comment_section' post.slug %}"> {% csrf_token %} <div class="form-group"> <textarea name="content" cols="60" rows="2" maxlength="1000" required="" id="id_content"></textarea> </div> <button type="submit" value="submit" class="btn-sm btn-outline-warning" style="color: black;">Comment</button> </form> <!-- Comment Form end --> </div> </div> {% if not post.comment_set.all %} <small>No comments to display</small> … -
Django ORM update with subquery
I have a model with 2 DateTime fields. I want to subtract start time and end time and update the duration column in seconds. Nearly 15000 records need to be updated at each request. I got below mentioned error operational error (1093, "You can't specify target table 'tq_trn_user_question' for update in FROM clause") class TqTrnUserQuestion(models.Model): question = models.ForeignKey(TqTrnQuestion, on_delete=models.CASCADE, null=False, blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False, related_name="%(app_label)s_%(class)s_users") question_status = models.ForeignKey(TqCfgQuestionStatus, on_delete=models.CASCADE, null=False, blank=False) start_time = models.DateTimeField(null=True, blank=True) end_time = models.DateTimeField(null=True, blank=True) duration = models.IntegerField(null=False, blank=False) role = models.ForeignKey("CfgUserRole", on_delete=models.CASCADE, null=False, blank=False) pause_duration = models.IntegerField(default=0) park_duration = models.IntegerField(default=0) below is my ORM tq_user_question = cls.objects.filter(question__in=locked, end_time__isnull=True, question_status=TqCfgQuestionStatus.objects.get(question_status_id=10)) tq_user_question.update(end_time=end_time, duration=Subquery(cls.objects.filter(id=OuterRef('id')).annotate( diff_duration=TimeStampDiff(F('end_time'), F('start_time'), output_field=IntegerField()) ).values('diff_duration')[:1]), question_status = TqCfgQuestionStatus.objects.get(question_status_id=50), updated_by=user) -
Django-Storages - I/O operation on closed file
I am trying to upload file in Amazon S3 Bucket. For that purpose I have installed latest version of Django-Storages. Though media is getting serve from S3 bucket but I am unable to upload file to S3 bucket'. I get this error: Value error: I/O operation on closed file I read over here https://github.com/jschneier/django-storages/issues/382 that this issue is cause of django-storages version. I changed version to 1.6.0 then I started getting error: No module named 'django.utils.six' Then I changes django version and more errors start getting appear and so on. My first question: Does this I/O error is really due to just django-storages version? If that so, then how to cater this situation as I was using most upgraded version of everything? -
Limiting the amount of posts per category not working (Django forum)
I've created a forum on my website, which has 2 different categories within it. These categories are General Discussion and Events. I've split these categories up into their own sections and I've managed to do that just fine. The issue I'm seeing occurs when I try to limit the number of posts that can be seen on the page per category. For example, I only want 4 posts to be displayed for each category on the main forum before the user has to go onto a separate page for those specific category posts. To limit the number of posts per category, I've been using |slice:":4" which is think is the wrong approach. Below is what I've added. Just an FYI, the below does work when there are only 4 posts on the entire website, but as soon as there are more than 4, the amount of posts shown for each category starts to decrease. {% for post in posts|slice:":4" %} <div class="media text-muted pt-3"> <p class="media-body pb-3 mb-0 small lh-125 border-bottom border-gray"> <strong class="d-block text-gray-dark margin-bottom-5"><a href="{% url 'forum_post_details' post.id %}">{{ post.title }}</a></strong> {{ post.content|truncatewords:30 }} </p> <hr> </div> {% endfor %} </div> <div class="my-3 p-3 bg-white rounded shadow-sm"> <h5 … -
Django creating and deleting user-wise caching
I am using Cache in Django. Everything is working fine but what I want is to clear the set of caches for a particular user only. I have a subscription-based platform and whenever a user makes a new subscription, all the caches related to him and only him should be deleted. To achieve user-wise caching, I have used @method_decorator(vary_on_headers('Authorization', 'cookie')) in the rest framework's methods. With this decorator, I am successfully achieving user-wise caching but how can I selectively delete all the caches related to the user. I could execute cache.delete(cache_key) or cache.delete_many(cache_key_list) individually for each URL but the tricky thing here is the find the exact key for those caches. -
How to return entire table row in array by foreign key and how to access from template in django models
I have tried like this. But it is returning the only one combined value. class employees(models.Model): nameininitials = models.TextField(null=True) nameinuse = models.TextField(null=True) employeeno = models.TextField(null=True) departmentname = models.TextField(null=True) def __str__(self): return '{} {}'.format(self.nameinuse, self.employeeno) class Region(models.Model): regionname = models.TextField(null=True) regionalincharge = models.ForeignKey(Erpemployees, on_delete=models.CASCADE,null = True) When I use datalist = Regions.objects.all() , I want all fields from primary table in different variables or array to use in template. -
Django 2.2 with external connection SQL SERVER
In my python 3.7 + Django 2.2 I need to connect to external SQL Server. Its not the main DB of Django (that remains in Postgres). I only need to make some query on a view. Im on Debian 9 and Im trying to install package to add sql server connection but I cant find on google a guide about Debian package to install. I try to install: pip install pyodbc pip install django-mssql-backend but the compile failed. I think Im missing some system libraries. Thanks. -
Django UnitTest keeps throwing KeyError
I have been building this unit-test for the Google Social Login View I made. There were lots of errors so far and I have been able to fix them all rummaging through StackOverflow. However, I have hit the wall while trying to get past this KeyError it keeps throwing at me. The KeyError seems to come from the request header and I tried all sorts of ways of adding key/value pair(in this case, "Authorization":"1234") into the header using Client. Below is my views.py import json import ast import httplib2 import google.oauth2.credentials import jwt import requests from google.oauth2 import id_token from django.shortcuts import render from django.views import View from django.http import JsonResponse from apiclient import discovery from oauth2client import client from pinterrorist.settings import SECRET_KEY from .models import User, Social, Follow class GoogleLoginView(View): def post(self, request): token = request.headers["Authorization"] url = 'https://oauth2.googleapis.com/tokeninfo?id_token=' response = requests.get(url+token) user = response.json() if User.objects.filter(social_id = user['sub']).exists(): user_info = User.objects.get(social_id=user['sub']) encoded_jwt = jwt.encode({'id': user["sub"]}, SECRET_KEY, algorithm='HS256') return JsonResponse({ 'access_token' : encoded_jwt.decode('UTF-8'), 'username' : user['name'], 'user_pk' : user_info.id }, status = 200) else: new_user_info = User( social_id = user['sub'], username = user['name'], social_service = Social.objects.get(name = "google"), email = user.get('email', None) ) new_user_info.save() encoded_jwt = jwt.encode({'id': new_user_info.id}, SECRET_KEY, … -
What is the best way to customize Django admin templates?
I have been trying to customize the django admin create/update form for a Model. I have a field in my database model that I want to generate through certain specification. For that I need a generate button that will generate data for that field and show those data before letting the admin/staff save the data. Model : - title - generated_data [ A paragraph containing random sentences from another Model ] I need an extra field in django-admin where I will specify how many random sentences I want to generate. Clicking generate button will generate that random paragraph and show it to user as a preview before he can save the data for both create and update. Is is possible customize django-admin to do that? -
Django, `KeyError <built-in function id>` in the form
I have created an app that give me the possibility to collect and store all daily income. In this case I have created the following model: class Income(models.Model): income=models.DecimalField() date=models.DateField() In my views I have created an algo that give me the possibility to collect all date monthly, like the following: now=datetime.datetime.now() now=now.year income=dict() for year, month, totals in(Income.objects.values_list( 'date__year', 'date__month'). annotate(totals=ExpressionWrapper(Sum(F('income')), output_field=FloatField())).values_list('date__year', 'date__month', 'totals')): if id not in income.keys() and year == now: income[id]=list(defaults) index=month-1 income[id][index]=totals All works perfectly. But now I want to give the possibility to be able to choose the year manage the now variable. So for this aim I have tried to create a new model, as the following: class Timing(models.Model): TYPE=[ ('2020','2020'), ('2021', '2021'), ] reference_year=models.CharField('Azienda/Privato', max_length=30, choices=TYPE, default="") And in my views I have added the code: now='2020' if request.method == 'POST': form = TimingForm(request.POST) if form.is_valid(): now = form.cleaned_data['reference_year'] But django give me the KeyError <built-in function id>. Where is the issue? I think that the problem is about the fact that now is not a datetime variable? -
my select2 js only work the first form in django formset
i want to use select2.min.js to auto-complete the choices (ForeignKey values) , but it only work for my first form this is my snippet <tbody class="tbody tb1 " id="form_set"> {% for item in items.forms %} <tr class="p-0 col-12"> <td class=""> <div class="col-12 p-0 mt-3 inp"> <input class="col-12 0qarz qarz" type="number" name="" placeholder="qarz"> </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.price | add_class:'col-12 '}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.quantity | add_class:'col-12 '}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.model | add_class:'col-12 0model model' | attr:'id:model'}} </div> </td> </tr> {% endfor %} </tbody> <script type="text/javascript"> $(function(){ $('.tb1 tr:last').formset({ prefix:'{{items.prefix}}', addText:'add', deleteText:'remove', addCssClass:'btn btn-success', }); }) </script> <script type="text/javascript"> $(document).ready(function(){ $("#model").select2() }) </script> but the select2 only work for my first form then doesnt have any effect on other forms ! and how to set number of forms to add_class it will help to solve maybe? thanks -
User ralated Data from other model
I have 2 persons with same name in user model,and both of them have intrest too and level under Intrest model,How can i get a level of the person from User model in session model. And how can i fetch that data in views. class User(models.Model): user_name=models.CharrField(max_length=30): class Intrest(models.Model): user=models.Foreignkey(User,on_delete=models.CASCADE) sports=models.CharrField(max_length=30) line=( ('Beginner','Beginner'), ('Intermediate','Intermediate'), ('Advance','Advance'), ) level=models.CharField(max_length=50,choices=line) class Session(models.Model): Person=models.Foreignkey(User) Level= -
django rest framework fails to serialize foreignkey field from string value
I am trying to submit post data to an api endpoint, which should create a model instance and return the object back in the response. And here is the returned error message. IntegrityError at /api/messages/ null value in column "sender_id" violates not-null constraint DETAIL: Failing row contains (27, null, null, this is a test message, warning: this is a test. this is only a test. please disregard. ..., f, null, f, f). Those first two null fields should be the sender and receiver, which I assume aren't being serialized properly. The post request body looks like this. sender and receiver are foreign key fields. { "sender": "user1", "receiver": "user2", "subject": "this is a test message", "body": "warning: this is a test. this is only a test. please disregard. say hello to your mother for me.", "read": false, "sender_deleted": false, "receiver_deleted": false } Here are my model and view. class MessageSerializer(serializers.HyperlinkedModelSerializer): pk = serializers.IntegerField(read_only=True) sender = serializers.StringRelatedField() receiver = serializers.StringRelatedField() class Meta: model = Message fields = ['pk', 'sender', 'receiver', 'subject', 'body', 'read', 'sender_deleted', 'receiver_deleted'] class Message(models.Model): sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sent_mail') receiver= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='received_mail') subject = models.CharField(max_length=50, default='') body = models.TextField() read = models.BooleanField(default=False) sender_deleted = models.BooleanField(default=False) receiver_deleted = … -
How to create a Django API using django rest framework which shows response from some external source?
Hi all i am in a situation where i need to create a djnago api which on call from frontend gives a response fetched internally from some other source but not from serializers and models. Currently i am using djnago rest framework to create api like below MODELS # Create your models here. class submission(models.Model): # fixed fields to show on today panel/pending panel email_id = models.CharField(max_length=200, primary_key=True) email_sender = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.email_id SERIALIZERS class UserSerializer(serializers.ModelSerializer): class Meta: model = submission fields = ('__all__') VIEWS class SAMPLE(viewsets.ModelViewSet): queryset = submission.objects.all() serializer_class = UserSerializer URLS router = DefaultRouter() # user table router.register('user_table_all_data', SAMPLE, basename='user_table_all_data') and it works as charm , but in order to work with djnago rest framework i always need to call like this 1. create model or use existing model, 2. Create serializers,3. Create Views,4 create URLs, But what if i dont want to use Models say for example i want to show data from other source say which contains a sample json like below sampleData = {"Name":"RAJNISH","Age":32,"ADDRESS":"India"} so if my API is say 'sample/someid (not pk)' returns {"Name":"RAJNISH","Age":32,"ADDRESS":"India"} as response how can i do this in djnago rest framework -
django returns NoReverseMatch but it actually got the value
I'm making a shopping cart app for my website, and the function that worked yesterday was broken today. I got Reverse for 'delete-cart' with arguments '(4,)' not found. 1 pattern(s) tried: ['cart/delete_cart/<int:pk>']error, But you can see that it has displayed the value of the parameter, proving that it got the value but still returned the not found error, why??? Here is my relevant code: urls.py urlpatterns = [ path('',views.myCartListView,name='my-cart'), url(r'^delete_cart/<int:pk>',views.delete_cart,name='delete-cart'), ] views.py @login_required def myCartListView(request): context = {} if request.user: data = Cart.objects.filter(client=request.user) context['cart'] = data return render(request,'cart/my_cart.html',context) @login_required def delete_cart(request,pk): record = Cart.objects.get(pk=pk) record.delete() return redirect('cart/') my_cart.html {% for c in cart %} <tr> <th>{{c.item}}</th> <th>{{c.quantity}}</th> <th>{{c.price}}</th> <th>{{c.get_total_price}}</th> <th><a href="{% url 'delete-cart' c.id %}">DELETE</a></th> </tr> {% endfor %} -
The requested resource was not found on this server. django
I have added my path into urlpatterns songs.urls file which was included in 1 views.py error occured -
Django query expression for counting particular attendance
I have a field that has 1000 rows. In these rows there are 2 status available. Present and Absent. I want to know if there's a query expression to count the total number of students present or absent. class StudentInClass(models.Model): Attendance = models.CharField(max_length=20, default='None') Total_Present = models.IntegerField Total_Absent = models.IntegerField -
DJANGO:How to remove empty QuerySet from the list of QuerySet
This is my list of QuerySets.Now my concern is to remove the list of empty QuerySet i.e.QuerySet [] from the given list. [QuerySet [], QuerySet [], QuerySet [], QuerySet [],[User: kharel321, User: kharelkharel]>] Expected OutPut [[User: kharel321, User: kharelkharel]] -
Django Sitemap Error: 'datetime.time' object has no attribute 'timetuple'
I am using django's built-in sitemap feature to dynamically create sitemap. But I am keep getting this error, and I don't know why? Please help me... Traceback: File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/contrib/sitemaps/views.py", line 16, in inner response = func(request, *args, **kwargs) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/contrib/sitemaps/views.py", line 77, in sitemap else site_lastmod.timetuple() AttributeError: 'datetime.time' object has no attribute 'timetuple' My Code: class NoteClassSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = 'monthly' def items(self): return Classes.objects.all().order_by('-date') def lastmod(self, obj): return obj.date -
Django - compare user objects by field
I have a Dictionary view that shows the list of words created by a specific (special) user: class Dictionary(FilterView): model = Word template_name = 'vocab/dictionary.html' context_object_name = 'dict_list' paginate_by = 15 filterset_class = WordFilter strict = False def get_queryset(self): qs = self.model.objects.filter(user__username__iexact='special_user') return qs def get_object(self): queryset = qs pk = self.kwargs.get('pk') if pk is None: raise AttributeError('pk expected in url') return get_object_or_404(queryset, pk=pk) Now I want any user to be able to come to this page and add any word that they want to, like this: def custom_create_word(request, object): if request.method == 'POST': pass if request.method =="GET": from .forms import WordForm from .models import Word word = Word.objects.get(pk=object) user = request.user target_word = word.target_word source_word = word.source_word deck_name = "My Words" fluency = 0 new_word, created = Word.objects.get_or_create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:dict')) Everything works as expected. But in the template I want the button to look different depending on whether the logged in user already has this word in their own list (which should be judged by if target_word is the same). My template looks like this: <tr> {% for word in dict_list %} <td>{{word.target_word}}</td> <td>{{word.source_word}}</td> <td> {% if user_word %} <a href="" class="btn btn-success btn-sm" >Added</a> …