Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting error 'QuerySet' object has no attribute '_meta'
getting this error, 'QuerySet' object has no attribute '_meta' how to solve this problem views.py def profile_update_view(request, username): user = User.objects.filter(username__iexact=username) form = UserProfileForm(instance=user) if request.user.is_authenticated and request.user.id == user.id: if request.method == "POST": form = UserProfileForm(request.POST, request.FILES, instance=user) if form.is_valid(): created_prof = form.save(commit=False) created_prof.user = request.user created_prof.save() return redirect('profiles:profile-detail',username=username) return render(request, "profiles/profile_form.html", { "username": username, "form": form, }) -
how to update django 2.0.1 I unable to upgrade from 1.8 version?
How to update django version 2.0.2 from 1.8 I am unable to doing this please help me out i am using python 3.5 enter image description here -
Django crispy-forms / xadmin - IndexError: list index out of range
Could someone help me understand what's going wrong here? I started a new Django project, logged into admin and created a "test" user. When I click on the user url, I could see all the editable fields (name, email, etc.) / user detail page. Then I installed xadmin, ran migrations, etc. All seems to work, except when I click on the user to see the detail page, it throws this error. IndexError at /xadmin/auth/user/2/update/ list index out of range Request Method: GET Request URL: http://127.0.0.1:8000/xadmin/auth/user/2/update/ Django Version: 1.11.10 Exception Type: IndexError Exception Value: list index out of range Exception Location: C:\Users\...\Documents\CSA\portal\portal\apps\xadmin\widgets.py in render, line 81 Python Executable: C:\Python27\python.exe Python Version: 2.7.14 Python Path: ['C:\\Users\\...\\Documents\\CSA\\portal\\portal\\apps', 'C:\\Users\\...\\Documents\\CSA\\portal', 'C:\\WINDOWS\\SYSTEM32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\xadmin-0.6.1-py2.7.egg', 'C:\\Python27\\lib\\site-packages\\six-1.11.0-py2.7.egg', 'c:\\python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf'] Error during template rendering In template C:\Python27\lib\site-packages\crispy_forms\templates\bootstrap3\field.html, error at line 28 list index out of range 18 19 {% if field|is_checkboxselectmultiple %} 20 {% include 'bootstrap3/layout/checkboxselectmultiple.html' %} 21 {% endif %} 22 23 {% if field|is_radioselect %} 24 {% include 'bootstrap3/layout/radioselect.html' %} 25 {% endif %} 26 27 {% if not field|is_checkboxselectmultiple and not field|is_radioselect %} 28 {% if field|is_checkbox and form_show_labels %} 29 <label for="{{ field.id_for_label }}" … -
Django Rest Framework: Call serializer.save using double underscore
When making querysets in Django, you can use the double underscore method, to filter on specific criteria of a model: E.g. instead of filtering restaurant by their pk like this: restaurants = Restaurant.objects.filter(restaurant=<some_pk>) You can filter them by some attribute of the model like this: restaurants = Restaurant.objects.filter(restaurant__uuid=<some_uuid>) Or restaurants = Restaurant.objects.filter(restaurant__name=<some_name>) Now in function in the api views you (e.g. in get_queryset) you can use this to filter by kwargs of the request: def get_queryset(self): restaurants = Restaurant.objects.filter(restaurant__uuid=self.kwargs['uuid']) return restaurants Now I want to do the same using serializer.save(). In my perform create I want to call: def perform_create(self, serializer): serializer.save(restaurant__uuid=self.request.data['uuid']) This unfortunately throws an error. My workaround is this: def perform_create(self, serializer): restaurant = Restaurant.objects.get(restaurant__uuid=self.kwargs['uuid']) serializer.save(restaurant=restaurant) but this obviously has bad performance, because it needs to do an additional queryset. Is there any way to get it work in one step within serializer.save()? Any help would be much appreciated! -
Images from my AWS Bucket not showing on my website
I've implemented AWS S3 storage to my Django project. So I just uploaded all my static images to my bucket. However it is not showing up on my site. My HTML for the images are the standard Django syntax for template: <img src="{% static 'images/settingsIcon.png' %}"> The img src appears to point to the correct URL (the image in my bucket): however the image still doesn't work. Any idea why? -
Django API REST : Issue with function in CreateAPIView
I'm working on my Django API Rest but it's pretty new for me and I have one more question about my code. I'm reading all the time Django Rest Doc ------------------------------------------------------------------------------------------------------------------------------------ FIRST PART - My code : ------------------------------------------------------------------------------------------------------------------------------------ I have a serializer.py file which describe my ModelSerializer like this : class IndividuCreateSerializer(serializers.ModelSerializer) : class Meta : model = Individu fields = [ 'Etat', 'Civilite', 'Nom', 'Prenom', 'Sexe', 'Statut', 'DateNaissance', 'VilleNaissance', 'PaysNaissance', 'Nationalite1', 'Nationalite2', 'Profession', 'Adresse', 'Ville', 'Zip', 'Pays', 'Mail', 'Telephone', 'Image', 'CarteIdentite', ] def create(self, validated_data): print('toto') obj = Individu.objects.create(**validated_data) Identity_Individu_Resume(self.context.get('request'), obj.id) return obj This create function calls another function which is not in my API module, but in my main module : Identity_Individu_Resume As you can see here, this function takes the last created object and applies multiple processes : @login_required def Identity_Individu_Resume(request, id) : personne = get_object_or_404(Individu, pk=id) NIU = lib.Individu_Recherche.NIUGeneratorIndividu(personne) personne.NumeroIdentification = NIU if personne.Image != " " : NewImageName = 'pictures/' + personne.Nom +'_'+ personne.Prenom +'_'+ NIU + '.jpg' FilePath = settings.MEDIA_ROOT FilePathOLD = settings.MEDIA_ROOT + str(personne.Image) FilePathNEW = settings.MEDIA_ROOT + NewImageName file = os.path.exists(FilePath) if file : os.rename(FilePathOLD, FilePathNEW) personne.Image = NewImageName if personne.CarteIdentite != " " : NewCarteName = 'Carte_Identite/' + 'Carte_Identite_' + personne.Nom … -
Post request handling in Django Rest framework
I am using Django Rest Framework, currently to pull some data from the backend we are using Get request, but due to URL limit going high we are planning to implement a Post request. To do this firstly the backend Django Rest API has to be made available to serve a post request. I am new to Django and I don't find a post or get method in the code, all i can say is we are using viewsets, I tried using "@detail_route(methods=['post'])" but this didn't work, what am I doing wrong here? -
How to redirect url other than login_url when using user_passes_test in django decorators?
Here is my code: url(r'^permission_not_granted/',views.permission_not_granted, name='permission_not_granted'), this is inside decorators.py: def is_admin_or_senior_surveyor(user): return user.userrole.id == 1 this is the view method : def permission_not_granted(request): return HttpResponse("Permission Not Granted") Here is my permission: @user_passes_test(is_admin_or_senior_surveyor,login_url=None,redirect_field_name='/permission_not_granted/') -
Delete function in Django not working
I am trying to create a delete function for my Workout model. This is the model: class Workout(models.Model): workoutID = models.AutoField(primary_key=True) name = models.CharField(max_length=40) created_by = models.ForeignKey(User) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def delete(self): return reverse("delete_workout", kwargs = {'workout_id': self.workoutID}) Next I have the view: def delete_workout(request, workout_id): workout = get_object_or_404(Workout, workoutID = workout_id) print(workout) if request.user != workout.created_by: return HttpResponse('Not ur workout') else: workout.delete() return HttpResponseRedirect('/') This is the url: url(r'^(?P<workout_id>\d+)/delete/$', views.delete_workout, name='delete_workout'), And finally the html: <a href='{{ instance.delete }}'> <button>Delete Workout</button> </a> Im not getting any errors in the console, which is why I dont know what is going wrong. Thanks -
Reverse for 'profile-update' with no arguments not found. 1 pattern(s) tried: ['profile\\/update/(?P<pk>[\\-\\w]+)/']
sir i'm getting this error, Reverse for 'profile-update' with no arguments not found. 1 pattern(s) tried: ['profile\/update/(?P[\-\w]+)/'] after the form validation getting that error. I am unable to redirect it. how do i redirect to profile-update how to solve this problem please help me views.py @login_required def profile_update_view(request, pk): user = User.objects.get(pk=pk) form = UserProfileForm(instance=user) if request.user.is_authenticated and request.user.id == user.id: if request.method == "POST": form = UserProfileForm(request.POST, request.FILES, instance=user) if form.is_valid(): created_prof = form.save(commit=False) created_prof.user = request.user created_prof.save() return redirect('profiles:profile-update') return render(request, "profiles/profile_form.html", { "pk": pk, "form": form, }) else: raise PermissionDenied class ProfileDetailView(LoginRequiredMixin,DetailView): template_name = 'profiles/profile_detail.html' def get_object(self): username = self.kwargs.get("username") if username is None: raise Http404 return get_object_or_404(User, username__iexact=username, is_active=True) models.py def get_sentinel_user(): return User.objects.get_or_create(username='deleted')[0] class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.SET(get_sentinel_user)) profile_image = models.ImageField(blank=True, upload_to='imgfolder/profile_image/') magz_cover_name = models.CharField(max_length=20, blank=True, default='') website = models.URLField(default='', blank=True) bio = models.TextField(default='', blank=True) phone = models.CharField(max_length=20, blank=True, default='') class Meta: verbose_name = _("UserProfile") verbose_name_plural = _("UserProfiles") def __str__(self): return '%s' % (self.user.username) def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) urls.py urlpatterns = [ re_path('update/(?P<pk>[\-\w]+)/', views.profile_update_view, name='profile-update'), re_path('(?P<username>[\w-]+)/', ProfileDetailView.as_view(), name='profile-detail'), ] template <form action="." method="post" enctype="multipart/form-data" > {% csrf_token %} {{form.as_p}} </form> -
How can I change django runserver url?
I'm trying to change django project url, so that users, who wants to connect to website in local area network will see url instead of localhost:8000 or 127.0.0.1. I need to change localhost:8000/users/board to be http://example.eu. I've tried to python manage.py runserver http://example.euand then thought about changing url's but it doesn't work. Also tried to change hosts file(Windows OS), but as far as I understand I need real ip address not url. Is it possible to do this thing and how? -
FileNotFoundError: No such file or directory: '/media/images/test2_EDBjGU4.jpg'
view.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from males.models import Male from .forms import MaleForm from django.http import HttpResponseRedirect import io import os from google.cloud import vision from google.cloud.vision import types def detect_text(path): client = vision.ImageAnnotatorClient() with io.open(path, 'rb') as image_file: content = image_file.read() image = types.Image(content=content) response = client.text_detection(image=image) texts = response.text_annotations for text in texts: print(text.description.encode('utf-8')) def response(request): queryset = Male.objects.all() for each in queryset: path = each.image.url detect_text(path) context = { "object_list" : queryset, } return render(request, 'result.html', context) and my result.html <!DOCTYPE html> <head> <title>Success</title> </head> <body> <center> <p>Response text...</p> {% for each in object_list %} {% if each.image %} <img src='{{ each.image.url }}' height="200px" width="200px"> <br /> <p>{{ each.image.url }}</p> {% endif %} {% endfor %} <h3>click <a href='/'>here </a>for HOME</h3> </center> </body> </html> here...in img tag when i use "each.image.url" as source of image it renders an image but when i pass this(each.image.url) argument to detect_text() function that is my client application for google cloud vision api that contains /media/iamge/bill.jpg it shows me error how can i resolve this django version 2.0 python 3.6.4 -
how can we query foreign key and get results of objects which are connected to foreign key
hello guys i want to know what is the way i can use managers to query my foreign key and then retrieve objects that are connected to foreign key so here is my models.py from django.db import models # Create your models here. class BookManager(models.Manager): def title_count(self,keyword): return self.filter(title__icontains=keyword).count() class CategoryManager(models.Manager): def category_count(self): return self.filter(category__icontains=python).count() class Category(models.Model): title=models.CharField(max_length=20) def __str__(self): return self.title class Enquiry(models.Model): title=models.CharField(max_length=200) category=models.ForeignKey(Category ,default=False,blank=False) detail=models.TextField() objects = BookManager() objects=CategoryManager() # tags=models.ChoiceField() def __str__(self): return self.title i tried to use category manager but it gave me a strange error i just want to know how exactly we can get the objects that are connected with category foriegnkey and show them as list to the users -
How to iterate over a list value of a dictionary in django template
I have a dictionary where value are in list { 'Fees': ['88000', '88000'], 'ROll Number': ['I0', 'I1'], 'Mark': [10, 10] } So I am trying to insert this data in table, SO my django template are <table> <thead> <tr> {% for k, v in loan_bank_info.items %} <th>{{ k }}</th> {% endfor %} </tr> </thead> <tbody> <tr> {% for k, value in loan_bank_info.items %} {% for v in value %} <td>{{ v }}</td> {% endfor %} {% endfor %} </tr> </tbody> </table> but in table value are printing as follow, Fees ROll Number Mark 88000 88000 I0 I1 10 10 But what I want is - Fees ROll Number Mark 88000 I0 10 88000 I1 10 how to iterate over list value in django template -
Django and trac integrations
Is there any ways to run the django apps in trac as plugins and host both in the same virtual host in apache? I am using trac to develop plugin but now moving towards django so I like to use it along with trac?? -
How to implement a search algorithm on help topics
We're adding a help guide section to our site and it contains articles on how to use our site. We want to implement search feature - similar to how most support sites work. How do I implement such a feature? For instance, if a user searches for "I want to add a user", how should I search our help topics? My current idea is to add keywords manually for each topic and then match the search query against my keywords. Or should I look to third party tools such as Haystack? Similarly, if a user creates a support ticket, how can we display a list of suggested help topics - similar to how SO suggests answers while I'm typing the question. Or would this follow a different approach? Our site has been built using Django. -
Getting TemplateSyntaxError when trying to use Jinja's replace filter
Below is the snip of code I am using. <ul class="article_list"> {%for article in articles %} <li><a href="{{article.title|replace(' ','-')}}">{{article.title}}</a></li> {%endfor%} </ul> This is the exception I get. Invalid filter: 'replace' Request Method: GET Request URL: http://127.0.0.1:8000/Mathematics/ Django Version: 1.10.5 Exception Type: TemplateSyntaxError Exception Value: Invalid filter: 'replace' My intention is to redirect user to http://127.0.0.1:8000/mathematics/how-to-use-replace-in-jinga when they click on the article: How to use replace in jinga Please help. -
What is Room, Channels and Groups in Django
I'm new to Django and making a feed system using Django where users can receive feed notification from their subscribed channels. But I'm getting confused on these terms (Room, Channels, Groups). Can anybody clarify these terms and let me walk through the process to achieve the feed notification system. Any help would be appreciated. Thanks -
Django -Duplicate Key Errors while using Update_or_Create to save multiple selection form
I'm trying to save data using the model object manager. Everything works for creating a new entry, but I'm unable to update it. Models.py class Choice(models.Manager): def rates (self, Assignment_id, rating2, years,rating_id): assignment = Assignment.objects.get(id=Assignment_id) rating = rating2 rating_id = rating_id for i in range(len(rating2)): yo =NewYear.objects.get(new_year=years[i]) rated = Prog_capability.objects.update_or_create( defaults={ 'task' : task, 'rating' : rating, 'fy' :yo, 'rating_id': rating_id, }, task = task, rating = rating[i], fy = yo, rating_id = rating_id[i] ) class Choice(models.Model): rating_id = models.CharField(primary_key=True,max_length=255) rating = models.CharField(max_length=255, blank=True, null=True) fy = models.ForeignKey(NewYear, related_name="fcap", blank=True, null=True) assignment = models.ForeignKey(Assignment, related_name="tcap") objects = ChoiceManager() Views.py def task_rating(request, Assignment_id): ratings= request.POST.getlist('rating2',[]) years= request.POST.getlist('yo',[]) rating_id = request.POST.getlist('rating_id',[]) rates = Choice.objects.rates(Assignment_id, ratings, years, rating_id) I keep getting this error: duplicate key value violates unique constraint. DETAIL: Key (rating_id)=([u'17-1'....]) already exists. My question is: once I create the entries, how can I structure the model manager to update the entries? I want it to use the rating_id(primary key) to search for the entries and update them and if the rating_id does not exist create a new entry. Thank you in advance for your assistance. -
ImportError: No module named 'wagtail.core'
I am using python3 in a virtual environment and have wagtail installed via pip. When I am trying to extend home model for home page. I get the error:- ImportError: No module named 'wagtail.core' Here is the code of models.py:- from django.db import models from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ] I am following the basic tutorial for wagtail. Here is the link http://docs.wagtail.io/en/latest/getting_started/tutorial.html Version of wagtail==1.13.1 and Django==1.11.10. Kindly point to right direction. Thanks in advance. -
How to use Joined table in django queryset
i was join two table and i want to get field in joined model class school_name_list = Students.objects.select_related('School').values('school_name') but this code raise django.core.exceptions.FieldError: Cannot resolve keyword 'school_name' into field`` how can i solve it? -
how to implement timer in django application to track time spent on a multiple project at the same time by a perticular user?
I am sending the value of time_spent like this to client side: return render(request, 'index.html',{'time_spent':100}) here is my javascript code which I got from heresettimeout Here is my customize javascript code for timer: //Assignment Timer javascript var c = 0; var t; var timer_is_on = 0; function setTime(time){ this.c=time; } function timedCount() { document.getElementById("assignment_timer").value = c; c = c + 1; t = setTimeout(function(){ timedCount() }, 1000); } function startCount() { if (!timer_is_on) { timer_is_on = 1; timedCount(); } } function stopCount() { clearTimeout(t); timer_is_on = 0; } Here is how I call it: <script src="{% static 'assets/js/dls_preload.js' %}"></script> <input type="text" id="assignment_timer"> <script type="text/javascript"> var t="{{time_spent}}"; this.setTime(parseInt(t)); this.startCount(); </script> This is ok for one assignment. but how do I implement when more than one project? -
Send data from django service views to java script(chrome extension)
I am sending email and password from chrome extension to django service to check whether email and password is present in database or not. Next I have to send response from django service to java script(chrome extension). javascript in chrome extension: document.addEventListener('DOMContentLoaded', loginEvents, false); function myAction(femail,fpassword) { //alert("femail=" + femail.value + "fpassword=" +fpassword.value); var strLogin = "email=" + femail.value + "&password=" + fpassword.value; if (femail.value == ""){ alert("Username must be filled out"); return false; } if (fpassword.value == ""){ alert("Password must be filled out"); return false; } var newxmlhttp = new XMLHttpRequest(); var theUrl = "http://127.0.0.1:8000/polls/login/?"; newxmlhttp.open("POST", theUrl, true); newxmlhttp.onreadystatechange = function() { if (newxmlhttp.readyState == 4){ alert("entered"); } else{ alert("not entered"); } }; newxmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); newxmlhttp.send(strLogin); } function loginEvents() { console.log("entered console"); var loginSubmitButton = document.getElementById('loginSubmit') loginSubmitButton.addEventListener('click', function(event) { var userEmail = document.getElementById('email'); var userPassword = document.getElementById('password'); myAction(userEmail,userPassword); }); } views.py: from django.http import HttpResponse from django.http import HttpResponseRedirect, HttpResponse from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render from .models import UserProfile from django.views.decorators.csrf import csrf_exempt @csrf_exempt def login(request): print(request.method) useremail = request.POST.get('email') userpassword = request.POST.get('password') print('email %s %s' % (useremail,userpassword)) try: /* to check the data is present in database or not */ entry = UserProfile.objects.get(email=useremail,password=userpassword) print('matched== %s %s' … -
Django customise response for success and fail
I want to create customise response for both success and fail for 1 of my serializer. Right now i only have the create function for success only I want the output to display like the default output + my 2 other message. promptmsg and status. eg output of json data: if success: promptmsg = "You have successfully create xxx" status = '200' if fail promptmsg = "You have fail to create xxx" status = '400' Here is the code for my views class ScheduleViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Schedule.objects.all() serializer_class = ScheduleSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if not serializer.is_valid(raise_exception=False): return Response({"promptmsg": "You have failed to register an account", "status": "400"}, status=HTTP_400_BAD_REQUEST) response = super(ScheduleViewSet, self).create(request, *args, **kwargs) response.data['promptmsg'] = 'You have successfully create a book' response.data['statuscode'] = '200' return response def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) if not serializer.is_valid(raise_exception=False): return Response({"promptmsg": "You have failed to register an account", "statuscode": "400"}, status=HTTP_400_BAD_REQUEST) # serializer.is_valid(raise_exception=True) # self.perform_update(serializer) response = super(ScheduleViewSet, self).update(request, *args, **kwargs) response.data['promptmsg'] = 'You have successfully create a book' response.data['statuscode'] = '200' return response As you can see, if fail, it will just return … -
Django User to User Messaging ModelForm Setup
I'm trying to build my own custom user to user messaging app for my site. I know about Postman and the other ones, but I'm doing my own for two reasons: 1. Get more familiar with Django, 2. Include the possibility for further customization down the road. As such, I'm trying to create a simple model and ModelForm to use but I'm getting an error. The following is my code. models.py from django.db import models from home.models import Profile class Message(models.Model): recipient = models.ManyToManyField(Profile, related_name = 'recipient') sender = models.ForeignKey(Profile, on_delete = models.CASCADE, related_name = 'sender') subject = models.CharField(max_length = 1000, blank = True) message = models.TextField() sent = models.DateTimeField(auto_now_add = True) unread = models.BooleanField(default = True) def __str__(self): return 'Message from ' + str(self.sender) + '. Subject:' + str(self.subject) For completeness the home.models Profile class is below, though this is not the problem. home.models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null = True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.user.username forms.py from django.forms import ModelForm from django.contrib.auth.models import User from messenger.models import Message class MessageForm(ModelForm): class Meta: model = Message fields = ('recipient','sender','subject','message','unread') I'm simply trying to figure …