Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create proxy web server in Django
I need to create a web server that proxies the request to the SWAPI api, finds the context provide(for example a character) and returns the result. I've done this many times but never had to create a proxy web server. So how do I implement a proxy web server??? I don't even know where to start. Any help? -
Generating gifs based on a user input
I would like to generate gifs based on a user input. I can generate a single gif using the following code: ` def getGif(request): import time import giphy_client from giphy_client.rest import ApiException from pprint import pprint # create an instance of the API class api_instance = giphy_client.DefaultApi() api_key = 'dc6zaTOxFJmzC' # str | Giphy API Key. q = 'rainbow' # str | Search query term or prhase. limit = 25 # int | The maximum number of records to return. (optional) (default to 25) offset = 0 # int | An optional results offset. Defaults to 0. (optional) (default to 0) rating = 'g' # str | Filters results by specified rating. (optional) lang = 'en' # str | Specify default country for regional content; use a 2-letter ISO 639-1 country code. See list of supported languages <a href = \"../language-support\">here</a>. (optional) fmt = 'json' # str | Used to indicate the expected response format. Default is Json. (optional) (default to json) try: # Search Endpoint api_response = api_instance.gifs_search_get(api_key, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt) # pprint img = requests.get(api_response.data[0].images.fixed_height_downsampled.url) return HttpResponse(img,content_type='image/gif') #return HttpResponse(api_response.data[0].images.fixed_height_downsampled.url, content_type="application/json") except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e)` -
Optimize Django Queryset for loop
How can I optimize the following queryset? [link.goal for link in self.child_links.all()] I want to get rid of the for loop and hit the database only once. I've got the following code: class Goal(models.Model): name = models.CharField(max_length=300) progress = models.SmallIntegerField(default=0) def __str__(self): return self.name def calc_progress(self): progress = 0 subgoals = [link.goal for link in self.child_links.all()] self.progress = int(progress) class Link(models.Model): parent_goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name="child_links") goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name="parent_links") weight = models.SmallIntegerField(default=1) def __str__(self): return str(self.parent_goal) + "-->" + str(self.goal) -
django-admin.py doens't work on Windows Server 2012
I'm not an expert on Python, however, I've been trying to setup a project on Windows Server 2012 on IIS. When I've tryed to run 'django-admin.py startproject teste' I always got an error like this: I've tryed the command in the following ways: django-admin.py startproject teste python django-admin.py startproject teste C:\Python37\Scripts\django-admin.py startproject teste My environment variables are like this: Can someone help me on this, please? -
Is there any HTML editor like CK editor where HTML block drag and drop features are present like in wordpress that can be used in django project
Is there any HTML editor like CK editor where HTML block drag and drop features are present like in wordpress that can be used in django project. I have a campaign mailing system where I want to user HTML editor to make campaigns using the likes of CK Editor etc. Is there any Drag and Drop HTML Editors out there. E.g. The ability to drag a heading into the editor, or a heading and an image and it fixes into a specific layout. I am only after the editor capabilities. -
attribute error when try to define url for index view
I keep getting a strange error when I define urls: AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://localhost:51942/ Django Version: 2.1.3 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' here is my urls: from django.contrib import admin from django.urls import path from saeed import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), ] and here is my views: from django.shortcuts import render def index(request): return render,"index.html" Please inform me. thanks, Saeed -
django rest action got unexpected positional argument
I have an viewset with action, which has defined for adding friends to user. But I got a problem with url, send post query on http://localhost:8000/accounts/users/mercer/add_friend/ and got this message: add_friend() got an unexpected keyword argument 'username' My ViewSet: class UserViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = UserSerializer lookup_field = 'username' http_method_names = ['get', 'patch', 'post'] @action(detail=True, methods=['post']) def add_friend(self, request): return Response('ok') -
How to avoid duplication of records in the database?
There are following models: class Parameter (models.Model): id_parameter = models.IntegerField(primary_key=True) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) #not FK par_name = models.CharField(max_length=200) class Measurements (models.Model): id_measurement = models.AutoField(primary_key=True) par_value = models.IntegerField(default=0) line = models.ForeignKey(Line, on_delete=models.CASCADE, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) parameter = models.ForeignKey(Parameter, on_delete=models.CASCADE, null=True) I write down as follows: def handle_parameters_upload(request, file): wb = openpyxl.load_workbook(file, read_only=True) first_sheet = wb.get_sheet_names()[0] ws = wb.get_sheet_by_name(first_sheet) recipe, created = Recipe.objects.get_or_create(par_recipe=ws["B2"].value) line, created = Line.objects.get_or_create(par_machine=ws["C2"].value) order, created = Order.objects.get_or_create(par_fa=ws["D2"].value) data = [] data_par = [] _id = 1 for row in ws.iter_rows(row_offset=1): parameter = Parameter() parameter.id_parameter = _id _id += 1 parameter.par_rollennr = row[5].value parameter.par_definition_id = row[6].value parameter.par_name = row[7].value data_par.append(parameter) measurements = Measurements() measurements.par_value = row[8].value measurements.line = line measurements.order = order measurements.parameter = parameter measurements.recipe = recipe data.append(measurements) # Bulk create data Measurements.objects.all().delete() Parameter.objects.all().delete() Parameter.objects.bulk_create(data_par) Measurements.objects.bulk_create(data) return True How to avoid duplication of records in the Parameter table and not to lose dependencies by Id. The parameter is 3 fields in the file, each next line has its own, but there are no more than 1052 in total and they are repeated, respectively, every 1052 entries. It looks like this: rollennr | deffinitionid | name | value … -
Comparing instance of different models - Django REST Framework
I'am just looking for answer for my (seems to be stupid) question. I've already watched few stackoverflow posts but any of them was helpful :( My question is how to compare two instance of different models with different? Here is my case: I've got two models: Product and Connector. First include id(pk), name, ect. Another include id(pk), productId(fk), userId(fk), ect. My goal is to prepare view that list only product which are in Connector db-table as product(fk). def list(self, request, *args, **kwargs): # return only product user's watching userId = self.request.user.id connectorData = ConnectorModel.objects.filter(userId=userId) allProducts = self.get_queryset() productListToDisplay = [] for product in allProducts: for connector in connectorData: if product.id == connector.productId: # HERE IS A PROBLEM productListToDisplay.append(product) serializer = ProductSerializer(productListToDisplay, many=True) return Response(serializer.data) Problem is that Django consider "product.id" and "connector.productId" as totally different types. Firs is "core.models.ProductModel" and second is "core.models.ConnectorModel". I was trying to parse it using int() but it generate errors. How I can compare this two values to add object to productListToDisplay array? (I saw django doc - Comparing objects but there is no helpful information for this case) -
pip3 install django on ubuntu
Trying to install djnago on my Ubuntu but I fail to do that. I guess this is due to the fact I have python 2/7 and python 3 on my Ubunutu: pip3 install django Traceback (most recent call last): File "/usr/local/bin/pip3", line 5, in <module> from pkg_resources import load_entry_point File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3126, in <module> @_call_aside File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3110, in _call_aside f(*args, **kwargs) File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3139, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 583, in _build_master return cls._build_from_requirements(__requires__) File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 596, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 784, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==9.0.1' distribution was not found and is required by the application The following is installed on the ubunuto: itaybz@itaybz-ub-pc:/usr/local/bin$ python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> itaybz@itaybz-ub-pc:/usr/local/bin$ python3 Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. -
How can i check if model field was changed in post_save?
I have to do some extra logic in post_save if one of model fields was updated, but can't check if it was updated. Tried to override init method like this def __init__(self, *args, **kwargs): super(Profile, self).__init__(*args, **kwargs) self.__old_city = self.city and in post_save check if instance.city != instance.__old_city: #extra logic but got an exception AttributeError: 'Profile' object has no attribute '__old_city' What i'm doing wrong(except of using signals :D )? -
NoReverseMatch at /polls/ Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']
NoReverseMatch at /polls/ Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P[0-9]+)/vote/$'] index.html: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <!-- # the 'name' value as called by the url template tag --> <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> <!-- or: <li><a href=" url 'detail' question.id "> question.question_text </a></li> How does one make it so that Django knows which app view to create for a url when using the url template tag? So we use polls:detail --> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} <input type="submit" value="Vote"> </form> enter image description hereenter image description here Below it's console error. Other relative questions in stackoverflow have answer like: not question_id! It's question.id! Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P[0-9]+)/vote/$']: 113 {% endfor %} 114 </ul> 115 {% else %} 116 <p>No polls are available.</p> 117 … -
Django/Database models automatic categorization
I am just starting with the Django framework and I have not too many background in databases as I am not a professional programmer. I am looking for the most elegant way to model the following: one item in the model , e.g. CharField could be: house, bridge, church I want to add a field that automatically uses "building" for these items. Or, I have car, truck, etc. it uses "automatically" (acc. to my definition) the category "vehicle". Ideally, I would just add data to the word lists, which are stored in a database and classification would be done accordingly. Is there something like enumeration/classification type? Hope it is clear, otherwise, please let me know. Thanks in advance for your help! -
Reverse for 'download_report' with arguments '()' and keyword arguments '{u'regid': 75}' not found. 0 pattern(s) tried: []
I'm new to django. I want to extend the existing project. I want to display dynamic data table and download report of a particular id. When I run the project it returns Reverse for 'download_report' with arguments '()' and keyword arguments '{u'regid': 75}' not found. 0 pattern(s) tried: [] urls.py > url(r'^(?P<regid>\d+)/$', > views.ApplicationView.as_view(),name="view_application"), registrationlist.html <li> <a href="{% url 'download_report' regid=registrationid %}"><span class="glyphicon glyphicon-list-alt"></span> Download Report</a> </li> views from random import shuffle from constance import config from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render # from django.template.response import SimpleTemplateResponse from django.views import View from bps_registration.models import NewRegistration def get_related_object_or_none(related_manager): try: return related_manager.get() except: return None class DownloadReport(LoginRequiredMixin, View): def get(self, request, regid): context = {} context['municipality'] = config.Municipality context['registrationid'] = regid reg = NewRegistration.objects.get(id=regid) context['registration'] = reg context['application_status'] = reg.applicationstatus_set.all() context['application'] = get_related_object_or_none(reg.application_set) context['houseowner'] = reg.houseownerinfo_set.all() houseowner_names = ", ".join(reg.getAllHouseownerNpNameAsList()) if houseowner_names == "": context['houseowner_name'] = u"{} ({})".format(reg.houseowner_name_np, reg.houseowner_name_en) else: context['houseowner_name'] = houseowner_names context['landowner'] = reg.landowner_set.all() context['applicant'] = get_related_object_or_none(reg.applicant_set) context['landinformation'] = get_related_object_or_none(reg.landinformation_set) charkillas = reg.charkilla_set.all() for ch in charkillas: if ch.ch_direction == "n": context['charkilla_n'] = ch elif ch.ch_direction == "e": context['charkilla_e'] = ch elif ch.ch_direction == "s": context['charkilla_s'] = ch elif ch.ch_direction == "w": context['charkilla_w'] = ch else: context['charkilla_other'] = … -
Django UpdateView misses queryset
I can't figure out, what is wrong with my code. I tried so much stuff and my createview is working. But there I use the flight and not the gatehandling as pk. For me this seems okay, and I dont understand why the console tells me that querysets are missing. models.py class Airport(models.Model): name = models.CharField(max_length=255, unique=True) class Flight(models.Model): start = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name='start') end = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name='end') number = models.CharField(max_length=5, default="EJT12") class Gate(models.Model): airport = models.ForeignKey(Airport, on_delete=models.CASCADE) number = models.IntegerField(default=0) class GateHandling(models.Model): gate = models.ForeignKey(Gate, on_delete=models.CASCADE) flight = models.ForeignKey(Flight, on_delete=models.CASCADE) urls.py path('gate-handling/<int:pk>/update', views.GateHandlingUpdate.as_view(), name='gate_handling_update'), detail.html {% for flight in flights_arriving %} {% for gate_handling in flight.gatehandling_set.all %} <p>{{gate_handling}} <a href="{% url 'management:gate_handling_update' gate_handling.pk %}">Change</a></p> {% empty %} <p>Gate <a href="{% url 'management:gate_handling_create' flight.pk %}">Assign</a></p> {% endfor %} {% endfor %} views.py class GateHandlingUpdate(UpdateView): form_class = GateHandlingUpdateForm template_name = 'management/gatehandling_update.html' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['airport'] = Gate.objects.get(gatehandling=self.object).airport kwargs['flight'] = Flight.objects.get(pk=self.object.flight.pk) return kwargs forms.py class GateHandlingUpdateForm(ModelForm): class Meta: model = GateHandling fields = ['gate', 'flight'] def __init__(self, *args, **kwargs): airport = kwargs.pop('airport') flight = kwargs.pop('flight') super().__init__(*args, **kwargs) self.fields['flight'].queryset = Flight.objects.filter(pk=flight.pk) self.fields['gate'].queryset = Gate.objects.filter(airport=airport) console Internal Server Error: /gate-handling/9/update Traceback (most recent call last): File "D:\airport\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner … -
How to run python project in context of Django
I'm working on a Python project, I finished it and I decided to turn it into SaaS (software as service) by using the Django framework (REST API) for the backend and VueJs for the frontend. For the part of the django + Vuejs I did things well. the problem is that I do not know how to integrate my python project that runs on linux with Django. image describe my work (how to import it, how to install the requirements, how to change the parameters with the interface Vuejs ...) Do I have to run my Python project in a server and control it with django? If yes, how ? I do not know if this approach is the best to launch a Saas? thank you for helping me to have a global idea about how things work. -
How to get object wise keys in Django requests?
I'm creating an Custom Object which has user as Foreign Key, so the request I'm getting is in the form: <QueryDict: {'csrfmiddlewaretoken': ['someToken'], 'name': ['SomeName'], 'user.username': ['username'], 'user.email': ['email@gmail.com'], 'user.password': ['1234']}> I need to get all attributes with keys starting from user.. Basically, it's my User object in that request. Is there any way to get it directly instead of nitpicking every key-val pair? Thanks -
Django: AttributeError: 'AdminSite' object has no attribute 'reqister'
So I am starting with Django and I am working on the Django tutorial-project, that includes a poll application. The tutorial gave me the Code: from django.contrib import admin from .models import Question admin.site.register(Question) But when I add this to my code and try it out it gives me the error: AttributeError: 'AdminSite' object has no attribute 'reqister' My admin.py file looks exactly like this and without this code everything is running fine -
Deploying a Django Project through Git to Heroku: "No module named.. - failure"
I'm hoping you may be able to help me and at the same time, I hope this query may serve others here well in the future. Based on the excellent book: Python Crash Course by Eric Matthes, I am trying to deploy a Django app to Heroku with the use of Git and have come across several issues. Do note, there are some corrections to the book here: https://ehmatthes.github.io/pcc/updates.html I am specifically mentioning the book here, as I believe it to be ranked one of the best starter books on various sites, so I can imagine other people facing the same problems - also, as there are several posts related to these 3 topics. Initially, the app could be commited to Git, but then not pushed to Heroku using: git push heroku master Part 1: This contineously brought about the error: No Procfile and no package.json file found in Current Directory - See heroku local --help To resolve this, it was vital to make sure the file had no extension (mac os) did not show it, but an ls in the directory showed the .txt ending on the file. Part 2: Retrying this, now allowed for a new message: ModuleNotFoundError: … -
How to implement m2m_changed in django?
Basically, my question is how do I implement the m2m_changed so that when I am creating, updating or deleting an instance of ClassSubjectGrade, the intermediate table between ClassSubjectGrade and Student is also updated. Example: 1. Adding more students when I edit an instance of ClassSubjectGrade will add those students associated to the intermediate table 2. Removing students from an instance of ClassSubjectGrade will remove those students associated from the intermediate table 3. Deleting an instance of ClassSubjectGrade will remove all students associated with that instance I placed my code below but I am not sure as well if I should check for those 2 actions or there is a simple way to do it. I do not get in the documentation as well how to write the code to do the things that I want whenever I am doing the 3 examples above. class Student(models.Model): # some fields class ClassSubjectGrade(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) # other fields students = models.ManyToManyField(Student, blank=True) from django.db.models.signals import m2m_changed @receiver(m2m_changed, sender=ClassSubjectGrade.students.through) def students_changed(sender, instance, action, **kwargs): if action == 'post_remove': # How to remove all instances in intermediate table of # ClassSubjectGrade and Student # of all students that were removed from a ClassSubjectGrade … -
how to take 'X' number of inputs in django form
First of all, I have looked at other similar questions and none of them answer my question so that is why I am posting a separate question. Now, coming to problem, let me first describe what i have to do and then i will explain the problem. I have to make 2 pages, 1st will take 3 inputs: that will be 3 numbers and those numbers will represent the number of fields fr each field in the next page. and when user goes to next page, that number of fields will appear. For example, at first page I give the input 2,3,2 then at the next page a total of 7(2+3+2) input boxes will appear and then whatever user inputs in those have to be stored in my model(database). I cant make multiple forms and multiple views (for 2nd page) and then call the appropriate according to the needs because catering every possible combination of input of first page will be too much inefficient. I dont want to use angular or ajax. I am using Form not ModelForm I have read about how to make variable number of fields using init function of forms.py and I have also read So … -
How to pass choices in template using dropdown html fields? (Django)
These are my files, Views.py Forms.py Models.py Html template Whenever I save the instance, it saves the type as "option value=" in type column. How do I pass type in database properly? -
Django Machine learning: '<' not supported between instances of 'Applicant' and 'Applicant'
I have a model that I want to use for predictions which I have loaded using pickle and I have a form created in using django. But when a user submits the form I want it to be in store it in a csv format in a variable so I can perform Xgboost prediction on every form the user fills and after it outputs the prediction. COuld it be its not getting any input. New to this from django.db import models from django import forms from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. type_loan=(("Cash loan","Cash loan"), ("Revolving loan","Revolving Loan")) Gender=(("Male","Male"), ("Female","Female")) Yes_NO=(("YES","YES"),("NO","NO")) status=(("Single","Single"), ("Married","Married"), ("Widow","Widow"), ("Seprated","Divorce")) Highest_Education=(("Secondary","Secondary"), ("Incomplete Higher","Incomplete Higher"), ("Lower Secondary","Lower Secondary"), ("Academic Degree","Academic Degree")) Income_type=(("Working","Working Class"), ("State Servant","Civil Servant"), ("Commercial Associate","Commercial Associate"), ("Pensioner","Pensioner"), ("Student","Student"), ("Businessman","Business Owner")) class Applicant(models.Model): name=models.CharField(default="Jon Samuel",max_length=50,null="True") Birth_date=models.DateField(default="2018-03-12",blank=False, null=True) Status=models.CharField(choices=status,max_length=50) Children=models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(17)]) Highest_Education=models.CharField(choices=Highest_Education,max_length=50) Gender=models.CharField(choices=Gender, max_length=50) loan_type=models.CharField(choices=type_loan, max_length=50) own_a_car=models.CharField(choices=Yes_NO,max_length=50) own_a_house=models.CharField(choices=Yes_NO,max_length=50) def __str__(self): return self.name views.py from django.shortcuts import render from .models import Applicant from .forms import Applicant_form from django.views.generic import ListView, CreateView, UpdateView from django.core.cache import cache import xgboost as xgb import pickle from sklearn.preprocessing import LabelEncoder class CreateMyModelView(CreateView): model = Applicant form_class = Applicant_form template_name = 'loan/index.html' success_url = '/loan/results' context_object_name = 'name' class … -
need to restrict relationship using foreign key
I need that when registering a Pessoa and a Veiculo they are realacionamos in a way that when registering using Views Mensalista when I put Pessoa soment the Veiculo that is owned by it appears Models.py STATE_CHOICES = ( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins') ) class Pessoa(models.Model): nome = models.CharField(max_length=50, blank=False) email = models.EmailField(blank=False) cpf = models.CharField(max_length=11, unique=True, blank=False) endereco = models.CharField(max_length=50) numero = models.CharField(max_length=10) bairro = models.CharField(max_length=30) telefone = models.CharField(max_length=20, blank=False) cidade = models.CharField(max_length=20) estado = models.CharField(max_length=2, choices=STATE_CHOICES) def __str__(self): return str(self.nome) + ' - ' + str(self.email) class Veiculo(models.Model): marca = models.ForeignKey(Marca, on_delete=models.CASCADE, blank=False) modelo = models.CharField(max_length=20, blank=False) ano = models.CharField(max_length=7) placa = models.CharField(max_length=7) proprietario = models.ForeignKey( Pessoa, on_delete=models.CASCADE, blank=False, ) cor = models.CharField(max_length=15, blank=False) def __str__(self): return self.modelo + ' - ' + self.placa views.py @login_required def mensalista_novo(request): if request.method == … -
Before and after login, I want to use same URL but use different class based view
Before and after user login, URL is not changed in many websites. How should I implement this in Django? For example, http://example.com (show login page) → login → http://example.com (show content list) I want to use class based view for Login Page (auth_views.LoginView), then after user login, use generic list View and different template. urls.py from django.contrib.auth import views as auth_views urlpatterns = [ path('', auth_views.LoginView.as_view(template_name='index.html'), name='index'), views.py from django.views.generic import ListView class UserIndexView(ListView): model = mymodel template_name = 'user_index.html'