Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Forbidden (403) error when calling the callback URL in django
I am working on a django webapp. I connected the paytm payment gateway with the django app. I did everything according to the docs, and everything works. almost. I am having a problem when calling the callback URL once the payment is over. Here is the code views.py def donate(request): if request.method == "POST": form = DonateForm(request.POST) name = request.POST.get('firstName') phone = request.POST.get('phone') email = request.POST.get('email') amount = float("{0:.2f}".format(int(request.POST.get('amount')))) ord_id = OrdID() cust_id = CustID() paytm_params = { "MID" : MERCHANTID, "WEBSITE" : "WEBSTAGING", "INDUSTRY_TYPE_ID" : "Retail", "CHANNEL_ID" : "WEB", "ORDER_ID" : ord_id, "CUST_ID" : cust_id, "MOBILE_NO" : phone, "EMAIL" : email, "TXN_AMOUNT" : str(amount), "CALLBACK_URL" : "http://127.0.0.1:8000/handlerequest/", } paytm_params['CHECKSUMHASH'] = Checksum.generate_checksum(paytm_params, MERCHANTKEY) return render(request, 'paytm.html', {'paytm_params': paytm_params}) else: form = DonateForm() context = {'Donate': form} return render(request, 'donate.html', context=context) @csrf_exempt def handlerequest(request): form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANTKEY, checksum) if verify: if response_dict['RESPCODE'] == '01': print('order successful') else: print('error: ' + response_dict['RESPMSG']) return render(request, 'paymentstatus.html', {'response': response_dict}) urls.py path('donate', views.donate, name='donate'), path('handlerequest', views.handlerequest, name='handlerequest'), donate.html <form class="test_paytm" action="{% url 'donate' %}" method="post"> {% csrf_token %} <div class="row"> <div class="col"> {{ Donate.firstName|as_crispy_field … -
Django Models Create
my friends from the internet I just wanna ask how can I create a model in Django that will look like this? Table Image -
reset value of model fields to default value in djnago after some time
I was trying to make a Leave management system. there are different types of leaves like PL, SL, CL. Every user gets particular no. Of leaves every year. How do I reset it to default value every year -
Django - updating database with an excel file is causing an error when primary key already exists
Note in my model contact_email is my primary key for the Contact model I have an html page and form where users can upload an excel file to upload their contacts to the database. If contact_email has not been uploaded previously, everything works fine, and contacts are uploaded. However, if the contact_email already exists an error is thrown and contact's info is not updated, for example if in new excel file an existing contact's fav_sport has changed it will not update. Error given is IntegrityError at /upload/ duplicate key value violates unique constraint "contacts_contact_pkey" DETAIL: Key (contact_email)=(john@gmail.com) already exists. Here is the code causing the error: for index, row in df.iterrows(): created = Contact.objects.update_or_create( contact_name = row[0], fav_sport = row[1], contact_email = row[2], ) How can this code be modified to resolve this error? -
Any equivalents of isfile() or isdir() in Django Template Language?
I'm using Python 3.8.1 / django 3.0.3 I wanted to avoid showing directories in my fileList like this: {% for file in fileList %} {% if file isfile %} {{file}} {% endif %} {% endfor %} Previously, I was advised to use {% if file.media %} and it worked perfectly, but it doesn't work anymore. fileList looks like this: def index(request): fileList = os.listdir(settings.MEDIA_ROOT) context = {'fileList':fileList} return render(request, 'gallery/index.html', context) -
Why isn't CSS and Javascript recognized when executing from python?
I'm currently building a website using Django and I've noticed that whenever I execute python manage.py runserver the CSS and Javascript isn't working at all. The HTML is working perfectly but somehow the CSS and JS doesn't get recognized at all. However, when I open the HTML file, the CSS and JS works perfectly, so there is nothing wrong with the CSS and JS files. Somehow it doesn't get recognized when I run the server from python. Is there a reason for this? Here is some code: Views.py from django.shortcuts import render from django.http import HttpResponse import json from django.views.decorators.csrf import csrf_exempt from chatterbot import ChatBot # Create your views here. chatbot = ChatBot( 'Ron Obvious', trainer='chatterbot.trainers.ChatterBotCorpusTrainer' ) @csrf_exempt def get_response(request): response = {'status': None} if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) message = data['message'] chat_response = chatbot.get_response(message).text response['message'] = {'text': chat_response, 'user': False, 'chat_bot': True} response['status'] = 'ok' else: response['error'] = 'no post data found' return HttpResponse( json.dumps(response), content_type="application/json" ) def Index (request): context = {'title': 'Chatbot Version 1.0'} return render(request, "AI.html", context) Settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) project_root = os.path.abspath(os.path.dirname(__file__)) STATIC_DIRS = ( os.path.join(project_root, 'static'), ) INSTALLED_APPS … -
On passing correct instance of FK django still throws error ValueError: Cannot assign "(<>,)": "" must be a " instance. django
So I am updating a model PrescriptionItemDrug, this model has a FK to drug_item = models.ForeignKey(Brand, related_name='drug_item_brand', null=True, on_delete=models.CASCADE) So now on updating the PrescriptionItemDrug prescription_item_drug = models.PrescriptionItemDrug.objects.get(id=drug_item['id']) print('Brand', type(models.Brand.objects.get(id=drug_item['what']))) ## <class 'apps.apis.models.Brand'> prescription_item_drug.drug_item = models.Brand.objects.get(id=drug_item['what']), This raises ValueError: Cannot assign "(<Brand: xyz>,)": "PrescriptionItemDrug.drug_item" must be a "Brand" instance. I've scratched my head a lot but i'm not able to identify whats happening here? Can someone please give me a workaround -
Calling management command from view with file creation
I've a management command which is called from a view via call_command and during the launch of the management command a file gets created on the filesystem. It seems it's jailed to somewhere. How do i make this creation to be located on the "real" root filesystem. And where do i find the jailed files? Django: 1.11.16 Python: 2.7 . -
how to iterate json in django template?
It should be rather obvious and easy to acomplish but for some reason my code doesn't do what I want. My goal is to itterate nested json to get the deep content. My json is created manualy from data fetched from DB and the variable is called reserved. I do pass it to template as json and also I created the simple tag to load the json. It prints only the first level (date) and when I try to print the date's content it prints nothing. What my be the reason of that ? reserved = {} for reservation in user_reservations: date = str(reservation.date) time = str(reservation.time) times = {time:[]} if not date in reserved: reserved.update({date:{"times":{}}}) for seat in reservation.seats.all(): user_seat = {seat.row:seat.number} times[time].append(user_seat) reserved[date]["times"].update(times) context = {} context["reserved"] = json.dumps(reserved) {% for k in reserved|loadjson %} <span>{{k.times}}</span> {% endfor %} -
Keys/values mapping with html select
Please, how can I map fields from excel file and json response(from api) using HTML select elements for the two fields (one for each) -
Aggragate Value django
I would like to aggregate some values from a table in django. Show how many projects I`ve got in my table Aggregate values of the column budget Subtract two values between two objects: Tobeinvoiced = Budget - Invoiced views.py def index(request): projects = Project.objects.all() project_count = Project.objects.count() return render(request, 'projects/index_table.html', {'projects': projects}) models.py class Project(models.Model): budget = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) invoiced = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) tobeinvoiced = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) part of the code from projects.html <h6 class="text-uppercase"align="center">Work in Progress</h6> <h1 class="display-4"align="center">{{ project_count }}</h1> <tbody> {% for project in projects.all %} <td>{{ project.invoiced }}</td> <td>{{ project.budget }}</td> {% endfor %} </tbody> Many Thanks -
register page couldnt register user and not even showingùùùùùùùùùùùùùùùù [closed]
view url patterns url patterns enter image description here register -
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? -
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: 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 … -
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?