Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why Django button don't have auto built code as asp.net does?
I am from the background of asp.net, currently i have started working on django, I always wonder why Django button don't have a auto built code or function that will execute on button click as asp.net does ? and can we make such functionality in Django that when we add button the auto built in code for that button will generate ? I am new in Django please provide me the reason why Django use this approach and its advantages and disadvantages ? -
How to incorporate images or graphs and plain-text in same field in Django
In my web-app (say a simple polls app) I want to add images and graphs to question text and options.Can you help we with appropriate field(s) for my models(Question and Option)? I want it to look this way : ................................ . n . Question Text .. ................................ ...... (relavant images) ....... ................................ ...Option1(Maybe a graph/text).. ...Option2(Maybe images)........ -
Django reply to comment in ajax does not work
I am writing an application in django 2.2 with ajax. It's about the comments section and responses to comments. I have two problems: Writing a new comment works. The response to the comment does not work, an error appears: The view spot.views.SpotDetailView didn't return an HttpResponse object. It returned None instead. Validation - if a comment is added, it works, but the error appears on all windows to respond to comments. The validation of the response to the comment does not work, the page source appears instead of the error view.py class SpotComment(SingleObjectMixin, FormView): template_name = 'spot/spot_detail.html' form_class = CommentModelForm model = Spot def get_success_url(self): return reverse('spot_detail_url', kwargs={'slug': self.object.slug, 'id': self.object.pk}) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.form_class(request.POST) form.instance.spot = self.object form.instance.author = self.request.user if form.is_valid(): reply = request.POST.get('comment_id') comment_qs = None if reply: comment_qs = Comment.objects.get(id=reply) form.instance.reply = comment_qs form.save() if request.is_ajax(): context = { 'form': form, 'errors': form.errors, 'object': self.object, } html = render_to_string('spot/comments.html', context, request=request) return JsonResponse({'form': html}) else: context = { 'form': form, 'errors': form.errors, 'object': self.object, } html = render_to_string('spot/comments.html', context, request=request) return JsonResponse({'form': html}) jQuery code: $(document).on('submit', '.comment-form', function(event){ event.preventDefault(); var serialized = $('.comment-form').serialize(); $.ajax({ type: 'POST', url: $(this).attr('action'), data: … -
How to filter django models based on ManytoMany relationhsip and on math calc
Guys i am learning Django and models linking to DB quite confusing for me. I would like to gte your help/guidance . Any help is very much welcomed. I have 4 models: class Profile(models.Model): player = models.CharField(max_length=150) surname=models.CharField(max_length=200) class Meta: db_table='profile' class race19(models.Model): player = models.CharField(max_length=150) profile=models.ManyToManyField(Profile) score19=models.DecimalField(decimal_places=2,max_digits=1000) distance=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='race19' class race18(models.Model): player = models.CharField(max_length=150) profile=models.ManyToManyField(Profile) score18=models.DecimalField(decimal_places=2,max_digits=1000) distance=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='race18' class adjustments(models.Model): player = models.CharField(max_length=150) profile=models.ManyToManyField(Profile) bonus=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='adjustments' I explored django docs and could learn filtering just from 1 table as fowllowing : score_m=race19.objects.annotate(score_margin=F('score19') / F('distance')).filter(score_margin__gt=0.4,) Now i want to be able to get values such as score19, score18, bonus from different tables and i though ManytoMany would help and tried the following: score_growth=race19.objects.annotate( score_change=((F('score19')+F('bonus')) / F('score18')).filter(score_change__gt=0.10,) But this does not work. What i needed to do. Would appreciate if you could share code as thereby i would better understand. Thanks in advance. -
Why the ach form is_bound always false?
i trying to update a modelform while save another modelform, I want to update ach form with the new value from the Payments forms, the ach from is always unbound ?? forms.py : achat = get_object_or_404(Achats,pk=pk) form = Payments_Form(request.POST or None,achat_id=pk) if form.is_valid(): ach = AchatForm(instance=achat) ach.fields['Montant_pay'] = form.cleaned_data['Montant_TTC'] if ach.is_valid(): ach.fields['Montant_pay'] = form.cleaned_data['Montant_TTC'] ach.save() print(ach.errors) print(ach.is_bound) form.save() return redirect('view') forms.py : class AchatForm(ModelForm): class Meta: model = Achats fields = ('Date','Id_Fournis','Montant_HT','Montant_TVA','Montant_TTC','Montant_pay') class Payments_Form(forms.ModelForm): class Meta: model = Payements fields = ('Date', 'mode_de_payement', 'reference', 'Montant_HT','Montant_TVA','Montant_TTC', 'Numero_facture', 'Numero_payement','E_S') -
Datable not working in django/bootstrap 4
Goal: I am using django and bootstrap. I would like to use datatable jquery plugin in my bootstrap table. Issues: The table in my html stay the same and doesn`t use the datatable plugin What Ive done to resolve this issue? I`ve added the two lines in my base.html file base.html <!-- Datatable --> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script> and the javascript code as well: <script> $(document).ready(function(){ $('#dtBasicExample').DataTable(); }); </script> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> My table is name dtBasicExample in my html file: <div class="container-fluid"> <div class="col-sm-20"> <table id="dtBasicExample" class="table table-striped table-hover"> Is there anything I need to add in django to make it work? Many Thanks, -
Apache2&Django - NameError: name "AttributeError" is not defined
I followed pretty much every official documentation to get my Django project running on my Ubuntu 18.04 v-server. And it seems to work...sudo service apache2 status -> everything ok too. [Sun May 03 16:07:20.489608 2020] [mpm_event:notice] [pid 11531:tid 139884218760128] AH00489: Apache/2.4.29 (Ubuntu) OpenSSL/1.1.1 mod_wsgi/4.7.1 Python/3.8 configured -- resuming normal operations [Sun May 03 16:07:20.489764 2020] [core:notice] [pid 11531:tid 139884218760128] AH00094: Command line: '/usr/sbin/apache2' I first noticed that something's off when my templates wouldn't update without a server restart which is not Django's usual behaviour (even in a productive environment). Whenever I restart the server I get this error in the apache2/error.log. Although the server keeps working I want to get to the bottom of this. Exception ignored in: <function Local.__del__ at 0x7fbd983f03a0> Traceback (most recent call last): File "/var/www/my_app/.my_app/lib/python3.8/site-packages/asgiref/local.py", line 95, in __del__ NameError: name 'AttributeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fbd983f03a0> Traceback (most recent call last): File "/var/www/my_app/.my_app/lib/python3.8/site-packages/asgiref/local.py", line 95, in __del__ NameError: name 'AttributeError' is not defined [Sun May 03 16:07:19.418926 2020] [core:warn] [pid 11433:tid 140452536064960] AH00045: child process 11435 still did not exit, sending a SIGTERM [Sun May 03 16:07:20.419208 2020] [mpm_event:notice] [pid 11433:tid 140452536064960] AH00491: caught SIGTERM, shutting down [Sun May 03 … -
invalid syntax in views.py in Django
The code was working. However, I got the error suddenly that can be seen in the image invalid_syntax_error . Even though the name of view and the name of function are same(in this case "addArticle"), I got this error. How can I fix that issue? Here is what my urls.py contains; from django.contrib import admin from django.urls import path from . import views app_name = "article" urlpatterns = [ path('dashboard/',views.dashboard,name = "dashboard"), path('addarticle/',views.addArticle,name = "addarticle"),] -
Django CreateView: How to create the resource before rendering the form
I have a model class for my resource, class Article(db.Model): title = models.CharField(_('title'), max_length=255, blank=False) slug = AutoSlugField(_('slug'), populate_from='title') description = models.TextField(_('description'), blank=True, null=True) content = RichTextUploadingField() Here's my form class class ArticleForm(ModelForm): class Meta: model = kb_models.Article And finally my CreateView, class CreateArticleView(generic.CreateView): form_class = ArticleForm model = Article def get_success_url(self): return "some_redirect_url" Right now I have configured my URLs like below, path('add/', CreateArticleView.as_view(), name='create_article') path('<slug:article>', ArticleDetailView.as_view(), name='article_detail'), path('<slug:article>/update', UpdateArticleView.as_view(), name='update_article') The current flow will render a form when I hit the add/ resource endpoint, and save the resource in the database only after I submit the form. After that, the article can be accessed using the slug generated from the title. What I want instead is to be able to create the Article resource before the resource is rendered, so that the add/ endpoint redirects to some add/unique-uuid endpoint, and even when the form is not submitted from the browser, this empty resource is preserved, and it can be accessed later on because of the unique-uuid. I thought of instantiating an object and redirecting that to UpdateView, but I am having difficulties in figuring out how to keep track of the unique-uuid and point both generated-uuid and slug … -
Django - LANGUAGE_CODE - 'en-IN' does not work, but 'hi-IN' works
Django version 2.2 and 3.0 Purpose: I would like to display numbers in India locale format. For e.g. 1000000 should be displayed as 10,00,000 Action To do this, I went to settings.py and made the following changes: LANGUAGE_CODE = 'IN' - date and time was displayed in Indonesian format but grouping of numbers were correct LANGUAGE_CODE = 'en-IN' - date and time was displayed properly but grouping of numbers were incorrect LANGUAGE_CODE = 'hi-IN' - date and time had Hindi language display but grouping of numbers were correct What I want LANGUAGE_CODE = 'en-IN' to display date and time properly and also do number grouping My settings.py file : LANGUAGE_CODE = 'en-IN' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_THOUSAND_SEPARATOR = True NUMBER_GROUPING = (3,2, 0) USE_TZ = True I had a look at Number Grouping which actually talked about this but I believe documentation is misleading. For starters they have put language code as en_IN which doesn't work. Let me know if any additional information needed. -
Get latitude and longitude after clicking on Geodjango Leaflet map
I have a form with a Geodjango Leaflet map on my page. What I want to achieve is that after clicking somewhere on the map, I get the latitude and longitude from that location, to than store that in my form. The code in the form already takes care of placing a marker on the map. I'm not able to find the location where I clicked. forms.py class PlacesForm(forms.ModelForm): required_css_class = 'required' place = forms.PointField( required=False, widget=LeafletWidget()) class Meta(): model = Places form.html var markers = []; var layerGroup = new L.layerGroup(); $.fn.setMap = function(map) { console.log(layerGroup); layerGroup.clearLayers(); //$(".leaflet-marker-icon").remove(); $(".leaflet-popup").remove(); if( $("#id_latitude").val() && $("#id_longitude").val() ) { map.setView([$("#id_latitude").val(), $("#id_longitude").val()], 18); markers = L.marker([$("#id_latitude").val(), $("#id_longitude").val()]).addTo(layerGroup); if( $("#id_radius").val() ) { L.circle([$("#id_latitude").val(), $("#id_longitude").val()], {radius: $("#id_radius").val()}).addTo(layerGroup); } layerGroup.addTo(map); } } $(document).ready(function() { // Store the variable to hold the map in scope var map; var markers; $(window).on('map:init', function(e) { map = e.originalEvent.detail.map; $.fn.setMap(map); }); $("#id_latitude").on("change", function () { $.fn.setMap(map); }); $("#id_longitude").on("change", function () { $.fn.setMap(map); }); $("#id_radius").on("change", function () { $.fn.setMap(map); }); $('#id_place-map').on("click", function(e) { //var lat = e.latlng; //var lng = e.latlng; console.log(e); }); }); </script> If I look in my console I can't find anything that I can use. I only see the … -
Django tournament
I have a problem with my model, i don't know how to create model called battle, because i want to choose two users from my database but i don't know how to create it class battle(models.Model): user1 = models.ForeignKey(Debatants, on_delete=models.DO_NOTHING) user2 = models.ForeignKey(Debatants, on_delete=models.DO_NOTHING) judge = models.ForeignKey(Judges, on_delete=models.DO_NOTHING) data = models.DateField(auto_now_add=False, auto_now=False) I'd appreciate any hint -
Copying dataframe column dict into Django JsonField
I have a table created with Django(3+) on a postgres database (10+). Class Cast(models.Models): profiles=JSONField(null=True) I am trying to copy a dataframe with a column full of python dict of the form {'test':'test'}. When I use the command: df.to_sql('cast',engine,if_exists='append') I get the following error: (psycopg2.ProgrammingError) can't adapt type 'dict' I tried replacing my dict by None and it worked well. I have correctly added 'django.contrib.postgres' in INSTALLED_APPS ( I don't know if this should be done before creating the database but I guess not) I must add that the postgres database is on a remote server, the django code is on my local computer and the code to copy the dataframe on a second remote server. -
Can I Delete migrations models django?
i am creating my site with django and MySQL (all are latest versions), my data base plan was change. now i want to edit my MySQL database. the project is still testing in face i don't need any data of the database. I'm new for python, Django with MySQL. please help with this. thank you -
How to create a google sign-in popup window that gets closed after login success in Django
I am creating a Django app that allows google sign-in (using python-social-auth). I want the google sign-in page to open in a new window. I am able to implement it with a javascript window.open() function. But after login, the app continues (successfully) on the created window. How do I get it to close itself and redirect the parent to the appropriate redirect_after_login_page? Is there any native way in Django to implement popup windows? -
Exception Value: 'str' object has no attribute '__name__' CreateView
Не получается создать экземпляр класса изза ошибки: Exception Value: 'str' object has no attribute 'name' До некоторго времени работало в норме, а сейчас перестало. Не могу понять в чем проблема. Заранее спасибр view.py class FoodCreateView(CreateView): fields = ('food_name','active_b','food_type_r','boxing_r','profile_pic_i','show_comments_b','User_Create_r') queryset = Food.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user.is_authenticated: context['test'] = self.request.user.id else: pass return context url.py path('food/create/',views.FoodCreateView.as_view(model="Food"),name='create'), Model.py class Food(models.Model): food_name = models.CharField(max_length = 25, verbose_name="Наименование еды") date_d = models.DateTimeField(auto_now=True, verbose_name="Время создания") desc_c = models.CharField(max_length = 256, verbose_name="Описание блюда") active_b = models.BooleanField(verbose_name="Активно?") food_type_r = models.ForeignKey(Food_Type_ref, models.DO_NOTHING, verbose_name="Тип Блюда", related_name='Food_type') boxing_r = models.ForeignKey(Boxing_ref, models.DO_NOTHING, verbose_name="Упаковка") moderated_b = models.BooleanField(verbose_name="Прошел модерацию", default=False) User_Create_r = models.ForeignKey(User, models.DO_NOTHING, verbose_name="Автор") views_n = models.SmallIntegerField(verbose_name="Просморы", default=0) profile_pic_i = models.ImageField(upload_to='profile_pics', blank=True, verbose_name="Фото еды") show_comments_b = models.BooleanField(verbose_name="Отображать комментарии") def __str__(self): return self.food_name def get_absolute_url(self): return reverse('dish_app:detail',kwargs = {'pk':self.pk}) -
cleaned_data is returning wrong/different value
I have been struggling with the Forms in Django. Able to get the value from the cleaned_data but it returns a totally different number. For example, I have 4 values to choose from (2,3,4,5). If I select 2, it will give cleaned_data.get(name_of_form_field) returns 5. And so on. class PopulationForm(forms.Form): districts = forms.ModelChoiceField(queryset=Population.objects.order_by('districtid').values_list('districtid',flat=True).distinct()) There are 4 options for a user to choose from: 2,3,4,5. If the user selects 2, it returns 5 and so on. I am not sure what's happening. Here is my views.py: if request.method == 'POST': form = PopulationForm(request.POST) if form.is_valid(): print(form.cleaned_data.get('districts')) return HttpResponse(form.cleaned_data.get('districts')) Here is my template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django Forms Tutorial</title> </head> <body> <h2>Django Forms Tutorial</h2> <form action="/display/" method="post"> {% csrf_token %} <table> {{form.as_table}} </table> <input type="submit" value="Submit" /> </form> </body> </html> -
Cannot resolve keyword 'pub_date_year'
I followed the documentation django enter link description here this my code model.py from django.db import models # Create your models here. class Reporter(models.Model): full_name = models.CharField(max_length=70) def __str__(self): return self.full_name class Article (models.Model): pub_date = models.DateField() headline = models.CharField(max_length=200) content = models.TextField() reporter = models.ForeignKey(Reporter, on_delete = models.CASCADE) def __str__(self): return self.headline code urls.py from django.urls import path from . import views urlpatterns = [ path('article/<int:year>/', views.year_archive), ] code views.py from django.shortcuts import HttpResponse, render from .models import Article def year_archive (request,year): a_list = Article.objects.filter(pub_date_year = year) context = { 'year' : year, 'article_list' : a_list } return render(request, 'news/year_archive.html', context) and than year_archive.html {%block title%} Article For {{ year }} {%endblock%} {% block content %} <h1>Article For {{year}} </h1> {% for ar in article_list %} <p>{{ar.headline}} </p> <p>By{{ar.reporter.full_name}} </p> <p>Publsihed {{ar.pub_date}} </p> {% endfor %} {% endblock %} I want to ask when i input urls http: // localhost: 8000 / article / 2020 / error appears Cannot resolve the keyword 'pub_date_year' what should I fix -
django DetailView doesn't catch data from ManyToMany field
I have 3 models: first main "Stones" connect by ForeignKey with "Typs" and Many-to-Many with "Mentions". When I try to write a template for detail view for each "stone" with DetailView class, it shows data only from "Stones" and "Typs", not from 'Mentions" my models.py (necessary part) class StonesManager(models.Manager): def all_with_prefetch_mentions(self): qs = self.get_queryset() return qs.prefetch_related('mentions') class Stones(models.Model): title = models.CharField(max_length=30, verbose_name='Назва') place = models.TextField(verbose_name='Месцазнаходжанне') legend = models.TextField(null=True, blank=True, verbose_name='Легенда') typ = models.ForeignKey('Typ', null=True, on_delete=models.PROTECT, verbose_name='Тып') objects = StonesManager() class Typ(models.Model): name = models.CharField(max_length=20, db_index=True, verbose_name='Назва тыпу') def __str__(self): return self.name class StonesImage(models.Model): image = models.ImageField(upload_to=stones_directory_path_with_uuid) uploaded = models.DateTimeField(auto_now_add=True) stones = models.ForeignKey('Stones', on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Mentions(models.Model): work = models.TextField(verbose_name='Праца') year = models.PositiveIntegerField(blank=True, null=True) sacral_objects = models.ManyToManyField(Stones, related_name='mentions', verbose_name='Сакральны аб\'ект') my views.py (necessary part) class StonesDetail(generic.DetailView): queryset = Stones.objects.all_with_prefetch_mentions() template_name = 'volumbf/stone_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['image_form'] = self.stones_image_form() return context def stones_image_form(self): if self.request.user.is_authenticated: return StonesImageForm() return None my template (necessary part) 1. All are shown in the right way <h2> {{ stones.title}} </h2> <p>{{ stones.legend }} </p> <p>{{ stones.place }}</p> <p>Typ: <a href="/volumbf/{{ stones.typ.pk }}/">{{ stones.typ.name }}</a></p> Isn't shown at all Mentions: {% for work in stones.mentions.work %} <p><a href="{% url 'work_detail' work.pk %}"> … -
Django : Best way to Query a M2M Field , and count occurences
class Edge(BaseInfo): source = models.ForeignKey('Node', on_delete=models.CASCADE,related_name="is_source") target = models.ForeignKey('Node', on_delete=models.CASCADE,related_name="is_target") def __str__(self): return '%s' % (self.label) class Meta: unique_together = ('source','target','label','notes') class Node(BaseInfo): item_type_list = [('profile','Profile'), ('page','Page'), ('group','Group'), ('post','Post'), ('phone','Phone'), ('website','Website'), ('email','Email'), ('varia','Varia') ] item_type = models.CharField(max_length=200,choices=item_type_list,blank = True,null=True) firstname = models.CharField(max_length=200,blank = True, null=True) lastname = models.CharField(max_length=200,blank = True,null=True) identified = models.BooleanField(blank=True,null=True,default=False) username = models.CharField(max_length=200, blank=True, null=True) uid = models.CharField(max_length=200,blank=True,null=True) url = models.CharField(max_length=2000,blank=True,null=True) edges = models.ManyToManyField('self', through='Edge',blank = True) I have a Model Node (in this case a soc media profile - item_type) that has relations with other nodes (in this case a post). A profile can be the author of a post. An other profile can like or comment that post. Question : what is the most efficient way to get all the distinct profiles that liked or commented on anothes profile's post + the count of these likes /comments. print(Edge.objects.filter(Q(label="Liked")|Q(label="Commented"),q).values("source").annotate(c=Count('source'))) Gets me somewhere but i have the values then (id) and i want to pass the objects to my template rather then .get() all the profiles again... Result : Thanks in advance -
django rest framework accessing and editing nested model
i'm new to django rest framework, spent last ~2hours looking for the answer and still didn't find one. Let's say i've got 2 models class Person(models.Model): name = models.CharField(max_length=50) class Language(models.Model): person = models.ForeignKey( Person, related_name='prs', on_delete=models.CASCADE) name = models.CharField(max_length=50) i want to be able to access all persons languages like that -> person/{person_id}/language and to access and edit specific language like that -> person/{person_id}/language/{language_id} thanks in advance -
I can not start Django local server
I am learning Django during this lock-down. My app has been running properly , made some changes like adding models ,etc and hit runserver and got errors below: PS C:\Users\RK\RentalMgt\TenancyMgt> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\ProgramData\Anaconda3\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed ValueError: source code string cannot contain null bytes Traceback (most … -
Django session issue while redirecting to other
I am developing the e-commerce website with Django, So after successful payment through Paytm payment gateway(Integration testing) I have a session issue in the local server, after redirecting from Paytm test integration portal to a payment success page (local server ), user session logout automatically while I am on the payment success page. Payment.html file {% extends 'shop/base.html' %} {% load static %} {% block title%} Paytm merchant payment page {% endblock %} {% block content %} {% csrf_token %} <h1>Redirecting you to the merchant....</h1> <h1>Please do not refresh your page....</h1> <form action="https://securegw-stage.paytm.in/order/process" method="post" name="paytm"> {{ form.as_p }} {% for key, value in param_dict.items %} <input type="hidden" name="{{key}}" value="{{value}}"> {% endfor %} </form> <script> document.paytm.submit() </script> {% endblock %} paymentstatus.html file {% extends 'shop/base.html' %} {% load static %} {% block title%}Shoppy hub{% endblock %} {% block content %} {% csrf_token %} <div class="container"> <div class="col my-4"> <h1>Payment status regarding your order Id : {{response.ORDERID}}</h1> {% if response.RESPCODE == '01' %} <h3>Amount paid:{{response.TXNAMOUNT}} </h3> <h3><img style="height:50px;"src="/static/img/success.png" >Your order has been received successfully</h3 > <h3>Thank you for your purchase! </h3> {% else %} <h2> <img style="height:50px;"src="/static/img/fail.jpg" >Your order has been failed</h2 > {% endif%} </div> </div> {% endblock %} {% block … -
Django 3.0.3 IntegrityError FOREIGN KEY constraint failed when making changes to db
I have two models in my database, an 'Account' model (which is a custom user model) and a 'Return' model. My database worked fine up to the point of adding the 'Return' model, which has a ForeignKey relationship with the 'User' model, which I suspect is causing the problem. (Each return belongs to an existing user. In the admin panel, the option box is populated with existing users so I thought this was working correctly?) Appreciate any help with this! Error: IntegrityError at /admin/returns/return/add/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://127.0.0.1:8000/admin/returns/return/add/ Django Version: 3.0.3 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Here is my Return app's models.py: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Return(models.Model): user = models.ForeignKey(User, related_name="returns", on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now=True) last_edited = models.DateTimeField(null=True) TAX_YEAR_CHOICES = [ ('2019', '2019'), ('2020', '2020'), ('2021', '2021'), ] tax_year_ending = models.CharField( choices=TAX_YEAR_CHOICES, max_length=4, blank=False, null=False, ) RETURN_STATUS_CHOICES = [ ('1', 'In progress'), ('2', 'Completed, awaiting review'), ('3', 'Completed, under review'), ('4', 'Completed, awaiting client action'), ('5', 'Submitted to HMRC'), ] return_status = models.CharField( choices=RETURN_STATUS_CHOICES, max_length=1, default=1, blank=False, null=False, ) Here is the post request information from the … -
Django @register.simple_tag of custom tags and filter is not working in template
app/templatetags/custom.py from django import template register = template.Library() @register.simple_tag def add(value, args): return value + args template/index.html {% load custom %} {% with number=0 n=0 %} {% for n in range(50) %} {% if n|divisibleby:6 %} {{ number|add:"1" }} {{ number }} {% endif %} {% endfor %} {% endwith %} I read the official Django Template Tag I want an increment in number like number ++ or number +=1 but it's not working and the server is also working. Somehow I found that {% load custom %} is not working because add function defined is not working. How to solve this error please help !!