Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms out as UL and not DIV
Just upgraded my Django app from version 3.2 to version 4.1. When I now render a form with multiple choices it renders each item as a div and not li. Sample code as follows: from django import forms CHOICES = [] for i in range(1, 20): CHOICES.append((str(i),str(i))) class ChoicesForm(forms.Form): choices = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple(), choices=CHOICES) form = ChoicesForm() print(form) The output(shortened) of the print(form) is <tr> <th><label>Choices:</label></th> <td> <div id="id_choices"><div> <label for="id_choices_0"><input type="checkbox" name="choices" value="1" id="id_choices_0"> 1</label> </div><div> <label for="id_choices_1"><input type="checkbox" name="choices" value="2" id="id_choices_1"> 2</label> </div><div> <label for="id_choices_2"><input type="checkbox" name="choices" value="3" id="id_choices_2"> 3</label> </div><div> <label for="id_choices_3"><input type="checkbox" name="choices" value="4" id="id_choices_3"> 4</label> But what I was getting in my earlier code was <tr><th><label>Choices:</label></th><td><ul id="id_choices"> <li><label for="id_choices_0"><input type="checkbox" name="choices" value="1" id="id_choices_0"> 1</label> </li> <li><label for="id_choices_1"><input type="checkbox" name="choices" value="2" id="id_choices_1"> 2</label> </li> <li><label for="id_choices_2"><input type="checkbox" name="choices" value="3" id="id_choices_2"> 3</label> </li> <li><label for="id_choices_3"><input type="checkbox" name="choices" value="4" id="id_choices_3"> 4</label> I can't find any reference to why this would change. Nor can I figure out how to create my form output as a list and not Is this expected or is there something else I am missing ? What I ultimately want to achieve is to format the output as rows of items and not a column … -
Exception inside application: No route found for path 'ws/chat/room/2/'
Problem with Django channels. Please help. my routing.py websocket_urlpatterns = [ url(r'ws/chat/room/(?P<room_id>\d+)/$', ChatConsumer.as_asgi()), ] my room.html var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/room/{{ room.id }}/' ); my settings.py path('chat/', include('chat.urls', namespace='chat')), my chat_urls.py path('room/<int:room_id>/', views.room, name='room'), path('room/<int:room_id>/send_message/', views.send_message, name='send_message'), websocket.url = ws://127.0.0.1:8000/ws/chat/room/2/ changed re_path a lot of times, asked chatgpt to write new html template (I'm more into Django then in JS). -
I connected a MySQL database to Django, but the user information is not being retrieved
class Review(models.Model): review_id = models.BigAutoField(primary_key=True) review_content = models.CharField(max_length=255, blank=True, null=True) review_grade = models.FloatField() user_id = models.BigIntegerField() book_isbn = models.CharField(max_length=32) created_date = models.DateTimeField(blank=True, null=True) modified_date = models.DateTimeField(blank=True, null=True) class Meta: db_table = 'review' class User(models.Model): user_id = models.BigAutoField(primary_key=True) created_at = models.DateTimeField() email = models.CharField(unique=True, max_length=64) username = models.CharField(unique=True, max_length=32) nickname = models.CharField(unique=True, max_length=32) password = models.CharField(max_length=128) user_type = models.IntegerField(blank=True, null=True) user_role = models.IntegerField(blank=True, null=True) age = models.IntegerField() sex = models.IntegerField() prefer_score = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'user' "This is the code written in models.py." >>> User.objects.all() <QuerySet []> >>> Review.objects.all() <QuerySet [<Review: Review object (1)>, <Review: Review object (2)>, <Review: Review object (3)>, <Review: Review object (4)>]> "This is what I tried in the Django shell_plus. Although there is data in the database, I can't figure out why the User data returns an empty queryset. Please help me." "I ran python manage.py makemigrations and python manage.py migrate. I also tried to find information about Django custom user model, but I couldn't solve the issue." -
how to pass the url into the view context in django?
page_title.html <!-- page title --> ... <ul class="list-inline custom-breadcrumb mb-2"> <li class="list-inline-item"><a class="h2 text-primary font-secondary" href="{% url 'teacher-list' %}">{{list_title}}</a></li> ... <!-- /page title --> views.py class TeacherDetailView(DetailView): model = Teacher context_object_name = "teacher" template_name = "users/teacher_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['list_title'] = "Our Teachers" return context So currently have a teacher_detail page, on that page there is a page_title section (which is being included inside other templates) which has a url that allows you to go to the list view version of it, in this case it is the teacher_list page. The problem is that i have multiple pages with similar design, i know how that i can pass in the list_view variable as a part of the view context which makes it dynamically displayed depending on the page. I wonder how i can also pass in the url as a dynamic variable into the view context like: context['list_url'] = "{% url 'teacher-list %}" so that i don't have to repeat it and also will be able to reuse the page_title sub template? -
Choosing framework for streaming video for better performance
I have a task to create an API for streaming images that my backend gets through a GRPC connection. The question is: what python framework is best suited for this job? I'd like to know if there is any framework that support having a single streaming response for multiple clients. I mainly use Django, but I've heard that it would be a bad choice for this kind of task since it'd allocate a separate process for every new connection, and that would result in bad performance. I've looked into websocket implementations with Django, but I'm still not sure what the best decision is for this kind of task. -
D3 bar chart returning height of "NaN"
I'm attempting to display a basic animated line-chart using D3 (v7) to my web page. This is being done from within a Django project and so my chart is being fed data from my views.py file. However, the chart only partially displays on the page. The x and y axis lines are displayed, along with the axis labels. Here is my error message: Error: <rect> attribute height: Expected length, "NaN". Here is the relevant part of my html template: <div id="chart-container"></div> <script src="https://d3js.org/d3.v7.min.js"></script> <script type="text/javascript"> const data = JSON.parse('{{ assign_levels|safe }}'); const margin = {top: 10, right: 30, bottom: 140, left: 60}; const width = 400 - margin.left - margin.right; const height = 500 - margin.top - margin.bottom; const svg = d3.select("#chart-container") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); const x = d3.scaleBand() .range([0, width]) .domain(data.map(d => d.level_assign)) .padding(0.3); const y = d3.scaleLinear() .range([height, 0]) .domain([0, d3.max(data, d => d.count)]); svg.append("g") .call(d3.axisLeft(y)); svg.selectAll(".bar") .data(data) .enter() .append("rect") .attr("class", "bar") .attr("x", d => x(d.level_assign)) .attr("width", x.bandwidth()) .attr("y", height) .attr("height", 0) .attr("fill", "#5F9EA0") .transition() .duration(1000) .delay((d, i) => i * 100) .attr("y", d => y(d.count)) .attr("height", d => height - y(d.count)); svg.append("g") .attr("transform", … -
I removed all firewalls but still can not access my webpage via vpn
I am just got my first Raspberry Pi and decided to host little website project using Django. Everything was running smoothly until the firewall part. I was not sure why externally other can not access my webpage, I do not see any errors on host. I completely removed all firewalls on my host (by default Raspberry Pi had: iptables), also changed django project settings and allowed all hosts. But still can not access webpage through mobile internet, vpn or though friends phone. Not sure what is going on. Website is accessible through devices that are connected to my wifi. But I though removing all firewalls will allow access to any device. This is how I deleted iptable from my host I also noticed message mentioning about replacing iptable with nftable. Just in case I also removed nftable, which should leave my webpage totally naked and without firewall protection. But still can not access it 😔 In case you missed I am using: Raspberry Pi Zero W OS: Linux raspberrypi 6.1.19+ #1637 Tue Mar 14 11:01:56 GMT 2023 armv6l GNU/Linux Project: Django 2.2.19 Note: Nginx and Gunicorn works perfectly fine. My website is accessible and working through my wifi. I know … -
I want to grab all my data from my forms and save to the DB
I wanna grab those fields and save to my db. But i get this error. 'User() got unexpected keyword arguments: speciality, start_year.... etc etc' I have two types of user Student and Teacher. So i have a custom user model. i have almost 3 months learning Django. I hope you can help me, thank you. #My forms. class StudentSignupForm(forms.Form): email = forms.EmailField( widget=forms.EmailInput( attrs={ "class": "form-control", "placeholder": "Email", } ) ) username = forms.CharField( min_length=3, max_length=20, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Username"} ), ) first_name = forms.CharField( min_length=5, max_length=50, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "First name"} ), ) last_name = forms.CharField( min_length=5, max_length=50, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Last name"} ), ) nation = forms.ChoiceField(choices=NATIONALITY_CHOICES, required=False) sex = forms.ChoiceField(choices=SEX_CHOICES, required=False) phone = forms.CharField( min_length=5, max_length=50, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Phone"}), ) address = forms.CharField( min_length=5, max_length=50, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Address"} ), ) department = forms.ChoiceField(choices=DEPARTMENT_CHOICES, required=False) speciality = forms.ChoiceField(choices=SPECIALITY_CHOICES, required=False) shift = forms.ChoiceField(choices=SHIFT_CHOICES, required=False) plan = forms.ChoiceField(choices=TYPE_CHOICES, required=False) medical_notes = forms.Textarea() campus = forms.ChoiceField(choices=CAMPUS_CHOICES, required=False) password = forms.CharField( label="password", widget=forms.PasswordInput( attrs={ "class": "form-control", "placeholder": " Insert a password", "id": "password", "required": "required", } ), ) password_confirmation = forms.CharField( label="password", widget=forms.PasswordInput( attrs={ "class": "form-control", "placeholder": " Confirm your password", "id": "password_confirmation", "required": "required", } … -
docker environment with django and postgres not loading the database container
I'm trying to learn how docker works, and trying to set up a react/Django image with Postgres, but I can't seem to connect to the database: This is my docker-compose.yml version: "3" services: database: image: postgres:12.7-alpine volumes: - ./backup_data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres backend: build: ./mash_backend volumes: - ./backend:/app depends_on: - database frontend: build: ./mash_frontend volumes: - ./frontend:/app depends_on: - backend ports: - 80:80 nginx_backend_server: build: ./nginx_backend_server ports: - 8000:8000 depends_on: - backend and on my seetings.py, I placed the host as database since this is the name of my container, not sure if this is correct DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'database', 'PORT': 5432, } } this is my Dockerfile on my backend: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip3 install -r req.txt RUN python manage.py makemigrations RUN python manage.py migrate CMD gunicorn -b 0.0.0.0:8000 --worker-class=gevent --worker-connections=1000 --workers=5 backend.wsgi whenever I run a docker-compose up I got this error during the migrate psycopg2.OperationalError: could not translate host name "database" to address: Name or service not known what I'm missing here? -
Better way of checking query string parmeter in Django
I have quite some integer query string params that I convert this way. Is there built in better way ? current_page = request.GET.get('page') current_page = 0 if current_page is None else int(current_page) -
Django. Adding fields to the model through the admin panel
How to make a model (for example, "Brigade"), the composition of which can be expanded when creating an instance in the admin panel? We don't know in advance how many team members there will be, maybe one, maybe five... Is it possible to get by with one field, for example "members", so as not to write many fields like "member_1", "member_2" and so on? And how then in the variant with the creation of many fields of the same type to use related_name? class Brigade(models.Model): brigadier = models.ForeignKey( 'Personal', null=True, blank=False, on_delete=models.SET_NULL, verbose_name='brigadier', related_name='brigadier' ) member_1 = models.ForeignKey( 'Personal', null=True, blank=True, on_delete=models.SET_NULL, verbose_name='member_1', related_name='brigade' ) -
Background image not loading when within <style> tags. It works fine when styled within the <div> itself. Not an incorrect filepath problem
I am unable to put a background image into the <style> tags and I don't know why it's not working. All of the following was done on my local machine. My website is also hosted on a Linode server. I have the following code, which works fine. It sets the background image in a style directly in the div within the body (via Django): <body> <div class="scroll-container" style="background-image: url('{% static 'myapp/scroll-L.jpg' %}');"> </div> </body> And when I load the page you can see the scroll image loads fine (image1 https://i.imgur.com/T75mFyl.png) However when I put the background image into the <style> tag in the <head> everything starts to go wrong: <style> .scroll-container { background-image: url("../../static/myapp/scroll-L.jpg") } </style> When I load the page you can see the scroll image doesn't load (image2 https://i.imgur.com/RCsWhE7.png) I can't use Django's {% static ... %} within the head style tags so that didn't work. It's clearly something to do with the object storage (eu-central-1.linodeobjects) but I don't know what. Why would it work when using the image in the div style and not within the style tags? I've searched around for about 2 hours trying to find a fix but I can't figure it out. The … -
TemplateDoesNotExist: index.html
This was working before but I removed the project off my terminal and git cloned it again from github. I tried reinstalling with pip install and changing the name of the template. -
correct way to redirect two views to one template with different url id Django
I have two views: one to show the list of assigned users and post method to assign new users. Second view: to delete a user from usecase_assigned table and redirect to the same page. I’m showing everything in one template, and pressing delete button It’s executing another view and redirecting to the same page (UsecaseDetails.html): first view has the id of the usecase, how can I delete from second view and redirect to first view which has the usecase id? my models: class User(models.Model): user_email = models.CharField(primary_key=True, max_length=100) user_role_id = models.CharField(max_length=20) user_password = models.CharField(max_length=20) user_name = models.CharField(max_length=100) class Usecase(models.Model): usecase_id = models.CharField(primary_key=True, max_length=20) usecase_name = models.CharField(max_length=256) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_type = models.ForeignKey('UsecaseType', models.DO_NOTHING) class UsecaseAssign(models.Model): usecase_assign_date = models.DateTimeField(primary_key=True, auto_now_add=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_role_id = models.CharField(max_length=20) my views: @user_login_required def view_usecase_details(request, ucid): usecase_details = Usecase.objects.filter(usecase_id=ucid).all() usecase_details = usecase_details.prefetch_related("usecaseids") users = User.objects.all() #SELECT user_email FROM usecase_assign WHERE usecase_id LIKE 'NN245'; usecase_assigned = UsecaseAssign.objects.select_related('user_email').values_list('user_email__user_name').filter(usecase_id=ucid) #to show list of users working on uc user_assigned = UsecaseAssign.objects.values_list('user_email').filter(usecase_id=ucid) #to show list of users working on uc print(user_assigned) if request.method=='POST' and 'assignuser' in request.POST: user_email = request.POST['user_email'] userAssignCheck = UsecaseAssign.objects.filter(user_email=user_email, usecase_id=ucid) if userAssignCheck: messages.error(request, "user already added!") return HttpResponseRedirect(reverse('usecase-details', … -
How to do paginator without request?
def page_look(post_list, request): paginator = Paginator(post_list, settings.VIEW_COUNT) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return page_obj Reviewer tells me to work with page_number, but im not smart enought to solve this, pls help -
ProgrammingError at /admin/django_celery_results/taskresult/
column django_celery_results_taskresult.periodic_task_name does not exist I checked django_celery_results_taskresult table in DB and there is really no periodic_task_name field. Migration log: Running migrations: Applying django_celery_results.0001_initial... OK Applying django_celery_results.0002_add_task_name_args_kwargs... OK Applying django_celery_results.0003_auto_20181106_1101... OK Applying django_celery_results.0004_auto_20190516_0412... OK Applying django_celery_results.0005_taskresult_worker... OK Applying django_celery_results.0006_taskresult_date_created... OK Applying django_celery_results.0007_remove_taskresult_hidden... OK Applying django_celery_results.0008_chordcounter... OK Applying django_celery_results.0009_groupresult... OK Applying django_celery_results.0010_remove_duplicate_indices... OK Process finished with exit code 0 This problem appeared after the creation of a new database. My celery config: # Celery # https://docs.celeryproject.org/en/stable/index.html CELERY_BROKER_URL = os.environ.setdefault('CELERY_BROKER_URL', 'redis://redis:6379/0') CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' # Fix empty task name bug # https://github.com/celery/django-celery-results/issues/326#issuecomment-1177477623 CELERY_RESULT_EXTENDED = True -
ModuleNotFoundError: No module named 'bookingformtools'
settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'booking' 'crispy_forms', 'formtools', ] the error, ModuleNotFoundError: No module named 'bookingformtools' Pip installed django-crispy-forms and django-formtools. Added them to settings.py and the project won't run. Tried using both a virtual environment and otherwise. Not quite sure why I am getting a module error. Pip show is not helping either. -
my phone can't login to Django admin panel.(but my pc can ???)
i got a problem i deploy my django app with azure and azure PostgreSQL.i can login admin perfectly fine with pc but when i give link to my friend for login to admin and this happened this picture i login by my phone and it says the same of my friend when they login but i login by my pc it fine. and this my setting.py 1 2 3 4 i want to let my friend login to admin for editing database. -
Bootstrap and CSS Styling not working with Django Forms
I have a django form where I have certain fields. Now I want to add some styling to it (bootstrap mostly). But it does not seem to be working. In my forms.py file from django import forms from django.core.validators import FileExtensionValidator file_type_choices = [ ('CSV', 'Comma-Separated Values'), ('TSV', 'Tab-Separated Values') ] valid_extensions = ['.tsv', '.csv'] class FileUploadForm(forms.Form): file = forms.FileField(allow_empty_file=False, \ validators=[FileExtensionValidator(allowed_extensions=valid_extensions)]) file_type = forms.ChoiceField(choices=file_type_choices, widget=forms.Select(attrs={"class": "form-control"})) source_language = forms.CharField(max_length=30,\ widget=forms.TextInput(attrs={"class":"form-control", "placeholder": "English"})) target_language = forms.CharField(max_length=30, \ widget=forms.TextInput(attrs={"class":"form-control"})) I also added bootstrap CDN links in the templates. And just for surety, added the following in settings.py file of the project: python CRISPY_TEMPLATE_PACK = 'bootstrap5' Also, its curious to see that placeholder is also not working. I don't see particular reason behind this. -
Django runserver crashes on chunked encoding
I am writing a Java client that posts a multipart/form-data request to a Django server. But Django logs an error (though the request continues to the view, just without the body). When Django is deployed behing Nginx it is working normally, which is why I suspect Django's runserver setup may not be able to handle it. The error is: code 400, message Bad request syntax ('23'). This 23 is part of the transfer-encoding: chunked that is being sent. I didn't find any reference that Django isn't able to understand chunked encoding so I am lost where this is going wrong. Java client, using Spring's WebClient: public void saveRecording(String token, Integer songId, String fileLocation) { var recording = new FileSystemResource(new File(fileLocation)); var data = new MultipartBodyBuilder(); data.part("songId", songId.toString(), MediaType.TEXT_PLAIN); data.part("recording", recording, MediaType.APPLICATION_OCTET_STREAM); webClient.post() .header("Authorization", token) .body(BodyInserters.fromMultipartData(data.build())) .retrieve() .toBodilessEntity() .block(); } Wireshark capture, notice the 23 after Content-Type which is part of the chunked encoding and which I believe is the reason for the error. POST /recording/save-recording/ HTTP/1.1 accept-encoding: gzip user-agent: ReactorNetty/1.1.5 host: localhost:8000 accept: */* transfer-encoding: chunked Authorization: 123e4567-e89b-12d3-a456-426614174000 Content-Type: multipart/form-data;boundary=GlYowTnlo8QZLczdlpPL6wSEhFBv1DA 23 --GlYowTnlo8QZLczdlpPL6wSEhFBv1DA 5e Content-Type: text/plain Content-Disposition: form-data; name="songId" Content-Length: 1 1 1 2 23 --GlYowTnlo8QZLczdlpPL6wSEhFBv1DA 8f Content-Type: audio/mpeg Content-Disposition: form-data; … -
Unable to render a D3 chart to my web page in a Django project
I have a Django project where a form takes a file from the user (.json), processes this file, populates a post-gres database, and then at the front-end I pull some of that data back out to render a table - this works well so far. However, I also want to draw a D3 bar chart that also pulls data from my db and plots it, this is what I am currently unable to do. I have created the chart in full, and it works correctly when I render it on its own template html. Though when I attempt to draw the chart beneath my main data table (on the page I need it to appear on), I am faced with problems. The issue is, I cannot get the d3 chart to appear on my main web page, anywhere. Here is the error message: Uncaught SyntaxError: Expected property name or '}' in JSON at position 1 at JSON.parse (<anonymous>) at d3bar.js:1:19 It looks like there's an issue with the formatting if the incoming json data, or least the object that emanates from the initial json data. I find this confusing because as I said, I can correctly display the d3 chart … -
QueryDict is empty, after received from the POST request
I used axios to send a POST request, here is my code: register: function (){ console.log("register start"); if (this.password !== this.confirmPassword) { alert("The Password IS DIFFERENT THAN CONFIRM PASSWORD!"); } else { console.log("register start"); const data = { firstname: this.firstname, lastname: this.lastname, username: this.username, email: this.email, password: this.password, confirmPassword: this.confirmPassword } console.log(data) axios.post("/register", data) .then(res => { alert("Register Success!"); console.log(res); }) .catch(error => { console.log(error); }) } } And here is the code for received the POST request: def register(request): try: # receive POST request, queryDict object if request.method == "POST": print("Post Request Received") user_info = request.POST print(request.body) print(user_info) except Exception as e: print("Error", e) return render(request, "error.html", context=e) return render(request, "register.html") However, I keep received an empty QueryDict but I did comform that the return type is Json and it does received something, here is the output: Post Request Received b'' QueryDict} I had found a method, which is replicate the POST request and decode it. Here is the code: if request.method == "POST": print("Post Request Received") request_data = request.body user_info = request_data.decode("utf-8") print(user_info) Here is the output, after the changed: Post Request Received {"firstname":"First Name","lastname":"Last Name","username":"username123","email":"username123@gmail.com","password":"12345678","confirmPassword":"12345678"} [25/Mar/2023 16:07:07] "POST /register HTTP/1.1" 200 5347 Post Request Received ------WebKitFormBoundarycXOVuwbkiaqZTvQy-- [25/Mar/2023 … -
mysql path environment variable not working
I am trying to connect mysql to the back end of my project in Django When I use the command mysql -u root -p I receive this error: 'mysql : The term 'mysql' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.' I have installed mysql, configured it and additionally set the PATH in the environment variables windows panel. C:\Program Files\MySQL\MySQL Shell 8.0\bin\ when I search this error I only see to change the PATH but it is already done, I'm not sure why it isn't working. -
How can I retrieve a value from my PostgreSQL database and print it in my html website?
I am trying to take information that is submitted by the user in a form, and make a query to my PostgreSQL database to retrieve the average cost of the selected repair. While I can retrieve the value, I can only do so in the scope of the (if request.method == POST) statement. Is there a way I can retrieve the cleaned_data from my form and filter the database entries outside of the scope? Here is the code in my views.py file that contains the problematic code: from django.http import JsonResponse from django.shortcuts import render, redirect, get_object_or_404 from .forms import ModelCreationForm from .models import Make, Model, Car, Repair, Cost def model_create_view(request): form = ModelCreationForm() if request.method == 'POST': form = ModelCreationForm(request.POST) if form.is_valid(): form.save() cost_data = getFormData(request, form) return redirect('model_add') return render(request, 'models/home.html', {"form": form}) def getFormData(request, form): year = form.cleaned_data['year'] make = form.cleaned_data['make'] model = form.cleaned_data['model'] repair = form.cleaned_data['repair'] form_data = Cost.objects.filter(year = year, make = make, model = model, repair = repair) return render(request, 'models/home.html', {"cost": form_data[0]}) def model_update_view(request, pk): car = get_object_or_404(Car, pk=pk) form = ModelCreationForm(instance=car) if request.method == 'POST': form = ModelCreationForm(request.POST, instance=car) if form.is_valid(): form.save() return redirect('model_change', pk=pk) return render(request, 'models/home.html', {'form': form}) def load_models(request): … -
custom user model Django - AUTH_USER_MODEL refers to model that has not been installed
I created my custom user model which inherits from AbstractBaseUser. My model is located in api/models/userModel.py file. Api is the name of my application which I registered in INSTALLED_APPS in settings.py. I register my custom user model in settings.py with AUTH_USER_MODEL='api.UserAccount'. My problem is whenever I try to py manage.py makemigrations I get error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.UserAccount' that has not been installed I tried to delete all migrations files and reset my DB but it doesn't work. Do you have any idea what is wrong ?