Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Encoding with 'idna' codec failed (UnicodeError: label empty or too long) when i use send_email
I have a problem with a contact form on my django project. UnicodeError at /contact encoding with 'idna' codec failed (UnicodeError: label empty or too long) Request Method: POST Request URL: http://127.0.0.1:8000/contact Django Version: 3.0.4 Exception Type: UnicodeError Exception Value: encoding with 'idna' codec failed (UnicodeError: label empty or too long) Exception Location: C:\Users\Florent\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\encoding.py in punycode, line 223 Python Executable: C:\Users\Florent\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.2 Python Path: ['D:\\Développement\\django-simple-blog', 'C:\\Users\\Florent\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\Florent\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\Florent\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\Florent\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\Florent\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] Server time: sam, 7 Mar 2020 23:18:11 +0000 I have this view for my contact form : def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): data = form.cleaned_data plaintext = render_to_string('emails/contact.txt', { 'data': data }) html = render_to_string('emails/contact.html', { 'data': data }) send_mail(subject = 'Demande de contact', message = plaintext, html_message = html , from_email = data['email'], recipient_list = [ settings.CONTACT_EMAIL ]) messages.success(request, 'Votre message à été envoyé avec succès.') else: messages.error(request, 'Une erreur s\'est produite.') else: form = ContactForm() data = { 'form': form } return render(request, 'contact.html', data) Here is my import : from django.shortcuts import render from django.contrib import messages from django.core.mail import send_mail from django.template.loader import render_to_string from django.conf import settings from blog.models import Post, Category from .models import ContactForm Of … -
How to show UniqueTogetherValidator as field error instead of non-field error?
I have a serializer like this: class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = ( 'account', 'first_name', 'last_name', 'email', 'phone_number', ) validators = [ UniqueTogetherValidator( queryset=Contact.objects.all(), fields=['account', 'phone_number'], message='A contact with this phone number is already exists.', ), ] API returns the unique together validator errors as non_field_errors. I want to show it in the specific field. In this case phone_number. How can I do that? -
Django 3.0.4 compatibility with Six package
I am using Django 2.2.10 for my app. I am trying to bump it up to Django 3.0.4. But it's throwing me this error: ImportError: cannot import name 'six' from 'django.utils' (C:\Users\hkhatri\Desktop\capstone\fitgirl-inc\env\lib\site-packages\django\utils__init__.py) I already have six==1.14.0 installed. Can someone please help on how to upgrade my Django version from 2.2.10 to 3. -
Django fails to connect to remote MongoDB server using djongo
I try to connect to use a MongoDB database for the Django project. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'testDB', } -
How to pass javascript variable as url argument
I can't pass javascript variable as the argument to my url. It read the variable as string and instead o variable content it displays variable name. Is there any way to fix it ? const title = movie_info["key"][x] const image = movie_info["value"][x]["image"] const single_movie = "<li><span>"+"<a href = '{% url 'reservations' movie="+title+" %}'>"+title+"</a>"+"</span><img src=/media/"+image+"></li>" path('reservations/<str:movie>', UV.reservations, name='reservations') -
how to define a class and model-less serializer for structure like this
i am new to python and i want to define a class and model-less serializer for structure like this. dataname="file1.txt" sample=[["1","leo","messi","1988"],["2","cr7","ronaldo","1987"], ..., ] albeit the number of items in inner aaray of sample could be variable. In summary, i want to preview top 100 rows of a csv file with rest api. can anyone help me to do this in python? Thank you -
Django slugs, uniqueness
Trying to have urls with slugs as opposed to ids. Have this code: class Word(models.Model): word_text = models.CharField(max_length=64, unique=True) ... slug = models.SlugField(max_length=32, unique=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.word_text) super(Word, self).save(*args, **kwargs) However, when receiving post data from form I get an IntegrityError. The code that parses form is this: def add(request): try: word_text = request.POST["word"] ... except KeyError: ... except IntegrityError: ... word_text = word_text.lower() word = Word(word_text=word_text, definition=definition, example=example) word.save() return HttpResponseRedirect(reverse("index")) Can anybody help? -
Django: unable to read POST parameters sent by payment gateway
I am unable to read POST parameters sent by payment gateway after payment was processed. Payment gateway redirects to returnUrl (I pass this to payment gateway before payment was processed) with some parameters by POST request. In url.py path('cashfreeresponse/',views.cashfree_response, name='cashfree_response'), in views.py @csrf_exempt @login_required def cashfree_response(request): print(request.method) if request.method == "POST": print('inside post method') print(request.POST.get('cf_subReferenceId')) if request.method == "GET": print('inside get method') print(request.GET.get('cf_subReferenceId')) print(request.method) is showing as GET but it was supposed be POST method also print(request.GET.get('cf_subReferenceId')) and print(request.POST.get('cf_subReferenceId')) are showing as None. But it looks like payment gateway sending parameters as POST method. When I pass returnUrl as http://127.0.0.1:8000/cashfreeresponse instead of http://127.0.0.1:8000/cashfreeresponse/ ('/' is missing in the first one) then I am getting error as You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/cashfreeresponse/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. but I see in my google chrome page that payment gateway sending parameters with POST request. Below image shows parameters sent by payment gateway by POST request If I change urls.py to path('cashfreeresponse',views.cashfree_response, name='cashfree_response'), in settings.py … -
QuerySet object has no attribute user
I am having a little problem trying to get list of all my profile users. When I try the code below Django says: QuerySet object has no attribute user class Profile(models.Model): user = models.OneToOneField(settings.Auth) def home(request): p = Profile.objects.exclude(user=request.user) u = p.user -
Django call command with parameters
I've a management command with the following argument parser section: class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('--out', action='store', dest='out', required=True) parser.add_argument('--todos', action='store', dest='todos', \ required=True, nargs='+') parser.add_argument('--filter', action='store', dest='filter') parser.add_argument('--list', action='store', dest='list') parser.add_argument('--add_id', action='store_true', dest='add_id') . I'm trying to call this command from a view / shell, but does not work: from django.core.management import call_command call_command('prg_name', out='/tmp/111.txt') , however i got the following error: argument --out is required . The program is kinda old: python: 2.7 Django: 1.11.16 . How should i call the call_command with parameters with this old layout? What is strange, if i do this: dt = {'--out=/tmp/111.txt': sth} call_command(prg_name, *dt) it works, however i can't define more value for --todos . -
How to track user events in Django along with heat maps
I have created a django web application that allows users to login, logout, create, delete, read, update. There are modal boxes on some pages. I would like to track the actions and the specific modal boxes when a user clicks. I am reading about django-analytics package, but I understand it to implement the type of tracking that I would want. Furthermore, I would to use heat maps to understand the parts of a given web page that a user is more focused on. I have a view that displays several forms via formset_factory. For each of the forms, if the clicks a button a modal box is displayed for the respective form. For each modal box, I would like to track how long the modal box is open. Use heat map to understand which part of the displayed page the user is more focused on. Those are my main thoughts at this point. Any advice on this front? -
Creating serializer for foreign key of foreign key
I have 3 models. Question, Choice, and ChoiceColor. class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question= models.CharField(max_length=200) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) vote_count = models.IntegerField(default=0) class ChoiceColor(models.Model): choice = models.OneToOneField(Choice, on_delete=models.CASCADE, null=True) color = models.CharField(max_length=7) I have a serializer that looks like this: class CreateQuestionSerializer(serializers.ModelSerializer): choice_set = ChoiceSerializer(many=True) class Meta: model = Question fields = ('user', 'status', 'choice_set') def create(self, validated_data): choices_validated_data = validated_data.pop('choice_set') question = Question.objects.create(**validated_data) choices_serializer = self.fields['choice_set'] for choice in choices_validated_data: choice['question'] = question choices_serializer.create(choices_validated_data) return question And another that looks like this: class ChoiceColorSerializer(serializers.ModelSerializer): class Meta: model = ChoiceColor fields = ('color',) class ChoiceSerializer(serializers.ModelSerializer): color_set = ChoiceColorSerializer(many=False) class Meta: model = Choice fields = ('choice', 'color_set') For some reason, when I put in the data it does not work. I need to define a create method for ChoiceSerializer but i'm unsure how to do that? -
Django 3.0 Custom password_reset_form.html
I have updated Django to Version 3.0.3 In 2.2 i used a Custom password_reset_form.html (My Path: /templates/registration/password_reset_form.html) when user clicked on password forgotten. (It worked perfect) After i updated to 3.0.3 it comes just the default django password_reset page. Any solution what i could do? -
How can i select only the first element with Angular? "Django Backend"
so as i mentioned in the title i have django working in the back-end sending my data to angular and i have a list of comments i want to show only the first element of my list in the html page i got this error while trying limitTo Failed to compile. src/app/app.component.html:8:3 - error TS2551: Property 'comment' does not exist on type ' AppComponent'. Did you mean 'comments'? 8 {{comment.author}} ~~~~~~~ src/app/app.component.ts:6:16 6 templateUrl: './app.component.html', ~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component AppComponent. Here is my app.component.html : <ul> <li *ngFor="let topic of topics"> <h2> Hey {{topic.author}}</h2> </li> <h2 ng-repeat="comment in comments | limitTo : 1"> {{comment.author}} </h2> </ul> btw the *ngFor work perfectly i just need to take only the first element for the comments thank you -
django access intermediate fields in template
i have django models like this: class FittingBag(models.Model): ... fittings = models.ManyToManyField("app.Fitting", through="FittingInBagInstances") class FittingInBagInstances(models.Model): fitting = models.ForeignKey("app.Fitting", on_delete=models.CASCADE) bag = models.ForeignKey("app.FittingBags", on_delete=models.CASCADE) qty = models.DecimalField(verbose_name='Quantity' ); is there any way to access intermediate fields (like "qty" ) from django template without prepare date in view? -
Django better join
Here is my models. This is like a sports team org app. Event model is the sports event like a baseball game. Anyone can belong to multiple teams. So, the team member represents the membership to team. class Team(models.Model): name = models.CharField(max_length=100, blank=True) class TeamMember(models.Model): member = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) class Event(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) I want to get the list of events my teams have. def get_queryset(self): teams = TeamMember.objects.filter(member=self.request.user).values('team') return Event.objects.filter(team__in=teams) This does work, but I want to make it to a single join. My ORM-fu is not that great. -
Django: how to populate dropdown with data from a variable after AJAX Post request?
I'm writing some AJAX code that takes the selected value of a dropdown and submits a Post request to a view which returns in a variable some data from a database. What I need is to fill a second dropdown with the data from this variable. Everything works fine except for the last part where I cannot populate the dropdown. In the html code below, 'reg2' is my first dropdown and 'dep' is the one that should be populated: <select name="reg2" class="toChange"> {% for item in regions %} <option val="{{ item }}" {% ifequal item reg %} selected {% endifequal %}> {{ item }} </option> {% endfor %} </select> <script type="text/javascript"> function dropdownChange () { var selectedRegion = $(".toChange option:selected").val(); $.ajax({ url: '/estimmo/templates/', type: 'POST', data: {'reg2': selectedRegion}, }); $("#dep").val(query_results); } $(".toChange").change(dropdownChange); </script> <select id="dep" name="dep"> {% for item in departements %} <option val="{{ item }}"> {{ item }} </option> {% endfor %} </select> The AJAX script calls the following view: @csrf_exempt def MyView(request): if request.method == 'POST' and request.is_ajax: result_r = request.POST.get('reg2') regions = data_immo.objects.values_list("nom_reg", flat=True).distinct().order_by('nom_reg') departements = data_immo.objects.values_list("insee_dep").filter(Q(nom_reg=result_r)).distinct() query_results_dict = { 'regions': regions, 'departements': departements, } return render(request,'home.html', query_results_dict) It seems that until here, all is well. The … -
Modify field format in listview Django
Is there any good way that I can make modifications to individual fields of data in a list view? For example, I have a blog post model that looks like class Blog(models.Model): create_time = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=250) document = models.TextField(blank=True) and my list view looks like this: class BlogPostListView(ListView): model = Blog template_name = 'blog/posts.html' context_object_name = 'posts' ordering = ['-create_time'] Obviously I want to display a list of blog posts in a table format, and I want to modify how the create_time looks (currently showing 'March 7, 2020, 10:16 a.m.', but I only want 2020-3-7 10:16); and the post document can be too long to display in a cell, I want to truncate it into only 150 words. so what are the better ways to achieve this in a listview view? (I read some sort-of similar questions in StackOverflow, but it is either done in the template such as reformating the time which does not solve my second requirement, or too vague to understand). -
(DJANGO) How to set current.username in author comment section
I have Comment model in my Django app. I want to make comment author to be current registered author, not another registered account. Here is screenshot, I can choose user2 account to post the comment, but currently I'm on user1 account. Here is my Django Comment model: class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.ForeignKey(User, on_delete=models.CASCADE) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) And some code from html form: <article class="media content-section"> <div class="media-body"> <!-- comments --> {% if comments.count == 1 %} <h2>{{ comments.count }} comment</h2> {% else %} <h2>{{ comments.count }} comments</h2> {% endif %} {% for comment in comments %} <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> {{ comment.name }} <span class=" text-muted font-weight-normal"> {{ comment.created_on }} </span> </p> {{ comment.body | linebreaks }} </div> {% endfor %} {% if new_comment %} <div class="alert alert-success" role="alert"> Your comment is awaiting moderation </div> {% else %} <h3>Leave a comment</h3> {% load crispy_forms_tags %} <form method="post" style="margin-top: 1.3em;"> {{ comment_form | crispy }} {% csrf_token %} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form> {% endif %} </div> </article> -
Django python manage.py runserver returns attribute error instead of launching the virtual server
I reviewed these lines many times and searched over the website to find similar issue, but I just can't figure out what I missed to generate the erro, kindly, help me solve it :) urls.py - profiles_api from django.urls import path from profiles_api import views urlpatterns = [ path('hello-view/', views.HelloApiView.as_View()), ] views.py - profiles_api from rest_framework.views import APIView from rest_framework.response import Response class HelloApiView(APIView): """test API View""" def get(self, request, format=None): """Returns a list of APIView features""" an_apiview = [ 'Uses HTTP methods as function (get, post, patch, put, delete)', 'Is similar to a traditional Django View', 'Gives you the most control over your application logic', 'Is mapped manually to URLs', ] return Response({'message': 'Hello!', 'an_apiview': an_apiview}) urls.py - profiles_project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('profiles_api.urls')) ] (env) vagrant@ubuntu-bionic:/vagrant$ python manage.py runserver 0.0.0.0:8080 .... path('hello-view/', views.HelloApiView.as_View()), AttributeError: type object 'HelloApiView' has no attribute 'as_View' -
Unable to assign user to a model object which changed the model object
I am using django-simple-history to maintain history of my model changes. I am trying to associate user changing the service object using the way proposed here models.py class UserTrackMixin(models.Model): changed_by = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING) @property def _history_user(self): return self.changed_by @_history_user.setter def _history_user(self, value): self.changed_by = value class Meta: abstract = True class Service(BaseModel, UserTrackMixin): name = models.CharField(max_length=200) serviceType = models.CharField(max_length=200) history = HistoricalRecords() But, when i am trying to assign user object to the attribute _history_user to service object it gives error as mentioned below. u1=User.objects.first() <User: User object (07ab8565-26c7-4bfa-a92e-e12bf924160a)> s._history_user = u1 s.save() ValueError: Cannot assign "<User: User object (07ab8565-26c7-4bfa-a92e-e12bf924160a)>": "HistoricalService.history_user" must be a "User" instance. u1 is User instance, then why does it give this error ? -
Item not submitted to payment after checkout
I am trying to submit a payment using python/django but with no success. I am not sure where is the problem since I am using the same checkout function from the course I am doing. from django.shortcuts import render, get_object_or_404, reverse, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import MakePaymentForm, OrderForm from .models import OrderLineItem from django.conf import settings from django.utils import timezone from tour_store.models import Destinations import stripe # Create your views here. stripe.api_key = settings.STRIPE_SECRET #@login_required() def checkout(request): if request.method == "POST": # call the two forms that will be used order_form = OrderForm(request.POST) payment_form = MakePaymentForm(request.POST) # Then will check if both forms are valid if order_form.is_valid() and payment_form.is_valid(): order = order_form.save(commit=False) order.date = timezone.now() order.save() cart = request.session.get('cart', {}) total = 0 for id, quantity in cart.items(): destination = get_object_or_404(Destinations, pk=id) total += quantity * destination.price order_line_item = OrderLineItem( order=order, destination=destination, quantity=quantity ) order_line_item.save() try: customer = stripe.Charge.create( amount=int(total * 100), currency="EUR", description=request.user.email, card=payment_form.cleaned_data['stripe_id'] ) except stripe.error.CardError: messages.error(request, "Your card was declined!") if customer.paid: messages.error(request, "You have successfully paid") request.session['cart'] = {} return redirect(reverse('destination')) else: messages.error(request, "Unable to take payment") else: print(payment_form.errors) messages.error(request, "We were unable to take a payment with that … -
TemplateDoesNotExist at / .html
Can anyone help me please. I get this error: TemplateDoesNotExist at / .html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.4 Exception Type: TemplateDoesNotExist Exception Value: .html Exception Location: C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.6 Python Path: ['C:\Users\Davids dator\Desktop\templateee\MySite', 'C:\Users\Davids ' 'dator\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\Davids dator\AppData\Local\Programs\Python\Python37', 'C:\Users\Davids dator\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\Davids ' 'dator\AppData\Local\Programs\Python\Python37\lib\site-packages'] Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.4 Python Version: 3.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MyApp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: C:\Users\Davids dator\Desktop\templateee\MySite\Templates.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\templates.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\templates.html (Source does not exist) Traceback (most recent call last): File "C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Davids dator\Desktop\templateee\MySite\MyApp\views.py", line 36, in Index return render(request, "index.html", {'form': context}) File "C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py", line 61, in … -
Django - React SSR Implementing a way to send form data to the database
I'm working on a project where SEO could be crucial. This is why Im using SSR. I'm currenty having trouble with sending form data to the beckhand and then to the database. Is there any comvinient way yo implement this? -
Retrieve list from request in django
how can I put json list to POST request in django? I'm using render method to show data on my site and then edit it with vue framework. render(request, self.template_name, { "form": self.form_class(request.user), "data": json.dumps(data), "keys": json.dumps(keys), }) How can I retrieve edited list in other view using form tags? <form action="{% url 'edit' %}" method="POST"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" name="confirm" class="btn btn-primary"> {% bootstrap_icon "circle-arrow-right" %} {% trans "Next" %} </button> {% endbuttons %} </form>