Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I expose Wagtail search in a Django Graphene query?
Given the general structure: class Article(Page): body = RichTextField(...) search_fields = Page.search_fields + [index.SearchField('body')] class ArticleFilter(FilterSet): search = SearchFilter() class Meta: model = Article fields = ['slug'] class Query(ObjectType): articles = DjangoFilterConnectionField(ArticleNode, filterset_class=ArticleFilter) I thought to create a "SearchFilter" to expose the wagtail search functionality, since I ultimately want to perform full text search via graphql like so: query { articles (search: "some text in a page") { edges { nodes { slug } } } } "search" is not a field on the Django model which is why I created a custom field in the Django FilterSet. My thought was to do something like: class SearchFilter(CharFilter): def filter(self, qs, value): s = get_search_backend() return s.search(value, Article) # not sure how to get the model? The search returns a DatabaseSearchResults instance rather than a QuerySet so the endpoint fails. Obviously one way to get this to work would be something like: return qs.filter(pk__in=[r.pk for r in s.search(value, Article)]) however, I'm curious if there's a better pattern that's more efficient. Should the "search" be moved outside of the FilterSet and into the Query/Node/custom connection, and if so, how can I add an additional field to "articles" to see it as the … -
View variables not interpreted as variable
Some variables seem to not be interpreted as variables but as string I'm starting on Django and am following a tutorial in which I came across this piece of code : In template : <ul> {% for key, value in couleurs.items %} <li style="color:# {{ key }} ">{{ value }}</li> {% endfor %} </ul> I should add that in my code editor (VSC) the " "color:# {{ key }} " " part is in a different color then the rest In view : def rainbow(request): couleurs = { 'FF0000':'rouge', 'ED7F10':'orange', 'FFFF00':'jaune', '00FF00':'vert', '0000FF':'bleu', '4B0082':'indigo', '660099':'violet', } return render(request, 'blog/rainbow.html', locals()) The errors displayed are in the 3rd line of the template : _The error displayed when I hover my mouse over the # is "property value expected" _And the one for } is "at-rule or selector expected" The code should print the colors in color (ex : red in red etc...) Thanks in advance ! English not first language btw so sorry if I misspelled stuff -
In django user model , i want to add contact ,username and role fields
I have created AbstractBaseUser in my Models.py , and i am able to create email,password,first_name and Last_name. I want contact,username and Role as well in the same User Model. Can anyone help me? -
Displaying comments for questions only when they exist
I need to display messages on a Django template. Each message can have 0 to many comments. I need to display the comments for each message. However, if a message has no comments, then it is 'None' and I can't iterate over it. The problem is occurring in Django templates. #models.py class User(models.Model): firstName = models.CharField(max_length = 255) lastName = models.CharField(max_length = 255) email = models.CharField(max_length = 255) birthDate = models.DateField() password = models.CharField(max_length = 255) createdAt = models.DateTimeField(auto_now_add = True) updatedAt = models.DateTimeField(auto_now = True) objects = UserManager() class Message(models.Model): content = models.TextField() user = models.ForeignKey(User, related_name = "messages") createdAt = models.DateTimeField(auto_now_add = True) updatedAt = models.DateTimeField(auto_now = True) objects = UserManager() class Comment(models.Model): content = models.TextField() message = models.ForeignKey(Message, related_name = "comments", default = []) createdAt = models.DateTimeField(auto_now_add = True) updatedAt = models.DateTimeField(auto_now = True) objects = UserManager() #views.py #Main wall page #Renders wall.html def wall(request): wallDict = { "message" : Message.objects.all() } return render(request, "loginRegApp/wall.html", wallDict) #wall.html <!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="utf-8"> </head> <body> <div class="container"> <a href="/logout">Log out</a> <form action="message/create" method="post"> {% csrf_token %} <h4>Post a message</h4> <textarea name="message"></textarea> <input type="submit" value="Post a message"> </form> {% for message in messages %} <div> <h6>{{message.user.firstName}} … -
Django Post Signal on some remote DB
I have two different projects Project1 settings default - project 1 database db2 - project 2 database project2 settings default - project 2 database What I did to use serializers, models of project 2, etc in project 1 . I copied the complete app from project 2 to project 1 and registered the model in settings.py and also removed the migrations folder so that any time I makemigrations in project 1 shell it does not create any migrations for project 2 apps in (project 1 and thus migrating wont add any models of project 2 in project 1 ). Now the problem I am facing is I have to use post_save signal on model of project 2 app that I imported in project 1. and get notified in project1 @receiver(post_save, sender=Project2Model) def project2model_save_hook(sender, instance, created, **kwargs): print(created) this will work only when this signal is present in project 2 but not in project 1. In project 1 this is never called when object is created in default db of project 2 or db2 of project 1 How should I proceed? -
Why doesn't js script work at django web-site?
I'm new in Django and JS. Trying to create HTML5 audioplayer with custom controls. When I start page nothing happens. Tested this mp3 with default player and everything is ok. So I think static settings is correct. Folders structure: -stream (the app) - ... - static - stream - audio - test.mp3 - scripts - player.js - templates - ... - index.html This is my index.html. The base template is almost empty. {% extends "base_generic.html" %} {% block content %} {% load static %} <script src="{% static "stream/scripts/player.js" %}" type="text/javascript"></script> <audio src="{% static "stream/audio/test.mp3" %}" type="audio/mpeg"> {% endblock %} And this is my player.js var aud = $('audio')[0]; aud.play(); I expect that when I open the page the music will start playing. -
How to solve the problem of attribute error in django?
I am trying to make the search bar work. Whenever I type something in views.py, it should be appeared and others shouldn't. I have written code which I will show but when I run the code, it gives me attribute error type object 'Destination' has no attribute 'filter'. How to solve this problem? index.html <form class="love" method="GET" action=""> <input type="text" placeholder='Search..' name="srh" value="{{request.GET.srh}}"> <br> <button type="submit" class="btn btn-danger"> Search </button> </form> views.py from django.shortcuts import render from . models import Destination from django.db.models import Q def index(request): query = request.GET.get('srh') if query: match = Destination.filter( Q(desc_icontains=query)).distinct() target1 = a, b= [Destination() for __ in range(2)] a.img = 'Article.jpg' b.img = 'Micro Tasks.jpeg' a.desc = 'Article Writing' b.desc = 'Micro Tasks' app url from . import views urlpatterns = [path('', views.index, name='index')] main url from django.contrib import admin from django.urls import path, include from firstapp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', include('firstapp.urls'))] -
I am new to django. How to resolve the csrf token missing or incorrect error? I have used render request in views
403 forbidden. CSRF token missing or incorrect. I have already tried from django.views.decorators.csrf import csrf_protect, it doesn't work. I have not used render_to_request either. -
Django-Rest-Framework: Make A PUT Request to API
So I want to make a put request to change the content of a message in my chat/messaging app. class MessageView(viewsets.ModelViewSet): http_method_names = ['get', 'post', 'put', 'delete', 'patch'] queryset = Message.objects.all() serializer_class = MessageSerializer filter_backends = ( django_filters.rest_framework.DjangoFilterBackend, rest_framework.filters.OrderingFilter, ) filter_fields = ['room'] class UserMessageView(MessageView): def get_queryset(self): return Message.objects.filter(canview__user=self.request.user) #get def get(self, request): hello_param = request.GET["helloParam"] #post def post(self, request): hello_param = request.POST["helloParam"] #put def put(self, request): hello_param = request.PUT["helloParam"] #patch def patch(self, request): hello_param = request.PATCH["helloParam"] #delete def delete(self, request): hello_param = request.DELETE["helloParam"] This is the error I get: 'Request' object has no attribute 'PUT' - If You have any idea how to fix this please respond! :) Thank you! -
I am trying to import gensim, pandas and numpy in my django project but getting import error
I am getting an import error as i try to import gensim, pandas and numpy in django views. How can I import them. I have installed the libraries in virtual environment. -
Conditional Form Field in Django wizard form
I am using wizard forms in django. I want to create a form field only if answer to some other form field is marked "yes" otherwise I don't want this new form field. How can I do this ? I have tried some other answers but most of them tells about how to mark field required or not but I want to display that field only if answer to other field is "Yes" Django Form Wizard with Conditional Questions In below code I want to display field "Pool2" only if answer to field "Pool" is marked "yes" otherwise I don't want that field. forms.py class ListingForm2(forms.Form): Pool = ( ("Yes","Yes"), ("No","No"), ) Pool = forms.ChoiceField(choices = Pool,label = "Does your property have a pool ?") Pool2 = forms.CharField(required=False) Views.py class ListingWizard(SessionWizardView): template_name = 'listing_form.html' form_list = [ListingForm1,ListingForm2,ListingForm3,ListingForm4] def done(self, form_list, **kwargs): save_data(form.cleaned_data for form in form_list) return render(self.request,'done.html',{ 'form_data' : [form.cleaned_data for form in form_list], }) -
django group by match
I want to group by match name i sorted by rank however i failed to group by match. What should you suggest to me [It looks like your post is mostly code; please add some more details.] [It looks like your post is mostly code; please add some more details.] [It looks like your post is mostly code; please add some more details.] (sorry for spam) Now my list; I want like this; html <!-- TABLE --> <div class="table standings"> <!-- TABLE ROW HEADER --> <div class="table-row-header"> <!-- TABLE ROW HEADER ITEM --> <div class="table-row-header-item position"> <p class="table-row-header-title">{{ team.broyale_match.name }}</p> </div> <!-- /TABLE ROW HEADER ITEM --> <div class="table-row-header-item padded"> <p class="table-row-header-title">Maç</p> </div> <div class="table-row-header-item padded"> <p class="table-row-header-title">Sırası</p> </div> </div> <!-- /TABLE ROW HEADER --> {% for team in teams %} <!-- TABLE ROWS --> <div class="table-rows"> <!-- TABLE ROW --> <div class="table-row"> <!-- TABLE ROW ITEM --> <div class="table-row-item position"> <!-- TABLE TEXT --> <p class="table-text">{{ forloop.counter }}</p> <!-- /TABLE TEXT --> <!-- TEAM INFO WRAP --> <div class="team-info-wrap"> <!-- TEAM LOGO --> <img class="team-logo small" src="{% static 'img/flags/' %}{{ team.team.country_code }}.svg" alt="{{ team.team.country_code }}"> <!-- /TEAM LOGO --> <!-- TEAM INFO --> <div class="team-info"> <p class="team-name">{{ team.team.name }}</p> … -
Django Rest Framework Assertion Error: Missing Meta.model attribute
I am trying to implement Rest api using Django framework. But when I click on the url on the default index page it gives me an assertion error at/languages/ Class LanguageSerializer missing meta.model attribute I made all the migrations after changes in models.py but it did nothing urls.py from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('languages', views.LanguageView) urlpatterns = [ path('', include(router.urls)) ] models.py from django.db import models class Language(models.Model): name = models.CharField(max_length=50) paradigm = models.CharField(max_length=50) serializers.py from rest_framework import serializers from .models import Language class LanguageSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'name', 'paradigm') views.py from django.shortcuts import render from rest_framework import viewsets from .models import Language from .serializers import LanguageSerializer class LanguageView(viewsets.ModelViewSet): queryset = Language.objects.all() serializer_class = LanguageSerializer I have no clue where am I going wrong -
Why the first row of grid is not showing properly?
I'm trying to achieve infinite-scroll using waypoint and django on backend. <div class="discover_feed infinite-container" style="background-color:transparent;padding-bottom:50px;"> {% for m in result %} <div class="example lazyframe infinite-item" style="margin-left:2%;" > <a class="IfFrrameContainer"href="/p/{{m.id}}"> {% for c in m.postimage_set.all %} {% if forloop.first %} <img src="{{ c.Image.url }}" class="lazy"/> {% endif %} {% endfor %}</a> </div> {% endfor %} </div> {% if result.has_next %}<div><a class="infinite-more-link" href="?page={{ result.next_page_number }}"> </a></div>{% endif %} <script type="text/javascript"> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onAfterPageLoad: function ($items) { $items.each(function() { }); }, onBeforePageLoad:function(){ } }); </script> as you can see, everytime styling does not work for first(or probabaly second) element of the grid. -
Django save with update_fields and POSTGRESQL MVCC
(Sorry for my english it's not my native language) I search on internet but I don't find informations about that, if I look at Heroku Devcenter I have this information: url: https://devcenter.heroku.com/articles/postgresql-concurrency#disadvantages-of-mvcc "This is why an UPDATE actually creates a new row", so if Postgresql actually creates a new row for each update, does it make any sense to use update_fields to increase performance? I will in a few days create a little benchmark to test if there is any performance improvement in using update_fields. -
what is causing this error : invalid literal for int() with base 10
Hello I'm developing a simple posts app using Django I have to models user and post model i'm to get all posts sent to a specific user I got this error message while trying to get the posts invalid literal for int() with base 10: 'user1' these are the models user model email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False)</pre> <b>post model</b> ```python class Post(models.Model): # post structure user = models.CharField(max_length=20, blank=True, default="Anonymous") # sender content = models.TextField(blank=False) date = models.DateTimeField(auto_now_add=True) toUser = models.ForeignKey(MyUser, null=False, on_delete=models.CASCADE) post_id = models.AutoField(primary_key=True)</pre> I'm getting the username variable sent in the URL in this view and trying to get all posts sent to this username def user_posts(request, username): posts = Post.objects.get(toUser=username) return render(request=request, template_name='post/user.html', context={'posts', posts}) -
Delivering Mass Notifications and Messages on a Subscription Model
I am trying to implement a subscription model. If one creator takes an action, subscribers of the creator should receive notifications. I made my model like this: class Notification(models.Model): created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(default=timezone.now, db_index=True) creator = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE, related_name='notification_creator') receiver = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE, related_name='notification_receiver') post = models.OneToOneField(forum_models.Post, null=True, on_delete=models.CASCADE, related_name='notification') comment = models.OneToOneField(forum_models.Comment, null=True, on_delete=models.CASCADE, related_name='notification') channels = models.ManyToManyField(forum_models.Channel, related_name='notifications') class Meta: ordering = ['-updated_date', '-id'] It is okay for making a simple notification from a creator to a receiver where a post or a comment is created. However, when I want to notify all the receivers who subscribe creator's channel, there is a problem. I have to create one notification for each receiver every time creator does something. That is what I found from django-notification. I concluded that is a very inefficient way to deliver notifications, so I made another model. class NotificationListner(models.Model): receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='notification_listners_receiver') channel = models.ForeignKey(forum_models.Channel, null=True, on_delete=models.CASCADE, related_name='notification_listners') following = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE, related_name='notification_listeners') notify = models.BooleanField(default=False) A notification listener is created for each receiver for subscribing a channel or a following person. And I query like this: def resolve_notifications(self, info, **kwargs): return models.Notification.objects.filter( Q(Q(channels__notification_listners__receiver=info.context.user) & Q(post__is_null=False) & Q(notify=True)) … -
Unresolved import views in urls.py warning BUT app working
from blog import views (blog beeing my app) prints an unresolved import warning yet the app works properly So I'm just starting at Django and in the tutorial i'm following it is sais that in urls i have to import views wich I did : from blog import views It works, the website displays as intended and even Django prints : "System check identified no issues (0 silenced)." the only problem is that VSC underlines it as an error (the import and everytime I reference views) making it harder to see properly . I looked similar issues on the internet and it seems like what I wrote (from the tutorial) is correct so I have no idea what to do now ... from blog import views urlpatterns=[... path('acceuil', views.home), ] PS : English is not my first language so sorry if there are mistakes :) -
Pylint Django model instance of 'str' has no member
I am using pylint-django for my Django project and one of my models is as follows: class Registration(models.Model): date_added = models.DateTimeField(auto_now_add=True) event = models.ForeignKey(Event, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): first_name = self.user.first_name last_name = self.user.last_name return f'{first_name} {last_name}' Running pylint, I am getting the following warnings: events/models.py:61:21: E1101: Instance of 'str' has no 'first_name' member (no-member) From the readme of pylint-django I understand this is a known issue: "If you reference foreign-key models by their name (as string) pylint-django may not be able to find the model and will report issues because it has no idea what the underlying type of this field is." My question is: what should I do to deal with this? I prefer not to suppress all C0111 warnings. Thank you so much in advance for your help! PS: I am using pylint-django as answered on Using Pylint with Django -
I want to pre-populate a form with a foreign key. I click an add link against supplier and add a review without retyping the supplier
I want to click a link next to the supplier and add a review. I should not be required to retype or select the supplier but just enter review details. However I get an error of MultiValueDictKeyError 'supplier.pk'. The error occurs in the get_initial method and specifically supplier.pk. The form is not opened in this case the title bare shows /review/add/2/ which implies that the supplier id 2 is available I also tried this code which opened the form (has other review fields but not supplier field). I got the error KeyError at /comment/add/5/ 'supplier' ''' I got the error KeyError at /comment/add/5/ 'supplier' with code below ''' class CreateReview(FormView): form_class = AddReviewForm template_name = 'comment_new.html' success_url = reverse_lazy ('supplier_reviews') def form_valid(self, form): supplier = get_object_or_404(Supplier, slug=self.kwargs['supplier']) form.instance.supplier = supplier return super(CreateReview,self).form_valid(form) The link below starts of the process Add a review code of my models and view are provided below class Supplier(models.Model): """Model representing suppliers.""" contact_name = models.CharField(max_length=50) company_name = models.CharField(max_length=100) contact_n01 = models.CharField(max_length=15) contact_n02 = models.CharField(max_length=15) class Review(models.Model): """Model representing members.""" date = models.DateField() comment = models.TextField(max_length=1000) score = models.IntegerField() supplier = models.ForeignKey(Supplier, on_delete=models.SET_NULL, null=True) class CreateReview(FormView): form_class = AddReviewForm template_name = 'comment_new.html' success_url = reverse_lazy ('supplier_details') def … -
Django standings with "through" keyword
I want to sort Teams with rank. However, i failed. First of all, i create a match with lots of teams and then i rate these teams. finally, connect the matches with the game object. (because a game can have 2-3 rounds every round is a match) (don't have any error. Just not come data) [ i want like this] team_name rank xxx 1 xxx 2 xxy 3 views.py game=get_object_or_404(BroyaleGame, tournament__slug=tournamentslug, slug=slug, game__slug=gameslug,) teams=Team.objects.filter( broyalematchteam__broyale_match__broyalegame=game ).annotate( points=F('broyalematchteam__rank') ).order_by( '-rank' ) models.py class BroyaleMatchTeam(models.Model): broyale_match = models.ForeignKey('BroyaleMatch', on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) rank = models.IntegerField(default=40) def __str__(self): return self.broyale_match.name class Meta: verbose_name_plural='Battle Royale Takım vs Takım Rank/Puan' class BroyaleMatch(Match): teams=models.ManyToManyField(Team,through='BroyaleMatchTeam') class Meta: ordering=('-name',) verbose_name='Battle Royale Takım vs Takım Maç' verbose_name_plural='Battle Royale Takım vs Takım Maç' class BroyaleGame(Game): match=models.ManyToManyField(BroyaleMatch) tournament=models.ForeignKey('BroyaleTournament',on_delete=models.CASCADE) -
Django : Stop calling same view if its alredy called
I have a view, and when user click on a button it gets called. But If a user click the button twice it gets called for another even if the first is still executing or running. This produces a problem(if I am correct), and that is : It stops execution for the first one and starts executing for the other. Please Help me so that i can stop this calling of views twice. -
Reverse for 'ques_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['ques_detail/(?P<pk>[0-9]+)/$']
I am getting the following error: Reverse for 'ques_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['ques_detail/(?P[0-9]+)/$'] Does anyone know how to solve it? I tried solutions posted on many sites but nothing worked. Someone kindly help. urls.py from django.urls import path from . import views urlpatterns = [ path('logout', views.logout, name='test_logout'), path('register', views.register, name = 'register'), path('', views.welcome, name='welcome'), path('instructions', views.instructions, name = 'instructions'), path('ques_detail/<int:pk>/',views.ques_detail,name='ques_detail') ] views.py def ques_detail(request, pk): ques = get_object_or_404(Questionm, pk=pk) return render(request, 'events/ques_detail.html', {'ques': ques}) instructions.html {% extends 'base.html' %} {% block content %} <div class="register"> <h1>Instructions</h1> </div> <br><br><hr><hr> <ul class="list-group"> <li class="list-group-item">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.</li> <li class="list-group-item">Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.</li> <li class="list-group-item">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum.</li> <li class="list-group-item">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt.</li> <li class="list-group-item">Massa placerat duis ultricies lacus.</li> <li class="list-group-item">Mattis rhoncus urna neque viverra justo nec ultrices dui sapien. </li> <li class="list-group-item">Sit amet facilisis magna etiam tempor orci eu. </li> <li class="list-group-item">Condimentum mattis pellentesque id nibh tortor id aliquet.</li> <li class="list-group-item">Sit amet commodo nulla facilisi nullam vehicula ipsum a arcu.</li> <li class="list-group-item">Vulputate eu scelerisque … -
How to create custom UserCreationForm and UserChangeForm for CustomUser for admin page?
How to create custom UserChangeForm and UserCreationForm for CustomUser for admin page? my models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), unique=True, blank=True, null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(_('phone number'), validators=[phone_regex], max_length=17, unique=True, blank=True, null=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] -
Can't save a list of numbers to models using api
im trying to create a list from 1 to 9 using the shell so the user can pick the number of tickets that he can book shell Passenger = list(range(1,10)) Passenger.save() Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute 'save' #Models.py class Ticket(models.Model): GENDER = ( ('m', 'Male'), ('f', 'Female'), ) trip = models.ForeignKey(Trip, related_name="tickets", null=True, on_delete=models.CASCADE) booking_time = models.DateTimeField(auto_now_add=True, blank=True) first_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False) middle_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False) last_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False) email = models.EmailField(max_length=70,blank=True, null= True) gender = models.CharField(max_length=1, choices=GENDER) def __str__(self): return "{}".format(self.first_name) #Views.py def trips_page(request, trip_id): trip = get_object_or_404( Trip,pk=trip_id) error = None ticket = None if request.method == 'POST': first_name = request.POST.get('first_name') middle_name = request.POST.get('middle_name') last_name = request.POST.get('last_name') email = request.POST.get('email') gender = request.POST.get('gender') ticket = Ticket(trip=trip,first_name=first_name, middle_name=middle_name, last_name=last_name, email=email,gender=gender) try: ticket.full_clean() ticket.save() return redirect('tickets',ticket_id=ticket.id) except ValidationError as e: error = dict(e) print(e) context = {'trip' : trip, 'error':error, 'ticket':ticket } return render(request, 'details/trips.html', context)