Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: To combine and retrieve rows from different models
1.We have two similar models, and I would like to be able to retrieve these at the same time and sort them by posting date and time, etc. Is it possible? 2.Or should both redundant fields be combined into one model? # 1. class Model1(models.Model): title = ... thumbnail = ... description = ... ... class Model2(models.Model): title = ... image_url = ... product_id = ... reivew = ... # 2. Combine into one model class Model(models.Model) title = ... thumbnail = ... description = ... image_url = ... product_id = ... reivew = ... -
Filter rows from Excel on import with Django Import-Export
I have a new Django web-application (My first one in python) and im using Import-export in the admin section to take an excel file and upload it to my database.the upload works perfectly, but I need to add two features: Is there a way to truncate all the existing data in the application database table before the upload? What is the best way to filter out rows from the Excel file that don't match a condition (if column value of a row != X) I have read the documentation and it seems like for question 2, the only option is to implement an for_delete method. I find it hard to believe this is the best way, but im brand new to python and Django. -
MultipleObjectsReturned at /sport/1/ get() returned more than one Product -- it returned 3
I am sorting products by categories. When I am viewing product's details, the program outputs following error: MultipleObjectsReturned at /default/1/ get() returned more than one Product -- it returned 2! Users/artemiikhristich/PycharmProjects/Eshop-original/store/views.py, line 114, in product_detail product = get_object_or_404(Product, slug=slug) product.html This template is used for viewing product details % extends "store/main.html" %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Tutorial</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet"> <!-- CSS --> <link href="static/css/style.css" rel="stylesheet"> <meta name="robots" content="noindex,follow" /> </head> <body> <main class="container"> <!-- Left Column / Headphones Image --> <!-- Right Column --> <div class="right-column"> <!-- Product Description --> <div class="product-description"> <span></span> <h1>{{product.name}}</h1> <div class="left-column"> <img data-image="black" src="{{ product.imageURL }}"> </div> <p>"{{product.description}}"</p> </div> <!-- Product Configuration --> </div> <!-- Product Pricing --> <div class="product-price"> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <div class="product-configuration"> <a href="#">How to take the measurements</a> </div> </div> </div> </main> <!-- Scripts --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" charset="utf-8"></script> <script src="static/js/script.js" charset="utf-8"></script> </body> </html> {% endblock %} views.py Here I have views for product_detail and category_detail class ProductList(ListView): model = Product def product_detail(request, category_slug, slug): product = get_object_or_404(Product, slug=slug) context = … -
Django back end and Wix front end
I have been working on a project for a while with a developer on apps. He was the coder and did most of the programming. I really just brought the design together and managed everything else. He has now moved on and left me with the code. Or more to the point I have a Django database on a server. Using a postgre db with all of the data in I have built easy websites using things like Wix and wordpress. But I am wondering is there a simple way to migrate the data to my new front end. I can keep the digital ocean droplet or move everything to Wix. If possible just a quick way to do it. The dB contains images, video and text. I am not too fussed right now about making a super duper website. The layout and simplicity to build a Wix site is fine for me. Any ideas. Is this something I can learn? Or should I just get a pro in? -
How to filter a model in case of too complicated database structure?
I want to make a flexible online shop which will allow it's admins to create products and add custom product fields without need to program. I did it, but the final database structure is so complicated that I can't figure out how to filter it. Let's say there are categories with some products attached to it. Each category has only one unique template, the template holds custom fields names and types(int, char). When a product is created, the corresponding template-like fields are written to another model that holds custom fields names and values. So, how to filter the product model considering its custom fields values? To clarify, let's say someone created smartphones category, created template with fields "Brand" and "Screen size", added some smartphones and wants to filter phones with brand="Apple" and screen size > 4.5 inches. I hope that makes sense ^_^ Database structure: class Category(models.Model): name = models.CharField(max_length=63) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=63) price = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(1073741823)], null=True, blank=True) #Template class CategoryTemplate(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=255, null=True, blank=True) #Model that holds template custom fields class TemplateField(models.Model): template = models.ForeignKey(CategoryTemplate, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True, blank=True) is_integer = models.BooleanField(blank=True, default=False) #Values … -
Django Admin show same database name when i am using custome user class
I am creating a custom user class and then I am inheritance this user class to another two classes called Customer and Agent. from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.deletion import CASCADE class User(AbstractUser): username = models.CharField(max_length=50, blank=False, null=False, unique=True) email = models.EmailField(('email address'), blank=False, null=False, unique=True) phone_no = models.CharField(max_length=10) isAgent = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'phone_no'] def __str__(self): return self.username class Customer(User): pass class Agent(User): company_name = models.CharField(max_length=150, default="", null=False, blank=False) company_desc = models.CharField(max_length=1000, default="") and then i am register this model class in admin pannel like this... from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Customer, User, Agent, Destination, Trip, Payment admin.site.register(User, UserAdmin) @admin.register(Customer) class CustomerAdmin(admin.ModelAdmin): list_display = ['username', 'email'] @admin.register(Agent) class AgentAdmin(admin.ModelAdmin): list_display = ['username', 'email', 'company_name'] NOTE : I am also create a model classes like Destination,Trip,Payment just ignore this class... but in my adminsite http://127.0.0.1:8000/admin/ it is how like this... https://i.stack.imgur.com/D8sX3.png ==> user class name as "User" , Customer class name as "User" as well as Agent class name as "User" soo why my orignal model class name is not occure..? -
Can we convert django application views to django restframework views just like 2to3 python library?
I have a application which is built in django 1.11 with templates. I want to convert that application views in django-rest-framework views, Is there any way we can do it easily or i have to rewrite all django views to django-rest-framework views -
Django DecimalField form field errors not shown in template
I have a silly problem. I have a decimal field with 1 decimal place allowed. I need to manually iterate over the form fields in the template and render them. If in the template I set the input to type="text" and enter a number with two decimal places in the form the error message ("Ensure that there are no more than 1 decimal place.") is displayed in the template. However, when I set the input to type="number" and step="0.1", then the error is not displayed in the template. I can just set it as text, but that means users can enter any characters. I prefer not to do that and have it as a type="number" so that they can only enter digits. Any help would be appreciated. Minimal code: # forms.py class TimeForm(forms.Form): time = forms.DecimalField(max_digits=3, decimal_places=1, label = 'Time') # template <form method="POST"> {% csrf_token %} <div> <input type="number" step="0.1" class="form-control {% if form.time.errors %} is-invalid {% endif %}" name="{{form.time.name}}" id="{{ form.time.id_for_label }}" {% if form.time.value %} value="{{form.time.value}}" {% else %} placeholder="Total Time" {% endif %}> {% if form.time.errors %} {% for error in form.time.errors %} <span class="invalid-feedback">{{error}}</span> {% endfor %} {% endif %} </div> <button type="submit" class="btn btn-primary">Submit</button> … -
ModelChoiceField: Select a valid choice. That is not one of the available choices. Only when answer is wrong
I have a ModelChoice Field that contains 4 vocabulary words' definitions as the options for "what is the definition of __". When you submit the form I get: "Select a valid choice. That choice is not one of the available choices", but this only happens if the answer selected is wrong. Otherwise, it works fine. Forms.py class Questions(forms.Form): choice = forms.ModelChoiceField( widget=forms.RadioSelect, queryset=QuesModel.objects.all(), to_field_name='display', initial = 0 ) Models.py class QuesModel(models.Model): display = models.CharField(max_length=200,null=True) def __str__(self): return self.display views.py deck = Word.objects.all() deck_list = list(Word.objects.all()) cards = deck.filter(xdef = 0) options = [] options.append(cards[0]) random.shuffle(deck_list) options.extend([deck_list[1], deck_list[2], deck_list[3]]) [enter image description here][1]random.shuffle(options) QuesModel.objects.filter(id = 1).update(display = 'adjective') QuesModel.objects.filter(id = 2).update(display = 'noun') QuesModel.objects.filter(id = 3).update(display = 'verb') QuesModel.objects.filter(id = 4).update(display = 'adverb') q = "What part of speech is " + cards[0].name + "?" if request.method == "POST": form = Questions(request.POST) if form.is_valid(): i = form.cleaned_data.get('choice') #is object input = i.display answer = cards[0].pos print(input) print(answer) if (input == answer): print('correct') print('updating: ' + cards[0].name) Word.objects.filter(name = cards[0].name).update(xpos = 1) messages.info(request, answer + " is correct!") return redirect("learn") else: print('wrong') print('updating: ' + cards[0].name) Word.objects.filter(name = cards[0].name).update(xpos = 2) messages.info(request, "The correct answer was: " + answer) return redirect("learn") else: … -
How to save user certain user data into the session?
Scenario: User clicks a link on some forum or ad and he lands on any page of our website. I have to store that landing page url and timestamp when he landed in session. User can then browse the site ( unregistered ) - and then he might decide to sign up - and we want that information stored. The question is how to make it so that the data is written to the session, regardless of the page the user went to -
send message to Django admin from save method
I want to write function in Django models when save object sends a message to Django admin panel I tried to use 'django.contrib.meseseges' but it needs a request and I cant give request to func! what can I do?! def my_func(self) if my_condition == false: messages.warning(request= ??? ,"my message") def save(self,*args,**kwargs): self.my_func() super().save() -
CustomUserModel has no user_doctors
I have a detail page of clinical operation. And i want to make it accessible for only staff's and doctor's related with this operation with ManyToManyField For do this i did class OperationPanelView(LoginRequiredMixin,View): login_url = reverse_lazy("doctor:login") def get(self,request,id): operation = OperationModel.objects.get(id=id) if request.user.user_doctors not in operation.doctor.all(): if DoctorModel.objects.filter(user = request.user).exists(): return redirect("doctor:panel",request.user.id) elif request.user.is_staff == True: return redirect("disease:panel",operation.id) context = { "operation":operation, } return render(request,"operation_detail.html",context) this has worked for if request.user.user_doctors is not related with this operation's doctors then it will redirects the user to their own panel. And also has worked for if request.user.user_doctors is related with operation's doctors then page will open. But didn't worked for if user is staff and gave this error: RelatedObjectDoesNotExist at /disease/panel/1 CustomUserModel has no user_doctors. in line 35: if request.user.user_doctors not in operation.doctor.all(): Then i add this condition: if request.user.user_doctors: but this gave the same error too DoctorModel: class DoctorModel(models.Model): BLOOD_TYPE_CHOICES = [ ("A+","A+"), ("A-","A-"), ("B+","B+"), ("B-","B-"), ("O+","O+"), ("O-","O-"), ("AB+","AB+"), ("AB-","AB-"), ] GENDER_CHOICES = [ ("Male","Male"), ("Female","Female"), ] user = models.OneToOneField("account.CustomUserModel",on_delete=models.CASCADE,null=False,blank=False,related_name="user_doctors") first_name = models.CharField(verbose_name="Ad:",max_length=40,null=False,blank=False) last_name = models.CharField(verbose_name="Soyad:",max_length=60,null=False,blank=False) gender = models.CharField(choices=GENDER_CHOICES,max_length=6) working_field = models.ForeignKey(DoctorField,on_delete=models.SET_NULL,null=True,blank=False,related_name="field_doctors") phonenumber = PhoneNumberField(null=False,blank=True) about = models.TextField(verbose_name="Haqqinda:",null=True,blank=True) is_active = models.BooleanField(default=True) blood_type=models.CharField(choices=BLOOD_TYPE_CHOICES,max_length=10, null=True,blank=False) born_date = models.DateField(null=True,blank=False) OperationModel: class OperationModel(models.Model): name = … -
I says E/Volley: [65] NetworkUtility.shouldRetryException: Unexpected response code 404 for http://10.0.2.2:8000/api/rooms/
**Here I have been trying to post in my data base using volley but it say "E/Volley: [65] NetworkUtility.shouldRetryException: Unexpected response code 404 for http://10.0.2.2:8000/api/rooms/" and bad request 400 in backend, and i have tried everything I can but i can't solve it. Also it shows null pointer in method uploadtodb where i have bolded below. public class HouseOwner extends Fragment { CircleImageView circleImageView; ImageView imageView; private static final int PICK_Image = 1; Button button; Bitmap bitmap; String encodeImage; EditText a, b, c, d, e, f; CheckBox g, h; private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; public HouseOwner() { // Required empty public constructor } public static HouseOwner newInstance(String param1, String param2) { HouseOwner fragment = new HouseOwner(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_house_owner, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); a = view.findViewById(R.id.edtTitle); b = view.findViewById(R.id.edtdescription); c = view.findViewById(R.id.edtEmail); d = view.findViewById(R.id.edtphone); e = view.findViewById(R.id.edtLocation); f = view.findViewById(R.id.edtPrice); g = view.findViewById(R.id.rad1); h … -
django display filefield on tables2 and django_filters
I am trying to display table that includes filefield with filter but it doesn't seem to work. It says filter is not defined and even if I remove filter completely, it says filefield is not right format or something. How do I make this work? I am trying to display table with uploaded file displayed on table(click to download) and filter it by date range(from start date to end date) and subject. model.py class TestModel(models.Model): id = models.AutoField(primary_key=True) date_created = models.DateTimeField('Date Created', auto_now_add=True) subject = models.CharField('Subject', max_length=150, null=True) posted_by = models.CharField('Posted By', max_length=30, null=True) description = models.FileField(upload_to='test/Description/') attachment = models.FileField(upload_to='test/Attachment/') tables.py class TestTable(tables.Table): class Meta: model = TestModel fields = ('date_created', 'subject', 'posted_by', 'description', 'attachment') view.py class TestView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = TestTable paginate_by = 10 model = TestModel template_name = "display/test.html" filterset_class = TestFilter filters.py class TestFilter(django_filters.FilterSet): start_date = DateFilter(name='date_created ',lookup_type=('gt'),) end_date = DateFilter(name='date_created ',lookup_type=('lt')) date_range = DateRangeFilter(name='date_created ') class Meta: model = TestModel fields = { 'subject': ['icontains'] } -
Django aggregation Many To Many into list of dict
It's been hours since I tried to perform this operation but I couldn't figure it out. Let's say I have a Django project with two classes like these: from django.db import models class Person(models.Model): name=models.CharField() address=models.ManyToManyField(to=Address) class Address(models.Model): city=models.CharField() zip=models.IntegerField() So it's just a simple Person having multiple addresses. Then I create some objects: addr1=Address.objects.create(city='first', zip=12345) addr2=Address.objects.create(city='second', zip=34555) addr3=Address.objects.create(city='third', zip=5435) person1=Person.objects.create(name='person_one') person1.address.set([addr1,addr2]) person2=Person.objects.create(name='person_two') person2.address.set([addr1,addr2,addr3]) Now it comes the hard part, I want to make a single query that will return something like that: result = [ { 'name': 'person_one', 'addresses': [ { 'city':'first', 'zip': 12345 }, { 'city': 'second', 'zip': 34555 } ] }, { 'name': 'person_two', 'addresses': [ { 'city':'first', 'zip': 12345 }, { 'city': 'second', 'zip': 34555 }, { 'city': 'third', 'zip': 5435 } ] } ] The best i could get was using ArrayAgg and JSONBAgg operators for Django (I'm on POSTGRESQL BY THE WAY): from django.contrib.postgres.aggregates import JSONBAgg, ArrayAgg result = Person.objects.values( 'name', addresses=JSONBAgg('city') ) But that's not enough, I can't pull a lit of dictionaries out of the query directly as I would like to do, just a list of values or something useless using: addresses=JSONBAgg(('city','zip')) which returns a dictionari with random keys and the … -
Retrieve specific user's profile information
In my web App I'm trying to add the function of clicking on the author of a certain post and being able to see their profile and also the posts said user has created. I've managed to get the post list working just fine but when I try to call specific user data, it gives me the data of the logged in user. Here's how I call the user profile in HTML: <section class="py-5"> <div class="container my-5"> <div class="row justify-content"> <div class="col-lg-6"> <div class="content-section"> <div class="media"> <img class="rounded-circle profile-img" src="{{ user.profile.image.url }}"/> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <!-- only This works --> <p class="text-secondary">{{ view.kwargs.username }} {{ user.last_name }}</p> <p class="text-secondary">{{ user.email }}</p> <div class="container"> <p class="lead"><Strong>Sobre mi:</strong></p> <p class="lead">{{ user.description }}</p> </div> <br> <p class="text-secondary">Se unió el {{ user.date_joined }}</p> <p class="text-secondary">Última vez visto: {{ user.last_login }}</p> <p class="mb-0">{{ user.profile.about }}</p> </div> </div> </div> </div> </div> Here is my views: class UserPostListView(ListView): model = Post template_name = 'forum/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') Here is how the problem looks: As you guys can see, that's Yonas1420's profile, but it's only returning the correct username, because the profile picture, the … -
Validation for unique in form
I have model and form like this class Article(models.Model): key = models.CharField(max_length=20,null=False,unique=True) class ArticleForm(forms.ModelForm): class Meta: model = Article key = forms.CharField(required=True) This key is unique in table, so I want to validate in form too. If I put the existing key, it comes to the 1062, "Duplicate entry 'inquiry' for key error in yellow screen However it also doesn't work, forms.CharField(required=True,unique=True) How can I make this validation? -
In Django : How can I multiply two columns and save to another column in update query?
class A(models.Model): revenue = models.FloatField() list_price = models.FloatField() unit_sold = models.FloatField() I have this model which has 1M records in list_price and unit_sold I want to fill revenue column using list_price * unit_sold -
How to check if record exists in django mysql before insert into database
Please pardon me, am still new to djando framework. This error i always get i run it. The view finance_lens_app.views.acct_type didn't return an HttpResponse object. It returned None instead. This is my model class Acct_type(models.Model): Aid=models.AutoField(primary_key=True) acct_type_name=models.CharField(max_length=200) class Meta: db_table="Acct_Type" This is my VIEW. def acct_type(request): if request.method=='POST': request.POST.get('acct_type_name') acct_type_record=Acct_type() acct_type_record.save() messages.success(request, 'Account Type Added Successfully...') return render(request, "admin_opera/acct_type.html") My Interface HTML <form method="POST"> {% csrf_token %} <div class="input-group mb-3"> <select name="acct_type_name" id="acct_type_name" class="form-control"> <option value="Assets">Assets</option> <option value="Liabilities">Liabilities</option> <option value="Equities">Equities</option> <option value="Incomes">Incomes</option> <option value="Expenses">Expenses</option> <option value="Expenses2">Expenses2</option> <option value="Expenses3">Expenses3</option> </select> </div> <input class="btn btn-primary btn-lg" type="submit" name="submit" value="Add Account"> </form> -
Is there an easier way to see changes made on front end?
I am building my first django + react project and my question is when I make a change to my front end, do I have to run build and then manage.py runserver every time after to see the changes? I mean this gets it to work for me but just felt I might be doing something wrong and there is an easier way. -
Frequently update an angularjs frontend with real time data from django server
There are some data which would be sent frequently from a django server to the angularjs, this is a data which would be modified frequently and the modification would be updated at the front end when the changes are made at the backend At the point where the data is made available I have inserted views.py send_event('test', 'message', {'text': dataModifiedFrequently}) asgi.py application = ProtocolTypeRouter({ 'http': URLRouter([ url(r'^event_url/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), { 'channels': ['test'] }), url(r'', get_asgi_application()), ]), }) angular.js $scope.EventSourceScope = function(){ if (typeof(EventSource) !== "undefined") { var source = new EventSource('event_url'); source.onmessage = function (event) { $scope.openListingsReport = event.data; $scope.$apply(); console.log($scope.openListingsReport); }; } else { // Sorry! No server-sent events support.. alert('SSE not supported by browser.'); } } I used the Django EventStream package and followed the example I do not seem to see any result in the angularjs. but in my browser it gave me the error EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection. Please how can I get django to send data to angularjs as it occurs -
Why is RDS MySQL Database with Django running very slowly with very simple queries?
I developed a simple application with Django, Django REST Framework and MySQL, and everything works fine in my local machine. I want to upload the application to AWS, so I started by creating an RDS MySQL instance and connected it to my Django app. After doing that and running the migrations, the application got very slow. I know that a local database is expected to be faster than an RDS instance, but the difference in the speed is way too big. As an example, this is one of the views I have: class DeckApi(viewsets.ViewSet): permission_classes = [IsAuthenticated] def list(self, request, *args, **kwargs): qs = Deck.objects.filter(user=request.user) serializer = DeckSerializer(qs, many=True) return Response(serializer.data, status=status.HTTP_200_OK) One call to this view takes about 5 or 10 seconds to respond and the database is almost empty. To find out whether the problem was in the RDS instance, I tested it from the terminal. I logged in and tried to make a query similar to what the above view would do: SELECT * FROM flashcards_deck WHERE user_id=2; This query runs in about 200 milliseconds. Although this is still a lot for such a simple query in an almost empty database, it is much less than 5 … -
How to fix login template dissappear problem?
I created 404 handler in my Django project and I am preparing it for deployment. So I change DEBUG = False and that remove my login page and I don't know how can I get the login page. When I change debug=true or remove 404 handler, my login page shows. But I cannot do them in deployment. How can I fix it? views.py @login_required def home(request): return render(request, 'index.html') def f_handler404(request, exception=None): return render(request, 'index.html') urls.py handler404 = "register.views.fray_handler404" settings.py LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/accounts/login' And my login template is in project/templates/registration/login.html -
Can i Create A Website Using HTML CSS JAVA (Not Javascript) Python Django Heroku?
Hi Everyone I Had A Question Regarding Creating Website Can i Make One Just Using HTML CSS JAVA (Not Javascript) Python Django Heroku? Reason i Don't Want To Touch Javascript Is Because i Hate it But im Pretty Open To Learning Vaadin and Springboot -
Use URL data to fill form in Django with Class Based Views
I have 2 Models: Projects and Members, each one with a form. I was able to add to the URL the number of the project (id) this: class PageCreate(CreateView): model = Page form_class = PageForm success_url = reverse_lazy('members:create') def get_success_url(self): return reverse_lazy('members:create', args=[self.object.id]) When I finish of filling the Project form, it redirects the page to the Member form. What I want to do is to extract the ID of the Project from the URL and use it in the Member form. I cannot think any other solution. Currently I have a Selection list to select the Project in the Member form but I want the Project loaded as soon as is created. I am using the CreateView in the models for both Projects and Members. This is the view for MemberCreate @method_decorator(login_required, name='dispatch') class MemberCreate(CreateView): model = Member form_class = MemberForm success_url = reverse_lazy('pages:pages') Only attempt I had to visualize the ID in the HTML was using {{ request.get }} To somehow get the value from the GET but I could not do it.