Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieve all Chats that have a certain participating user
I have a Chat model in that has a field called users. How could I retrieve all of the Chats, whose users field has a CustomUser with a certain username? There is a ManyToMany relationship between Chats and CustomUsers. I've tried the following, but it doesn't work: user = CustomUser.objects.get(username=username) chats = Chat.objects.filter(users__in=user) -
Django 2.1: How to get a list of objects that in each object, contains the objects that have a foreign key pointing to them
I have these two classes: Class A: data Class B: a = models.ForeignKey(A) How can I get an array of A in which each A contains the B's related to them? I need it because I must return the two tables joined in a JSON. -
Edit form if it exists in model django
I want a form to load with existing data if it exists and if not load a new form. THe problem is that when it loads existing data and i edit it and submit again,the data is not changing in the model or it takes form invalid.It saves with the previously entered data itself my forms.py: class StudentTaskForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form- control',' type': "text",'placeholder':'Enter Title'})) content = forms.CharField(widget=SummernoteWidget()) class Meta: model = Task fields = [ 'title', 'content', ] widgets = { 'content': SummernoteWidget(), } def __init__(self, *args, **kwargs): super(StudentTaskForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Images fields = ('image', ) In my views: todo = Task.objects.filter(todo=qs, student=request.user) print("TODOS",todo) verification = Verification.objects .filter(task__in=todo,is_accepted=True,is_rejected=False) if todo.exists() and verification.exists(): messages.error(request, 'You already completed this task') return redirect('student:level-detail', pk=instance.id) task =Task.objects.filter(todo=qs, student=request.user) Task.objects.filter(todo=qs, student=request.user).update(is_verified=False) if task.exists(): print("ENTO") form = StudentTaskForm(instance=task[0]) else: print("ALLA") form = StudentTaskForm(request.POST or None, request.FILES or None) if form.is_valid(): form.instance.user = User.objects.get(id=request.user.id) obj = form.save(commit=False) obj.student = request.user obj.todo = qs obj.level = instance obj.save() else: print("ERROR",form.errors) ImageFormSet = inlineformset_factory(Task,Images, form=ImageForm,min_num=0, max_num=3, validate_min=True,extra=3) if request.method == 'POST': formset = ImageFormSet(request.POST, request.FILES, instance=task[0]) if formset.is_valid(): formset.save() return redirect('student:dashboard') else: formset … -
Passing a model function to geojson serializer in GeoDjango
Ok, I am trying to add a function defined inside a model (called Highway) to the HttpResponse of the model (Highway) after serializing with geojson serializer without success. I'm trying to find a solution by going through the source code as no errors are passed and the property does not appear in the HttpResponse. I might however be complicating things and hopefully can get another eyes on this. Thank you! The item appears correctly when passing it to the admin site and all other fields (not shown below) work as intended. PS. I'm quite new to the whole Django system. geom.models.py class Highway(models.Model): name = models.CharField(max_length=50, unique=True) length = models.IntegerField("Length in meters") mline = models.MultiLineStringField("Geometry", srid=4326) def cameras_per_km(self): count = self.location_set.filter(location__icontains="camera").count() return round(count/(self.length/1000),1) cameras_per_km.short_description = "Cameras/km" class Location(models.Model): location = models.CharField(max_length=30, unique=True) highway = models.ForeignKey(Highway, null=True, on_delete=models.SET_NULL) point = models.PointField() geom.admin.py (when passing the func to list_display the item appears correclty in admin) class HighwayAdmin(LeafletGeoAdmin): list_display = ('name', 'cameras_per_km') admin.site.register( Highway, HighwayAdmin, ) geom.views.py (this doesn't) def geojson_highway_all(request): geojsonformat = serialize('geojson', Highway.objects.all(), geometry_field='mline', fields = ( 'pk', 'cameras_per_km' # <-- I want this to show ) ) return HttpResponse(geojsonformat) geom.urls.py from django.urls import path from . import views app_name = … -
Count and group by foreign key and return model django
Data Model: Each Store has many Books Each Book may or may not be read by a User dictated by the UserBookReceipt Objective: Given a user, order the libraries by how many pages they have read at each library. Example: User 1 has read: 2 Books from Library 1 5 Books from Library 2 1 Book from Library 3 0 Books from Library 4 We should return the libraries in order of number of books read by User 1 ie: Library 2, Library 1, Library 3 Current solution libraries = (UserBookReceipt.objects .filter(user=user) .values('book__library') .annotate(rcount=Count('book__library')) .order_by('-rcount') ) Actual output [ {'book_library': 2, 'rcount': 5}, {'book_library': 1, 'rcount': 2}, {'book_library': 3, 'rcount': 1} ] Expected output [ {'book_library': <Library: 2>, 'rcount': 5}, {'book_library': <Library: 1>, 'rcount': 2}, {'book_library': <Library: 3>, 'rcount': 1} ] The actual output is 90% of what I want, except I want the book_library value to be instances of the django Library model rather than just the library id. Otherwise, I have to make another query for retrieve the Library objects which would probably require some inefficient ids__in query. How can I count and group by the UserBookReceipt.book__library and return the Library model? If I were to do this … -
Error handling while using chain of groups in celery
I have 100 tasks. But I want to process only 4 tasks at a time. Once these 4 tasks get completed i want to run the next set of 4 tasks. This can be done by grouping tasks in sets of 4 and then chaining them. But some tasks may fail in between, how can I handle these errors and take appropriate actions, so that I retry for only the tasks that failed. As per my knowledge in a chain if one task fails, the subsequent tasks in the chain will not run. So if I implement chain of groups, if any tasks in a group fails, the entire chain will fail. Suggest me a proper error handling method for this, also any better idea for implementing this will be appreciated. A little background - I have a cron running every 30s implemented using celery-beat which picks up 100 new tasks at a time. So all these chaining and grouping has to be done inside the cron function. -
Django rest api google authentication
Hello I stuck in trouble with authentication using Google Gmail platform. I know that there is a lot of topics mention the same situation but none of them help me. That's why I am asking for the brief explanation how to generate this. The first question is - if I am using social-auth-app-django==3.1.0, then facebook API(which is working) works in the same flow as Google Api ? The second question is when I was looking and searching for the answer I found out someone mentioned that Google Gmail api for register user is not working in local preproduction, which I understand like "If I have no domain then it doesn't work" ? In the last part of my question I would try to desribe what kind of problem occur even if I am trying develop everything in the same way like some tutorials show.. At first I tried to put necessary things inside setting.py file: AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.open_id.OpenIdAuth', 'social_core.backends.google.GoogleOpenId', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '***' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '***' Then just create url: path(r'^oauth/', include('social_django.urls', namespace='social')), And that's it, I don't want yet to create any more complex functionalities, before I didn't get a result to redirect for Google … -
WrappedAttributeError 'IsAdminUser' object has no attribute 'authenticate'
I'm using Django Rest Framework with permission_classes to create an API. My understanding is that once I go to that API with an unauthenticated user I should be redirected to the login form, right? Instead, I get the following error: WrappedAttributeError at /sessions/api/listPatients/ 'IsAdminUser' object has no attribute 'authenticate' There's no redirect to the login form... and I don't understand why. Why is this happening? What am I doing wrong? How to fix that? Here's the urls.py: path('api/getSessions/', views.GetSessions.as_view(), name="GetSessionsAPI"), And here's the view: class GetSessions(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = SessionSerializer def get_queryset(self): if self.request.user.is_authenticated: return Session.objects.filter( patient__created_by_user=self.request.user) else: raise PermissionDenied -
Create Download PDF File and store it into a Model
I've created a PDF Creator with WeasyPrint and included the download function. Is it now possible to store that PDF File immediately into a Model-FileField (called Invoice)? How should this code look like? def generate_pdf(request): # Rendered html_string = render_to_string('bills/pdf/invoice.html', context) html = HTML(string=html_string, base_url=request.build_absolute_uri()) result = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/bills.css')], presentational_hints=True); # Creating http response response = HttpResponse(content_type='application/pdf;') invoice_number = context['invoice_id'] filename = "Invoice" + str(invoice_number) + ".pdf" response['Content-Disposition'] = 'inline; filename="{}"'.format(filename) pdf_file = HTML(string=html_string, base_url=settings.MEDIA_ROOT).write_pdf() temp = tempfile.NamedTemporaryFile() temp.write(pdf_file) temp.seek(0) new_bill = Invoice(invoice_no=billNumber, invoice_file=temp) new_bill.save() response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = output return response -
Django ConnectionAbortedError
After running the django server i get this error. I've searched a lot, but could not find any solution to this problem. Traceback (most recent call last): File "C:\Users\Adil\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Adil\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Adil\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Adil\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\Adil\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\Adil\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\Adil\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 796, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine Is there any way to solve it? I got latest Python and Django versions. Django version 2.1.3. Python 3.7.1 Thanks in advance -
Tournament draw with django
I am making a website by using django framework and mysql. I am making this website as a Karate event management systems. So After getting the list of registered players from mysql database to the front end, I want to make a draw. (Knockout matches with byes). when the competetion starts, the user could be able to select the player from the draw. Then that playe's name should be displayed in the next round of the draw. After refreshing the draw, Draw should be as the last updated moment. Is there any idea to do it? I have spent lots of time to it. But still I couldn't do it. Can any one help me. -
how to render html page after ajax success from django backend
I want to render html page after ajax success. but i am not getting the proper path for the file. I am using django backend. I am not using django inbuilt function to authenticate. this is my python code. this is the error this is my project structure //this is my javascript code function admin_login(){ username = document.getElementById("username").value; password = document.getElementById("password").value; console.log(username+password); data={ "username":username, "password":password } $.ajax({ type: 'POST', url: "http://127.0.0.1:8000/admin_login/", data:JSON.stringify(data), success: function(data) { console.log('sucessfully loggedin') window.location.href = "/chat/templates/user.html"; } }); } -
form getting into not valid before sumbitting django
views.py: task =Task.objects.filter(todo=qs, student=request.user) Task.objects.filter(todo=qs, student=request.user).update(is_verified=False) if task.exists(): print("ENTO") form = StudentTaskForm(instance=task[0]) else: print("ALLA") form = StudentTaskForm(request.POST or None, request.FILES or None) if form.is_valid(): form.instance.user = User.objects.get(id=request.user.id) obj = form.save(commit=False) obj.student = request.user obj.todo = qs obj.level = instance obj.save() else: print("ERROR",form.errors) obj=None obj.save() ImageFormSet = inlineformset_factory(Task,Images, form=ImageForm,min_num=0, max_num=3, validate_min=True,extra=3) if request.method == 'POST': formset = ImageFormSet(request.POST, request.FILES, instance=obj) if formset.is_valid(): formset.save() return redirect('student:dashboard') else: formset = ImageFormSet(queryset=Images.objects.none()) Im using django forms and inline formset for saving images for a particular task ... I want the inputs to be saved if the user has already entered the inputs . if task.exists() ,load existing form . The problem is it is gettting into else loop before even going to the form page.HOw do i resolve this?form.errors() are not getting printed -
Retrieving metadata from a post, then sorting posts by said metadata in django
I have two interconnected models in my blog app; Category and Post. The blog front page displays a list of posts and their corresponding metadata, like it should; fairly standard stuff. Aside from displaying the posts on the front page, they're also displayed on the individual user's profile page in short form (just the category and the headline). What I'm interested in doing is sorting all the posts that belong in a category, however the only way I've managed to make it work is something like this: NEWS some title NEWS another title PYTHON another arbitrary title NEWS yet another title I'd like to sort it thusly instead: NEWS some title another title yet another title PYTHON another arbitrary title Alas, my mind keeps turning into a bowl of spaghetti when I try to come up with a method, so without further ado; how should I go about this bit? I reckon that there's something off with calling the category from the post's metadata only to try and categorize the posts via the retrieved data, but aside from that, I'm somewhat lost. Here's the template snippet from user_profile.html: {% if user.post_set.exists %} <p> {% for post in user.post_set.all|dictsortreversed:"date_posted" %} <span … -
Django permissions are not getting cached
I am using django 1.11, postgres with @permission_required decorator in my django views. The problem is that for any view, I get 2 extra SQL queries - 1) SELECT ••• FROM "auth_permission" INNER JOIN "account_myuser_user_permissions" ON ... 2) SELECT ••• FROM "auth_permission" INNER JOIN "auth_group_permissions" ON ... The Django docs state that - The ModelBackend caches permissions on the user object after the first time they need to be fetched for a permissions check. I am unable to understand why the permissions are not getting cached the first time, or am I missing something? -
Define a file path for saving uploaded file by users in Django
Consider if we have a form which contains a field to upload a file by users like this : class PoscastForm(forms.ModelForm): class Meta: fields = ("title", "message", "channel", "file", "tag") model = models.Podcast def __ini__(self, *args, **kwargs): user = kwargs.pop("user", None) super().__init__(*args, **kwargs) if user is not None: self.fields["channel"].queryset = ( models.Channel.objects.filter( pk__in = user.channels.value_list('channel__pk') ) ) And the Podcast model: class Podcast(models.Model): title = models.CharField(max_length=255, default='') user = models.ForeignKey(User, related_name="podcasts", on_delete=models.CASCADE, unique=False) created_at = models.DateTimeField(auto_now=True) channel = models.ForeignKey(Channel, related_name="podcasts", null=True, blank=True, on_delete=models.CASCADE) message = models.TextField(blank=True, null=True) message_html = models.TextField(editable=False) tag = models.ForeignKey('podcasts.Tag', related_name="podcasts", null=True, blank=True, on_delete=models.CASCADE) file = models.FileField(blank=True, null=True, default='') So when a user upload his attach file it will save in root directory of my project! How can I change the direction path? The view for this form is look like this : class CreatePodcast(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): fields = ("title", "message", "channel", "file", "tag") model = models.Podcast def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) -
GraphQL/Graphene for backend calls in Django's templates
I just installed Graphene on my Django project and would like to use it also for the back-end, templating. So far, I find just tutorials how to use it only for front-end, no mention about back-end. Should I suppose that it is not a good idea to use it instead of a SQL database? If yes, then why? Is there a downside in the speed in the comparison to a SQL databases like MySQL? What's the best option how to retrieve the data for templates in Python? I mean, best for the performance. Thnx. -
I am getting a double login form with 2 usernames and passwords
I am getting 2 username and password fields on my login page. I tried to make a custom django authentication login page. The first username and password field that appeared on my page is the default login page given by django whereas the second pair is the formatted one which I tried to create using bootstrap. Here are my files: Here is my login.html div class="container"> <form method="POST"> {% csrf_token %} <div class="form-group"> {{form.as_p}} </div> <button type="Submit" class="btn btn-primary"> Log In </button> </form> </div> loginform.py from django import forms from django.contrib.auth.forms import AuthenticationForm class LoginForm(AuthenticationForm): Username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) Password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'})) urls.py from django.urls import path from . import views from django.contrib.auth.views import login,logout from .loginform import LoginForm urlpatterns = [ path('', views.HomePageView, name='home'), path('accounts/login', login, {'authentication_form' : LoginForm},name='login'), path('accounts/logout',logout,name='logout') ] -
Django can not save the model inside restless Endpoint
I'm facing with a very strange issue. Basically I've written a JSON interface which a remote server would feed it with log data about a batch. I'm adding each JSON data to BatchStatusLog table, and last log contains extra information about the batch and I'm trying to update the batch with last request. Problem starts here; There are no exception on logs both on local and remote server, everything seems fine. Even I see the log lines after batch.save() but batch could not be updated successfully on database. The strangest one, I've written a small script to mimic server, and it could update the batch!! There is something that I can not see. from restless.views import Endpoint from restless.auth import BasicHttpAuthMixin, login_required from api.authentications import CustomAuthMixin from api.utils import date_with_tz_from_timestamp from splitter.models import Batch, BatchStatusLog class BatchStatusLogEndpoint(Endpoint, BasicHttpAuthMixin): def post(self, request): if request.data is None: return {'is_valid': False, 'message': 'No data'} try: data = request.data['data'] entry = data['status_entry'] batch_id = entry["batch_id"] message = entry["text"] state = entry["state"] item = entry["item"] total_items = entry["numOfItems"] timestamp = entry["timestamp"] except Exception as e: print('EXCEPTION: ' + str(e)) return {'is_valid': False, 'message': 'key {0} is required'.format(str(e))} try: batch = Batch.objects.get(id=batch_id) except Batch.DoesNotExist as e: … -
firebase storage bucket gives 403 for non authentication required files if files are uploaded via firebase web interface
I have uploaded some static files to the bucket via the web interface of firebase. Here are my security rules: service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read, write: if request.auth != null; } match /{static=**} { allow read: if request.auth == null } } } If I upload the files via the django admin (using django-storages) I can access the files that are in the static folder without authentication. If I use the firebase webinterface to upload them, I receive a 403. What additional security rule am I missing here? -
How can I only print the the current logged in user data in Django?
from django.db import models from django.contrib import auth from django.urls import reverse from django.contrib.auth.models import User models.py class placement(models.Model): user=models.ForeignKey(User,related_name='placeid', null=True, default=None,on_delete=models.CASCADE) name=models.CharField(max_length=150, blank=True, null=True) ad_space=models.CharField(max_length=100, blank=False, null=False) PID_TYPE = ( ('FN','FORMAT_NATIVE'), ('FNB','FORMAT_NATIVE_BANNER'), ('FI','FORMAT_INTERSTITIAL'), ('FB','FORMAT_BANNER'), ('FMR','FORMAT_MEDIUM,RECT'), ('FRV','FORMAT_REWARDED_VIDEO'), ) format = models.CharField(max_length=3,choices = PID_TYPE,default = 'FN',blank=False, null=False) pid=models.CharField( max_length=50,default='',blank=False, null=False) cpm=models.IntegerField(default=0,blank=False, null=False) ADS_TYPE=( ('FB','FACEBOOK'), ('G','GOOGLE'), ) source=models.CharField(max_length=2,choices=ADS_TYPE,default='FB',blank=False, null=False) comments=models.TextField(default='',blank=False, null=False) objects=models.Manager() def __str__(self): return self.name def get_absolute_url(self): return reverse("dashapp:disp")` views.py class createPlace(LoginRequiredMixin,CreateView): fields=('name','ad_space','format','pid','cpm','source','comments') model=placement template_name='createpl.html' def form_valid(self, form): form.instance.user = User.objects.get(id = self.request.user.id) return super(createPlace, self).form_valid(form) class Idlist(LoginRequiredMixin,ListView): model=placement template_name='placement_list.html' def get_queryset(self): query_set=super().get_queryset() return query_set.filter(placement.objects.filter(user=self.request.user))` Now What query i have to make in Idlist class in Views.py to fetch only the current logged in user related data. And the query that I'm Perfroming in Idlist is giving me error as Exception Type: ValueError Exception Value: too many values to unpack (expected 2) I'm New to to this and any help would be best for me. Please have a look and help a newbie out -
How to avoid Cache error on django 1.11 and redis 3.0
Recently our Redis pack was updated from version 2.10.6 to version 3.0.1. Because of that we start to have a DataError exception, raised when we try to login to django web site. The solution we got was to revert the update and fix the Redis version to 2.10.6, this worked fine, and acording to the Redis docs, this error is expected, as they changed some encoding restrictions: redis-py 3.0 only accepts user data as bytes, strings or numbers (ints, longs and floats). Attempting to specify a key or a value as any other type will raise a DataError exception. My querstion, is that if this is an error with Django 1.11? And, if this is the case, how can we update to Redis 3.0, without getting that raise? -
Best way to count number of records from NDB library
I am developing an application in which I am explicitly using memcache with Google Appengine's NDB library. I want something like this. 1) Get 100 records from datastore and put them in memcache. 2) Now whenever user wants these records I would get these records from memcache instead of datastore. 3) I would invalidate the memcache if there is a new record in datastore and then populate the memcache with 101 records. I am thinking of an approach like I compare the number of records in memcache and datastore and if there is a difference, I would update the memcache. But if we see documentation of NDB, we can only get count by retrieving all the records, and this is not required as datastore query is not being avoided in this way. Any help anyone? Or any different approach I could go with? Thanks in advance. -
Cookie behavior in Django
I've been doing some research on cookies in Django for some time now. However, I don't understand the following. The default setting in django for the SESSION_COOKIE_DOMAIN is None so the domain attribute will be empty. Django sets the session cookie in the session middleware: response.set_cookie( # ... domain=settings.SESSION_COOKIE_DOMAIN, ) The set_cookie function from the response object has the following relevant part if the domain is None which is the default setting in Django: if domain is not None: self.cookies[key]['domain'] = domain Therefore, I assume that the domain in the cookie header is omitted. I've read this great article about cookies and user2864740 made a nice conclusion about it: "When no domain is set in the cookie, the cookie should only match the exact host name of the request. No sub domains, no partial matches. This means simply not including the domain attribute – it is not valid to set an empty domain attribute." 1.) Why does the cookie still work if it's not valid to leave the domain attribute empty or did I missunderstood something here? 2.) Let's assume I own the domain example.com I don't modify the default settings from django so SESSION_COOKIE_DOMAIN is None If I inspect … -
Defining initial field value in def __init__
I'm struggling to figure out why I'm not able to populate the jurisdiction field with the value indicated in my def init in forms.py. Is there a problem with the way that I'm setting the initial value of this field? I should not that the only thing that doesn't work related to this form is the setting of the initial value. All other functionality works, which is why I haven't included the rest of the code associated with this form. def __init__(self, *args, **kwargs): self.taxtype = kwargs.pop('taxtype',None) self.jurisdiction = kwargs.pop('jurisdiction',None) super(TaxEditForm, self).__init__(*args, **kwargs) if self.taxtype == 1: self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.all()] self.fields['jurisdiction'].queryset = State.objects.all() self.fields['jurisdiction'].initial = State.objects.get(name=self.jurisdiction) Thanks!