Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UnicodeDecodeError during error reporting
Error reporting is constantly crashing. In the traceback, I first get the actual error, then many times the same During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in __call__ response = response or self.get_response(request) File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/views/debug.py", line 94, in technical_500_response html = reporter.get_traceback_html() File "/var/www/exc2-backend/.venv/lib/python3.6/site-packages/django/views/debug.py", line 332, in get_traceback_html t = DEBUG_ENGINE.from_string(fh.read()) File "/var/www/exc2-backend/.venv/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128) I am using Python3.6 and Django==2.2. I do not understand where the UnicodeDecodeError comes from. Any ideas? -
Unable to get include js file
I want to include this js file to my template but unable to do so.. It includes rest of links which are not passing values but this is not including because it passing value v=1.4.0, I am new to django please help me out url.py: from django.urls import path from . import views urlpatterns = [ path('test1', views.test1, name='profile1'), ] views.py def test1(request): return render(request, 'user.html') "GET /static/djangoapp/light_css_js/light_js/light-bootstrap-dashboard.js%3Fv%3D1.4.0 HTTP/1.1" 404 1832 -
How to write URL dynamically in HTML
I'm trying to write URL dynamically for EDIT and DELETE button in HTML. But here when i'm trying to edit it changes all, i want edit particular row data only. index.html <tbody> {% for ads_obj in ads_objs %} <tr> <th scope="row">{{ ads_obj.id }}</th> <td>{{ ads_obj.business_id }}</td> <td>{{ ads_obj.description }}</td> <td><a href="{% url 'native:home_ads_edit' %}"><i class="fas fa-edit" style="color:green"></i></a></td> <td><a href="{% url 'native:home_ads_delete' %}"><i class="fas fa-trash-alt" style="color:red"></i></a></td> </tr> {% endfor %} </tbody> </table> view.py def home_view(request): if request.method == 'POST': form = AdsForm(request.POST) if form.is_valid(): business_id = request.POST.get('business_id') description = request.POST.get('description') adsedit_obj = Ads.objects.all().filter(username=username) if len(adsedit_obj) > 0: adsedit_obj.update(business_id=business_id,description=description) return render(request, 'index.html',{}) return render(request, 'login/login.html', {}) urls.py urlpatterns = [ path('signup/', views.signup_view, name='signup_view'), path('login/', views.signin_view, name="signin_view"), path('home/', views.home_view, name="home_view"), path('adsedit/', views.home_ads_edit, name="home_ads_edit") ] [Template view][1] [1]: https://i.stack.imgur.com/jLzhE.png -
Django logic problems
I'm fresh to Django. I have 3 questions/problems regarding logic. Task 1. As soon as the user gets registered an Employee is created, Problem I want each employee to have a set values as default for further processes, e.g. User1=> registers (he is given default or constant values against his id. These values are the amount of leaves each user is granted, Casual leaves = 3 etc) Task 2. Problem I want to be able to restrict the user from applying for a certain type of leave or not apply for a leave at all. Task 3. Problem I want each type of leave to have a specific amount ( Task 1) which the admin can change (e.g. add or deduct), if the user applies for the leave and if accepted then the amount of days he/she applied for should be deducted out of that specific or constant amount of that leave type. My logic is somewhat weak. I would like it if you guys can help me out. You will see what I tried in the code mentioned. forms.py class Leave_Form(forms.ModelForm): to_date = forms.DateField( widget=forms.DateInput(format=('%m/%d/%y'), attrs={'class': 'form-control', 'placeholder': ' Month/Date/Year'})) from_date = forms.DateField( widget=forms.DateInput(format=('%m/%d/%y'), attrs={'class': 'form-control', 'placeholder':' Month/Date/Year'})) class … -
Outer join django Models . Many to Many relationship
I am unable to join the following tables I tried these things . But i am still unable to to join CartDetail and Products table on the basis of product_id I am using django 2.1.7 ''' Product data model ''' category = models.ManyToManyField(Category, blank=True) title = models.TextField(blank=False, null=False) created_by = models.ForeignKey( get_user_model(), on_delete=models.CASCADE) description = models.TextField(blank=False, null=False) price = models.FloatField(default=0.0, blank=False, null=False) product_image = models.ImageField(upload_to='images/', null=True) units_in_stock = models.IntegerField(default=1) created_at = models.DateTimeField( auto_now_add=True, blank=True, null=True) last_updated = models.DateTimeField(auto_now=True) last_updated_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default=None, related_name='updated_by', null=True, blank=True) class Cart(models.Model): ''' Cart For User ''' user_id = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) product = models.ManyToManyField(Product, blank=True,through='CartDetail') # quantity = models.IntegerField(default=1, null=False, blank=False) class CartDetail(models.Model): ''' Further Data of Cart ''' product_id = models.ForeignKey(Product, on_delete=models.CASCADE) cart_id = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField(default=1, null=False, blank=False) class Meta: ''' To make Product Id and User Id Unique ''' unique_together = ('cart_id', 'product_id',) -
how to pass dynamic id inside href tag
here i am trying to filter items based on the category.This code displaying only one items for each category even there are many items inside the category.But the one item which displays belongs to the this category which is correct .How can i display all the items of that category not only one ? template <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#home" role="tab"><span class="hidden-sm-up"></span> <span class="hidden-xs-down">Home</span></a> </li> {% for category in categories %} <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#category-{{category.id}}" role="tab"> <span class="hidden-sm-up"></span> <span class="hidden-xs-down">{{category.title}}</span></a> </li> {% endfor %} </ul> <!-- Tab panes --> <div class="tab-content tabcontent-border"> <div class="tab-pane active" id="home" role="tabpanel"> <div class="pad"> {% for item in items %} <p>{{item.name}}</p> {% endfor %} </div> </div> {% for category in categories %} {% for item in category.product_set.all %} <div class="tab-pane pad" id="category-{{category.id}}" role="tabpanel"> {{item.name}}</div> {% endfor %} {% endfor %} -
TypeError: 'F' object is not subscriptable
I am using Django ORM to query a database called Product having column name price(Decimal) and stock_units(int). I want to Multiply both of the columns and get the accumulated summation. report = Product.objects.filter(stock_units__gte=1).aggregate(Count('name'), Sum('stock_units'), Sum(F('price')*F('stock_units'))) I expect the output to be { "Total product Sold ": { "name__count": 2, "stock_units__sum": 844, "Total amount": 84400 } } But it through an error: TypeError: 'F' object is not subscriptable -
if condition not responding as expected in django for a like button
I actually have a properly working like button for my post, but I wanted that to change to dislike if the user has already liked the post. but am unable to change the button using if condition. view.py file def home(request): post = get_object_or_404(Post, id=id) is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post, 'is_liked':is_liked, } return render(request, 'blog/home.html',context) def like_post(request): post = get_object_or_404(Post,id=request.POST.get("post_id")) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: is_liked = True post.likes.add(request.user.id) return HttpResponseRedirect(post.get_absolute_url()) html file: <form action="{% url 'like_post' %}" method="post"> {% csrf_token %} {% if is_liked %} <button type="submit" name="post_id" value="{{ post.id }}" class= "btn btn-danger">Dislike</button> {% else %} <button type="submit" name="post_id" value="{{ post.id }}" class= "btn btn-info">Like</button> {% endif %} </form> -
Implementation of Google Sign up in Django
I want to implement Google Sign up in my web application using libraries suggested by Google like oauthclient. I want my user to authenticate via google and get signed in. Can anyone help me -
How to Serlialize and Deserialize 2 related models in django?
I have 2 Django Models: from django.db import models class PersonManager(models.Manager): def get_by_natural_key(self, first_name, last_name): return self.get(first_name=first_name, last_name=last_name) class Person(models.Model): objects = PersonManager() first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birthdate = models.DateField() class Meta: unique_together = (('first_name', 'last_name'),) def natural_key(self): return (self.first_name, self.last_name) class Book(models.Model): name = models.CharField(max_length=100) author = models.ForeignKey(Person, on_delete=models.CASCADE) def natural_key(self): return self.name, self.author.natural_key() natural_key.dependencies = ['example_app.person'] when I serialize it: serializers.serialize('json', Book.objects.all(), use_natural_foreign_keys=True, use_natural_primary_keys=True) It returns something like this: ... { "pk": 1, "model": "store.book", "fields": { "name": "Mostly Harmless", "author": ["Douglas", "Adams"] } } ... Now, when I take this JSON and try to deserialize and save it to another DB which DOES NOT have an entry in Person model corresponding to "Douglas", "Adams": deserialized_objects = serializers.deserialize("json", data) for deserialized_object in deserialized_objects: deserialized_object.save() it will give error saying that "matching query does not exist" because it did not find an entry corresponding to ["Douglas", "Adams"] in Person model to which this Book data is pointing to. Is it possible for deserialize save to create entries in the related model as well? For example, if the entry in book is refering to a person and the person doesn't exist, deserialization should create that entry in Person … -
How to add a django rest framework authentication in url?
How to add a django rest framework authentication in url? I am using JWT for authentication of my application. Everything works perfectly. What I need to know is how can I authenticate a particular url based on REST Framework and JWT example from rest_framework.permissions import IsAuthenticated path(r'modulo/app/aula/<modalidade>', IsAuthenticated AppAulaAdd.as_view(), name='app_aula') or from rest_framework.decorators import authentication_classes path(r'modulo/app/aula/<modalidade>', authentication_classes(AppAulaAdd.as_view()), name='app_aula') Both does not work. -
The views didn't return an HttpResponse object. It returned None instead
I am trying to make my new form and in that process i have encountered this issue of The view myapp.views.contact didn't return an HttpResponse object. It returned None instead.Please help me out The problem is in return render function and have no clue of how solve this HttpResponse error from django.shortcuts import render from django.http import HttpResponse from .forms import ContactForm,SnippetForm def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): name= form.cleaned_data['name'] email=form.cleaned_data['email'] print(name,email) form = ContactForm() return render(request,'form.html',{'form':form}) def snippet_detail(request): if request.method == 'POST': form = SnippetForm(request.POST) if form.is_valid(): print("VALID") form = SnippetForm() return render(request,'form.html',{'form': form}) #form.save() Create your views here. The error message is in the browser and the question is itself a error message. -
How to implement a module for different Django versions
I had been running a code in Django 2.1 and moved to Django 2.2. Some codes have changed. How can I implement the code for two different versions? Something like: If django.get_version() >= '2.2': uid = urlsafe_base64_encode(force_bytes(account.pk) else: urlsafe_base64_encode(force_bytes(account.pk)).decode() urlsafe_base64_encode has changed from bytestring to str in the 2.2 release. -
duplicate key value violates unique constraint in django
I have function for creating new user in django as follows: def initialize(username, password, email, title, firstName, lastName, telephoneNumber, mobileNumber, smsActive, for_company_id = 1): sUsername = username.lower() if len(username) > 30: sUsername = username[:30].lower() user = User.objects.create_user(sUsername, email, password, last_login=datetime.datetime.now()) user.first_name = firstName user.last_name = lastName user.save() userProfile = UserProfile(user = user, title = title, telephone = telephoneNumber, mobile = mobileNumber, smsActive = smsActive) userProfile.code2Factor = pyotp.random_base32() userProfile.forCompanyId = for_company_id userProfile.main_updated = datetime.datetime.now() userProfile.save() return userProfile But when I try to create new user I get error as follows: duplicate key value violates unique constraint "auth_user_pkey" DETAIL: Key (id)=(21811) already exists. The id 21811 exists in the database but the last one is 25530. Why django does not use the first next number for ID? -
"how to fix " Error in in django " cannot import channal routing 'projectnaame.routing_channal_routing' no module name routing
I am setting up a new server using WebSocket and I am facing some issues here I am using Python 2.7 Django 1.11 channel 1.1.8 asgirf 1.1.2 daphne 1.4.2 enter image description here i am following this tutorial https://devarea.com/django-simple-channels-example/#.XOd9YHUzY5k -
is there any work around for "django-admin makemessages" not to make changes to already updated translations?
I have added translation for my web app few months back but added some new changes now . For which also i needed to make translation. But they are variables like django messages and notifications. I tried adding translation for them in existing po files but not getting translated. So do i need to generate new po files using make messages command ? . I tried it. but it also bring changes to already translated files. is there any workaround for this problem ? -
Dynamic front end blog template in Django
just a quick question. I'm creating a blog in Django. Everything's almost done, However though in the blog posts, the clients need to decide the layout much like how you do in a CMS site like wix, WordPress and all that. The allignment needs to change for every blog post (Which is decided by the client) . For eg. in some posts there are 3 pictures or in some there are 2 pictures. How do I deal with this ? Is there any way, because the front end template needs to be changed then right ? -
Which pattern to use for a model to have different variations of? Generic FK, multi-table, inheritance, others?
I am having trouble deciding how to structure my models for a particular data structure. The models I have would be Posts, Groups, Users. I want the Post model that can be posted from a groups page or user page and potentially more, like an events page. Posts would contain fields for text, images(fk), user, view count, rating score (from -- a reference to where ever it was posted from like user or group page, though I am unsure how to make this connection yet) I thought about using a Generic Foreign Key to assign a field to different models but read articles suggesting to avoid it. I tried the suggested models, but I wasn't unsure if they were the right approach for what I required. At the moment I went with Alternative 4 - multi-table inheritance class Group(models.Model): name = models.CharField(max_length=64) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='_groups') members = models.ManyToManyField( settings.AUTH_USER_MODEL) def __str__(self): return f'{self.name} -- {self.created_by}' def save(self, *args, **kwargs): # https://stackoverflow.com/a/35647389/1294405 created = self._state.adding super(Group, self).save(*args, **kwargs) if created: if not self.members.filter(pk=self.created_by.pk).exists(): self.members.add(self.created_by) class Post(models.Model): content = models.TextField(blank=True, default='') created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_posts", related_query_name="%(app_label)s_%(class)ss") # class Meta: # abstract = True def __str__(self): return f'{self.content} … -
I was trying to implement an update view that adds +1 to a specific integer field. In the view function, a not defied error occurs
I was trying to implement an update view that adds +1 to a specific integer field. In the view function, a not defied error occurs. error NameError: name 'grade' is not defined model class Best20(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True) url_lec = models.CharField(max_length= 60) author = models.ForeignKey(User, on_delete=True) # grade = models.CharField(max_length= 30) grade = models.IntegerField() view def grade_plus (request, id): Best20.objects.filter (Q (id = id)). Update (grade = grade +1) print ('grade +1 success') return redirect ('') Please let me know if you know how to fix it. Thank you. -
Generic Class based DetailView returns the same page
I am building a photo album app. Where users can log in and create categories and add photo posts in those categories. When post link is clicked it should open the post with the use of DetailView instead, it just loops back to user's post history page with post links I have been trying to use various methods to filter queryset and return the data but I don't where I am going wrong. ```posts/models.py class Post(models.Model): user = models.ForeignKey(User, related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) post_title = models.CharField( max_length=30) post_message = models.TextField() postimage = models.ImageField(upload_to='postimgs/',verbose_name=('post picture')) category = models.ForeignKey(Category, related_name='post_category', on_delete=models.CASCADE) def __str__(self): return self.post_title def save(self,*args,**kwargs): self.post_message_html = misaka.html(self.post_message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single', kwargs={"username":self.user.username,"pk":self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user','post_title'] ```posts/views.py class PostDetail(SelectRelatedMixin, generic.DetailView): model =models.Post select_related = ('user', 'category') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user__username__iexact=self.kwargs.get('username')category__categoryname__iexact=self.kwargs.get('categorynamee') ) ```posts/urls.py app_name = 'posts' urlpatterns = [ url(r'^$',views.PostList.as_view(),name='all'), url(r'new/$',views.CreatePost.as_view(),name='create'), url(r'by/(?P<username>[-\w]+)',views.UserPosts.as_view(),name='for_user'), url(r'by/(?P<username>[-\w]+)/(?P<pk>\d+)/$',views.PostDetail.as_view(),name='single'), url(r'delete/(?P<pk>\d+)/$',views.DeletePost.as_view(),name='delete'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ```HTML <a href="{% url 'posts:for_user' username=post.user.username%}">@{{post.user.username}}</a> </span> <time class="time"> <a href="{% url 'posts:single' username=post.user.username pk=post.pk %}"> {{post.created_at}} </a> ``` After clicking on the {{post.created_at}} should open the post detail view with details, but it is looping in post list page -
django) request.POST method gives me errror : querydict object is not callable
I'm trying to add social login to my django-rest-framework app, but I'm stuck on this problem and need some help. Login Flow: Request code(GET) -> Response -> Request token(POST)(This part is where I'm stuck) -> Response API reference here So, after I log in to social account,(e.g. Facebook)click authorize my app button, I get access code like this : @api_view(['GET', 'POST']) def kakao_login(request): # Extracting 'code' from received url my_code = request.GET["code"] request.session['my_code'] = my_code return HttpResponseRedirect(reverse('kakao_auth_code')) # This makes me redirect to 'kakao_auth_code' url After that, I should ask for token, using user_code I got from above. According to the API document, I should use POST method like this. curl -v -X POST https://kauth.kakao.com/oauth/token \ -d 'grant_type=authorization_code' \ -d 'client_id={app_key}' \ -d 'redirect_uri={redirect_uri}' \ -d 'code={authorize_code}' So I implemented my code like the following : @api_view(['GET', 'POST']) def kakao_auth_code(request): my_code = request.session.get('my_code') try: del request.session['my_code'] except KeyError: pass request.POST(grant_type = 'authorization_code', client_id = '428122a9ab5aa0e8 140ab61eb8dde36c', redirect_uri = 'accounts/kakao/login/callback/', code = my_code) return HttpResponseRedirect('/') But, I get this error at request.POST(...) line. 'QueryDict' object is not callable I just don't know how to solve this issue at request.POST(). Any help would be really appreciated. -
Steps for Creating Login api using django rest framework by Token Authentication
I am trying to create login api with LoginSerializer and LoginAPIView using django-rest-auth, can anyone please explain the steps on how to do it? -
Django - Right way to render html after Ajax call
I have a page with a button which makes an Ajax call and only returns data. I have HTML hard coded in the success handler as string as shown below: var content = "" for (var i = 0; i < result.data.length; i++) { if (result.data[i].profile_picture != undefined) { var img_src = result.data[i].profile_picture } var template = "<div class='row search-location-wrapper'> \ <div class='search-list-section'> \ <a href=/facility/" + result.data[i].id + ">\ <div class='col-sm-2 image-section'> \ <img src='" + result.data[i].profile_picture + "' alt=''> </div></a> \ } Above HTML string is not complete but just to give you an idea of how the rest of the success handler looks like. This does not look like the right way of rendering the HTML as it makes it very hard to debug. Is this the right way to render HTML after making an Ajax call which only returns data? Is there a way I can make the HTML assigned to template variable real HTML and not HTML string? -
Django local variable 'form' referenced before assignment
I m trying to make a form where user enter the state and weather of that location is given back It was working fine untill I added cities = City.objects.all() in the code from django.shortcuts import render import requests from .models import City def index(request): cities = City.objects.all() #return all the cities in the database url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=ec2052730c7fdc28b89a0fbfe8560346' if request.method == 'POST': # only true if form is submitted form = CityForm(request.POST) # add actual request data to form for processing form.save() # will validate and save if validate form = CityForm() weather_data = [] for city in cities: city_weather = requests.get(url.format(city)).json() #request the API data and convert the JSON to Python data types weather = { 'city' : city, 'temperature' : city_weather['main']['temp'], 'description' : city_weather['weather'][0]['description'], 'icon' : city_weather['weather'][0]['icon'] } weather_data.append(weather) #add the data for the current city into our list context = {'weather_data' : weather_data, 'form' : form} return render(request, 'weathers/index.html', context) UnboundLocalError at / local variable 'form' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.1 Exception Type: UnboundLocalError Exception Value: local variable 'form' referenced before assignment Exception Location: C:\Users\Admin\Desktop\the_weather\weathers\views.py in index, line 12 Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\Admin\Desktop\the_weather', 'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\DLLs', … -
how to add margin without ruining responsiveness
so I have three cards in one row but they are all stuck together without margin it looks ugly. I want there to be some margin between each card so I added margin but it ruins the responsiveness bootstrap provides. Thus I added padding only. Any help would be appreciated <div class="row"> {% for all_episode in episode %} <div class="col-6 col-md-4 card" style="padding:20px"> <a href="{% url 'episode_detail' slug=all_episode.slug %}"> <img class="card-img-top" src='{{all_episode.image.url}}'> </a> <div class="card-body"> <h5 class="card-title"> <a href="{% url 'episode_detail' slug=all_episode.slug %}">{{ all_episode.title }}</a> </h5> <p class="card-text">{{ all_episode.story |slice:":100" }}...</p> </div> <div class="card-footer"> <small class="text-muted"> <span class="h5"> <a href="{% url 'series_detail' slug=all_episode.series.slug %}">{{ all_episode.series }}</a> </span> / <span class="h6"> <a href="{% url 'season_detail' slug=all_episode.season.slug %}">{{ all_episode.season }} </a> </span> </small> </div> </div> {% endfor %} </div>