Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
context_processor with if inside
first of all , thanks for all the answers that have permit me to get better at django, i'm not yet an "uber" djanglers but i'm moving forward. I'll got a problem with a project. As i'll move into django i'll keep being stuck with the same problem: I got django allauth installed to have several field in registration for a horse club in this fields i'll have a choices field, with the mount level. here is the model code : from django.db import models from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): PRIME = ( ('régulier', 'régulier'), ('occasionnel', 'occasionnel'), ('concours', 'concours'), ) NIVEAUX = ( ('débutant', 'débutant'), ('galop1', 'Galop 1'), ('galop2', 'Galop 2'), ('galop3', 'Galop 3'), ('galop4', 'Galop 4'), ('galop5', 'Galop 5'), ('galop6', 'Galop 6'), ('galop7', 'Galop 7'), ) AGE = ( ('18 mois - 3ans', '18mois - 3ans'), ('3 - 5 ans', '3 - 5 ans'), ('6 - 12 ans', '6 - 12 ans'), ('13 - 60 ans', '13 - 60 ans'), ) PHOTO =( ('oui', 'oui'), ('non', 'non'), ) prenom = models.CharField(max_length= 120) nom = models.CharField(max_length= 120) telephone = models.CharField(max_length=12) adresse = models.CharField(max_length=250) ville = models.CharField(max_length=120) code_postal = models.IntegerField(default="63120") occurence = models.CharField(choices=PRIME ,max_length = 150, … -
Query next smaller and next bigger instance of model in one queryset in Django
For example I have a following model: class Example(models.model): number = PositiveSmallIntegerField() I have 10 model instances saved in DB with number field like: [1, 2, 5, 8, 4, 75, 11, 6, 55, 18] And I would like to query 2 model instances with next smaller and next bigger number field to my exact instance. Example. If I have an instance with number 11, than next lower one would be 8 and greater would be 18. Is it possible to query these 2 closest instances by using Django ORM in one queryset? -
React Native Expo with Graphene in Django
I am new on mobile app development, i am using React Native Expo, and all Tutorials that I have searched so far is integrated with Firebase, But I am working on Django Graphene, I could not find any example, documentation or tutorial for using Graphene + React Native. How they are connected to each other. If anyone can help me, I'd be much appreciated. Thanks a lot -
How to get rid of CSRF verifcation issues while trying to send emails (Django)?
I want to receive the message from the contact form in a particular email 'example@example.com' . I have made the views and while rendering in the template I got Forbidden (403) CSRF verification failed. Request aborted error. views.py def send_email(request): name = request.POST.get('name','') subject = request.POST.get('subject', '') message = request.POST.get('message', '') from_email = request.POST.get('from_email', '') if subject and message and from_email: try: send_mail(name, subject, message, from_email, ['example@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponse('Thank you. Your message has been delivered successfully') else: # In reality we'd use a form class # to get proper validation errors. return HttpResponse('Make sure all fields are entered and valid.') def contact(request): return render(request,'newspaper/contact.html') contact.html <div class="row"> <div class="col-12 col-lg-8"> <div class="contact-form-area"> <form method="POST"> {% csrf_token %} <div class="row"> <div class="col-12 col-lg-6"> <input type="text" class="form-control" id="name" placeholder="Name" name="name"> </div> <div class="col-12 col-lg-6"> <input type="email" class="form-control" id="email" placeholder="E-mail" name ="from_email"> </div> <div class="col-12"> <input type="text" class="form-control" id="subject" placeholder="Subject" name="subject"> </div> <div class="col-12"> <textarea name="message" class="form-control" id="message" cols="30" rows="10" placeholder="Message" name="message"></textarea> </div> <div class="col-12 text-center"> <button class="btn newspaper-btn mt-30 w-100" type="submit">Send Message</button> </div> </div> </form> </div> </div> -
Django forms validation: working in dev but not in production (nginx/gunicorn/supervisor)
My Django project is currently deployed in a test remote server using nginx/gunicorn/supervisor. I try to update minor change 'on the fly' remotly. I have a field with expected format: XXX-YY-000 I have added Jquery field mask on a field (AAA-AA-999) and want the user be able to enter lowercase but want to store result in database in uppercase Moreover, I have form validation: on length (10) YY that should correspond to specific XXX (patient_code_is_valid function) So I modify by code entries using upper() method Locally, it works but on remote server it doesn't work ! I don't know how to 'debug' to see what is pass to my patient_code_is_valid function... forms.py def clean_ran_num(self): data = self.cleaned_data['ran_num'].upper() if len(data) != 10: raise forms.ValidationError(_("Error on Patient code number format (example: XXX-YY-000)")) if not patient_code_is_valid(data): raise forms.ValidationError(_("Error on Patient code number: country code does not correspond to site code")) return data models.py def patient_code_is_valid(code): site = code[4:6].upper() pays = code[:3].upper() site_list = [s.sit_abr for s in Site.objects.all()] pays_list = [p.pay_abr for p in Pays.objects.all()] if site in site_list and pays in pays_list: a = Site.objects.get(sit_abr = site).reg.pay.pay_ide b = Pays.objects.get(pay_abr = pays).pay_ide if a == b: return True return False -
how to get hour from timestamp and attonate it and count its number of occurances in django
I have a "startTime" field in my model which contains timestamp.I want to get a list with count of only hour from that stamp.I mean my code should be able convert and get only hour from the timestamp and count the number of occurance of each hour.I tried doing datetime.datetime.fromtimestamp(int(<timestamp>)).strftime(\'%H\')) this thing returns only hour from a timestamp but when i tried incorporating it in the queryset..it failed..this is what i tried in my views.py timehour = InteractionWith.objects \ .values('startTime')\ .annotate(times=Count('datetime.datetime.fromtimestamp(int("startTime")).strftime(\'%H\'))')) -
remove table tags but not p tags with BeautifulSoup
I have problem with delete table in text in django object. Sometimes I have <p> tags inside <table>. How to avoid delete p tags but delete table tags. For now I am deleting table and it is ok when p tag is outside of table. To do all this things I am using BeautifulSoup. for obj in article: soup_en = BeautifulSoup(obj.text_en, features="html5lib") if soup_en.find_all('table'): for i in soup_en.select('table'): i.decompose() obj.text_en = str(soup_en).replace(r'\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n','').replace(r'\r\n', '\n').replace('#####444#####', '').replace('#####555#####', '') obj.save() -
How to create a wrapper for a hybrid mobile app, using Python/Django as backend?
I wrote a website with a log-in function and different apps behind the log-in using HTML, CSS, JS and Python/Django for the backend. Now I would like to create a hybrid mobile app and I want to be able to use the database I created using Django for the mobile app. I also need to mobile app to be automatically synced with the web app. I know that it is possible to create a wrapper for the website and style it appropriately for an app - what program would be good to use for this? Thanks guys! -
Django cms missing migration error while upgrading
I am trying to upgrade a django/django-cms project from django-cms 3.0.7 to 3.7 and I have django 1.7.11 which should be at least 2.2. I upgraded django cms from 3.0.7 to 3.0.16 without any problem. But from there to 3.1.0 I get an error: Migration events.0015_somemigrationname dependencies reference nonexistent parent node (u'cms', u'0003_auto_20140926_2347') Although, when I go and check the migrations of cms I see that this particular migration exists: 0003_auto_20140926_2347 I have this dependency in almost all of my plugins and in some other third party apps like django-cms filer etc. This issue is mentioned and said to be fixed with django-cms 3.0.13 But I am still getting this problem. I have no clue why... -
Django, How to not delete related object (forignkey related) when parent is deleted
I have a user model refers as User and Product model. When user delete himself,I dont want the related objects to be deleted. Is there any vulnerabilities in the below code ? class Product(models.Model) user = models.ForeignKey(User,on_delete=models.PROTECT) Or is the below code is correct ? class Product(models.Model) user = models.ForeignKey(User,on_delete=models.DO_NOTHING) -
How to update all instances of a model for multiple models on the same page?
I am trying to update all instances of Goals and Competencies all at once, within the same page, using modelformset_factory. However, everytime I do that, it loads very weirdly such that goals formset will never be saved. If i were to erase the form.is_valid() for goals, it will load perfectly with the exception of goals formset not being saved within the database. I think the form for goals is invalid, and I have no idea how to continue. I am new to Django and am wondering if I am doing this the wrong way with regards to updating all the instances of multiple model at the same time. models class Goals(models.Model): appraisal = models.ForeignKey(User_Appraisal_List, blank = False, null = True, on_delete=models.SET_NULL) summary = models.CharField(max_length = 150, blank = False, null = False) class Competencies(models.Model): appraisal = models.ForeignKey(User_Appraisal_List, blank = False, null = True, on_delete=models.SET_NULL) summary = models.CharField(max_length = 150, blank = False, null = False) class User_Appraisal_List(models.Model): STATUS_CHOICE = ( ('Employee', 'Employee'), ('Manager', 'Manager'), ('S2Employee', 'S2Employee'), ('S2Manager', 'S2Manager'), ('Approved', 'Approved') ) status = models.CharField(max_length = 30, blank = False, null = False, choices=STATUS_CHOICE) views.py def UpdateAppraisal(request, *args, **kwargs): id = kwargs.get('mk') selfappraisal = get_object_or_404(User_Appraisal_List, id=id) GoalsFormset=modelformset_factory(Goals, form = AppGoalsForm, extra … -
How to use python-socket io with django restframework?
I found socket.io good for real time things. There is a python based implementation called python-socketio. I wanted to use it in django rest framework to support push notifications. For example, I implement push notification on client side when new object is created. Now I just have no idea how to integrate it with django restframework. Question: How to use python-socketio with django restframework'? (Any ideas or sources) -
Django REST Framework return a pdf without using database
I'm trying to create Django REST API. It should get data via POST request and based on that data it should create a pdf(using xhtml2pdf). It should be a simple project, so I'd like not to include a database, and that is the question, is it possible to do it without a database(the request will contain dates, strings, and arrays). -
How to save object of django model without giving all fields values?
model of contact class Contact(models.Model): owner = models.ForeignKey(User,related_name="contacts",on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) account_name = models.CharField(max_length=100) title = models.CharField(max_length=200,null=True,blank=True) email = models.EmailField(null=True,blank=True) phone = models.BigIntegerField(null=True,blank=True) mobile = models.BigIntegerField(null=True,blank=True) assistant = models.CharField(max_length=100,null=True,blank=True) assistant_phone = models.BigIntegerField(null=True,blank=True) Department = models.CharField(max_length=100,null=True,blank=True) fax = models.CharField(max_length=100,null=True,blank=True) date_of_birth = models.DateField(null=True,blank=True) skype_id = models.CharField(max_length=100,null=True,blank=True) twitter = models.CharField(max_length=100,null=True,blank=True) country = models.CharField(max_length=100,null=True,blank=True) state = models.CharField(max_length=100,null=True,blank=True) city = models.CharField(max_length=100,null=True,blank=True) street = models.CharField(max_length=100,null=True,blank=True) pin_code = models.IntegerField(null=True,blank=True) description = models.TextField(null=True,blank=True) added_on = models.DateTimeField(auto_now_add=True) As you can some fields have blank=True means we don't need to give a value to that field during creating a new object views.py for saving new objects of contact model. def save_contact(request): if request.method == "POST": first_name = request.POST.get("fname") last_name = request.POST.get("lname") contact_name = request.POST.get("contact_name") title = request.POST.get("title") email = request.POST.get("email") phone = request.POST.get("phone") mobile = request.POST.get("mobile") assistant = request.POST.get("assistant") assistant_phone = request.POST.get("assistant_phone") department = request.POST.get("department") fax = request.POST.get("fax") date_of_birth = request.POST.get("date_of_birth") skype_id = request.POST.get("skype_id") twitter = request.POST.get("twitter_id") country = check(request.POST.get("country") state = request.POST.get("state") city = request.POST.get("city") street = request.POST.get("street") pin_code = request.POST.get("pin_code") description = request.POST.get("description") contact_obj = Contact(owner=request.user,first_name=first_name,last_name=last_name,account_name=contact_name,title=title,email=email,phone=phone,mobile=mobile,assistant=assistant,assistant_phone=assistant_phone,Department=department,fax=fax,date_of_birth=date_of_birth,skype_id=skype_id,twitter=twitter,country=country,state=state,city=city,street=street,pin_code=pin_code,description=description) try: Contact.save(self=contact_obj) except: messages.success(request,"Something went wrong! Try again") return redirect("crm_contacts") messages.success(request,"Your contact has been successfully saved") return redirect("crm_contacts") else: messages.success(request,"Something went wrong! Try again") return redirect("crm_contacts") Now the problem … -
How i like counter My code is below in django
I am working on a project which in i want make like counter but How i make Like Counter in django for below code i don't understand it can you help anyone please. in django.......................................................................................................................................................................................................... in template:. template.html <button type="button" class="btn-xs btn-info like btn-sm " id="{{i.id}}"> {% if i in liked_post %} <a href="{%url 'user_homeview:like_dislike_post'%}" style="color: white;" id="likebtn{{i.id}}">Liked</a></button> {% else %} <a href="{%url 'user_home-view:like_dislike_post'%}" style="color: white;" id="likebtn{{i.id}}">Like</a> </button> {% endif %} $(".like").click(function (e) { var id = this.id;//$(this).attr(.id); var href = $('.like').find('a').attr('href'); console.log(href, id) e.preventDefault(); $.ajax({ url: href, data: { 'likeId': id }, success: function (response) { if (response.liked) { $('#likebtn' + id).html("Liked") } else { $('#likebtn' + id).html("Like") } } }) }); in my models:. models.py ############################################################################################# class Post(models.Model): user =models.ForeignKey(User,on_delete=models.CASCADE) image =models.FileField(upload_to='post',blank=True) caption = models.CharField(max_length=200,default="") views = models.IntegerField(default=0) date =models.DateTimeField(auto_now_add=True,blank=True, null=True) def __str__(self): return str(self.user)+' '+ str(self.date.date()) ############################################################################################## class Like(models.Model): user = models.ManyToManyField(User,related_name="linkingUser") post = models.OneToOneField(Post,on_delete=models.CASCADE) @classmethod def like(cls,post,liking_user): obj,create= cls.objects.get_or_create(post=post) obj.user.add(liking_user) @classmethod def dislike(cls,post,disliking_user): obj,create= cls.objects.get_or_create(post=post) obj.user.remove(disliking_user) # @classmethod # def def __str__(self): return str(self.post) in my views views.py # Create your views here. def user_home(request): # messages.success(request,'login successfully') user = Following.objects.get(user=request.user) #following_obj of user followed_users = user.followed.all() posts = Post.objects.filter(user__in = followed_users).order_by('-pk') | Post.objects.filter(user = request.user).order_by('-pk') … -
Apache2 and Django - [wsgi:error] ImportError: cannot import name 'get_version'
I have set up a basic site in Django and am trying to serve it using Apache 2, however when trying i get an error: [Tue Jul 07 08:03:50.274206 2020] [mpm_event:notice] [pid 21614:tid 140492525521856] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Tue Jul 07 08:03:50.274292 2020] [core:notice] [pid 21614:tid 140492525521856] AH00094: Command line: '/usr/sbin/apache2' [Tue Jul 07 08:03:55.841352 2020] [wsgi:error] [pid 21616:tid 140492373808896] [remote myip:myport] mod_wsgi (pid=21616): Target WSGI script '/home/ubuntu/Django/customspiritco/wsgi.py' cannot be loaded as Python module. [Tue Jul 07 08:03:55.841401 2020] [wsgi:error] [pid 21616:tid 140492373808896] [remote myip:myport] mod_wsgi (pid=21616): Exception occurred processing WSGI script '/home/ubuntu/Django/customspiritco/wsgi.py'. [Tue Jul 07 08:03:55.841626 2020] [wsgi:error] [pid 21616:tid 140492373808896] [remote myip:myport] Traceback (most recent call last): [Tue Jul 07 08:03:55.841655 2020] [wsgi:error] [pid 21616:tid 140492373808896] [remote myip:myport] File "/home/ubuntu/Django/customspiritco/wsgi.py", line 3, in <module> [Tue Jul 07 08:03:55.841661 2020] [wsgi:error] [pid 21616:tid 140492373808896] [remote myip:myport] from django.core.wsgi import get_wsgi_application [Tue Jul 07 08:03:55.841669 2020] [wsgi:error] [pid 21616:tid 140492373808896] [remote myip:myport] File "/home/ubuntu/Django/env/lib/python3.6/site-packages/django/__init__.py", line 1, in <module> [Tue Jul 07 08:03:55.841745 2020] [wsgi:error] [pid 21616:tid 140492373808896] [remote myip:myport] from django.utils.version import get_version [Tue Jul 07 08:03:55.841768 2020] [wsgi:error] [pid 21616:tid 140492373808896] [remote myip:myport] ImportError: cannot import name 'get_version' My installed version are: Apache/2.4.29 … -
How to add Admin section in Django?
After designing home page of website, i want to create a admin section where i can add,update and delete product. -
Django: Unable to validate MultipleChoiceField
Problem I'm recieving some bizarre behaviour with my MultipleChoiceField. I'm able to see my list of entries from a CheckboxSelectMultiple widget in my request.POST, but when explicitly calling that parameter it returns only my first entry. The form also does not validate an I recieve the error: File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\forms\forms.py", line 185, in is_valid return self.is_bound and not self.errors File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\forms\forms.py", line 180, in errors self.full_clean() File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\forms\forms.py", line 383, in full_clean self._post_clean() File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\forms\models.py", line 398, in _post_clean self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude) File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\forms\models.py", line 60, in construct_instance f.save_form_data(instance, cleaned_data[f.name]) File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 853, in save_form_data setattr(instance, self.name, data) File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\db\models\fields\related_descriptors.py", line 211, in __set__ self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "['1', '2', '3']": "CanisterModel.test_cell" must be a "CellModel" instance. So if I print request.POST I get: <QueryDict: {'csrfmiddlewaretoken': ['9KwmPg1GzSXL98kjQbUHsvJGCIX3zNiBgqPbMPVtZtxYXKGnlZjreN9tDtDSdxiC'], 'test_cell': ['1', '2', '3'], 'canister_type': ['Total Hydrocarbons'], 'canister_change_date': ['07/07/2020'], 'time_field': ['12:30'], 'actual_conc': ['123']}> If I print request.POST['test_cell'] I get: '3' And if I print request.POST.getlist('test_cell') I get: ['1', '2', '3'] What I want I want validate the form without having to copy and manipulate the request.POST and simply pass it into the form and validate. Code Forms def queryset_to_choice(queryset): return [(x.id, x.__str__()) for x in queryset] class UpdateCanisterForm(forms.ModelForm): test_cell = … -
Django swagger "No operations defined in spec!" after using namespaceversioning
I'm implementing namespaceversioning for my application. Everything works fine, except swagger. I got following message (and no endpoints) on my swagger page: "No operations defined in spec!" I only added this to my project urls.py from backend.versioning import v2_urls as v2_urls urlpatterns = [ .... url(r"^v2/", include(v2_urls)), ] and that file looks like: from django.conf.urls import url from django.urls import include from backend.st_site import urls as site_urls urlpatterns = [ url(r"^sites/", include((site_urls, "sites"), namespace="v2")), ] I added this to my settings/base.py REST_FRAMEWORK = { .... "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.NamespaceVersioning", "DEFAULT_VERSION": "v1", } If anything else is useful, I will add it. -
NoReverseMatch at /wiki/CSS Reverse for 'edit_pagina' with no arguments not found. 1 pattern(s) tried: ['edit/(?P<editPage>[^/]+)$']
i have tried to put an edit button on the wiki page but it give me this error: NoReverseMatch at /wiki/CSS Reverse for 'edit_pagina' with no arguments not found. 1 pattern(s) tried: ['edit/(?P[^/]+)$'] urls.py: app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:page>", views.wiki_page, name="wiki_page"), path("create", views.add_entry, name="add_entry"), path("search", views.search, name="search"), path("edit/<str:editPage>", views.edit_page, name="edit_page") ] views.py: def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None def edit_page(request, editPage): content = util.get_entry(editPage) return render(request, "encyclopedia/edit.html", { "page_title": editPage, "content": content }) edit.html: {% extends "encyclopedia/layout.html" %} {% block title %} {{ page_title }} {% endblock %} {% block body %} <form action="{% url 'edit_page' %}" method="POST"> {% csrf_token %} <h1>Edit Page</h1> <textarea name="edit-content" id="textarea-content">{{ content }}</textarea> <button class="btn btn-primary" id="save-edit" type="submit">save changes</button> </form> {% endblock %} thank you in advanced -
Upload Multiple files in Django 3
I am new to pyhthon\Django and would like to get my Django 3 app to have the ability to upload multiple files but I am struggling to get this functionality, below is my sample code which uploads a single file, I beleive I need to enable multiple files in the forms.py and then override the post method to deal with multiple files. As I bonus I would also like to use a field name from the form in the file path when it is saved. (Pyhton 3.8/Django 3) thanks Model.py class Predocs(models.Model): doc_files = models.FileField(blank=True) Form.py from .models import Predocs class PostForm(forms.ModelForm): class Meta: model = Predocs fields = ['doc_files'] View.py from django.shortcuts import render, redirect # Create your views here. from .forms import PostForm from PredocsForm.models import Predocs def create(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): # save form form.save() data = "test data" return render(request, 'preform/created.html', { 'data': data }) else: form = PostForm() return render(request, 'preform/create.html', { 'form': form }) def created(request): return render(request, 'preform/created.html') -
CSRF verification failed. Using Python Django backend and React, Axios(using POST) frontend
I am following this tutorial https://www.valentinog.com/blog/drf/ and succesfully finished it. I am trying to add a POST functionality to this tutorial. The thing is I am having trouble adding the POST command to send a csrf value using the Axios ajax framework. I have obtained the csrf on the cookies, and stored it in "csrfmiddlewaretoken" variable followed by a test message embedded in a json format to the axios function but it doesn't work resulting in a 403 error. I added @ensure_csrf_cookie decorator to the views.py but still the same error. Using the @csrf_exempt decorator on views.py solves this however I want to use csrf for security. csrftoken.js import React from "react"; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== "") { var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie("csrftoken"); const CSRFToken = () => { return <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} />; }; export default CSRFToken; App.js ... import axios from "axios"; import CSRFToken from "./csrftoken"; ... sendPost() { var … -
Django .config files or .env files usage?
I am working on Django as backend. I want to make use of configuration files to update some variable values of my code in future, so that I do not have to modify them through the code everytime. Is there a way to do this? -
How can I make a search work in django-admin with a choice field?
I'm using django-admin to manage my db models, and I want to add a search field to it as below: dashboard_table_type_choices = [(1, "normal"), (2, "risk")] # model class MDashBoard(BasicModel): dashboard_name = models.CharField(max_length=255, null=False) dashboard_type = models.SmallIntegerField(choices=dashboard_table_type_choices, verbose_name='type_of_dashboard') owner = models.ForeignKey( MUser, related_name='dashboards', on_delete=models.PROTECT, verbose_name='the_owner', null=False ) class Meta: verbose_name = 'dashboard' db_table = 'dashboard' ordering = ['-updated_time', '-created_time', '-id'] def __str__(self): return f"{self.dashboard_name}({self.id})" \ f"({self.get_dashboard_type_display()})" # admin class DashBoardAdmin(admin.ModelAdmin): list_display = ('dashboard_name','dashboard_type','owner') search_fields = ('dashboard_name', 'dashboard_type', 'owner__user_name') # dashboard_type didn't work here # I put risk to serch for example list_filter = ('dashboard_type',) But it doesn't work if i input a dashboard_type string in, how can I make it work? -
retrieve a coupon in stripe using python
I'm working on a project to create a subscription function for our products. I'm creating a function to check if the coupon code entered by the user matches the coupon.id in stripe if it does then it should store it in session else it should display "incorrect code" message. My code seems to be incorrect and is not working. Please help !!! views.py def retrieve_coupon(request): if request.method == 'POST': form = CouponApplyForm(request.POST) if form.is_valid(): code = form.cleaned_data['code'] try: coupon_id = stripe.Coupon.retrieve(code) request.session['coupon'] = code except coupon.DoesNotExist: messages.info(request, "This coupon does not exist") request.session['coupon'] = None context={ 'form':form } return render(request, "retrieve_coupon.html", context) forms.py class CouponApplyForm(forms.Form): code = forms.CharField() template <div class="divo"> <p> coupon code to apply discount </p> <form action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="apply" class="btn"> <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> </form> </div>