Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django 3.2 inline_formset with related models many to one
I'd like to make my form look like this enter image description here but my following this approach my output looks like this enter image description here Here are my models class Question(models.Model): id = models.BigAutoField(primary_key=True) question = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=False) class Declaration(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='declarations', on_delete=models.CASCADE) created_at = models.DateTimeField(verbose_name='created', auto_now_add=True) class Checklist(models.Model): id = models.BigAutoField(primary_key=True) declaration = models.ForeignKey(Declaration, related_name='checklist_declarations', on_delete=models.CASCADE) question = models.ForeignKey(Question, related_name='checklist_questions', on_delete=models.CASCADE, limit_choices_to={'is_active': 'True'}) is_yes = models.BooleanField() forms class ChecklistInlineFormSet(BaseInlineFormSet): def clean(self): if any(self.errors): #Don't bother validating the formset unless each form is valid on its own return questions = [] for form in self.forms: question = form.cleaned_data.get('question') if question in questions: raise ValidationError(_('Question must be distinct'), code='invalid') questions.append(question) class HorizontalRadionRenderer(forms.RadioSelect): def render(self): return mark_safe(u'\n'.join([u'%s\n' % w for w in self])) class ChecklistForm(forms.ModelForm): ANSWER_CHOICES = [ (True, 'Yes'), (False, 'No') ] is_yes = forms.TypedChoiceField( choices=ANSWER_CHOICES, coerce=lambda x: x == 'True', widget=forms.RadioSelect, required=True ) class Meta: model = Checklist fields = ['question', 'is_yes'] views declaration.views def checklist(request): FS_PREFIX = 'question_fs' user = request.user result = "" if request.method == 'POST': # Use your custom FormSet class as an argument to inlineformset_factory formset = inlineformset_factory(Declaration, Checklist, form=ChecklistForm, fk_name='declaration', formset=ChecklistInlineFormSet) declaration = Declaration() … -
How to get id of a dynamic input field in javascript
I want to create a dynamic form where I also apply JavaScript to the dynamic elements. What I want to do right now is figure out which field (stored in array or whatever data structure) in JavaScript has been clicked so that I can apply the script to that particular field. The HTML looks like this: <div class="triple"> <div class="sub-triple"> <label>Category</label> <input type="text" name="category" id="category" placeholder="Classes/Instances" required/> <ul class="cat-list"></ul> </div> <div class="sub-triple"> <label>Relation</label> <input type="text" name="relation" id="relation" placeholder="Properties" required/> <ul class="rel-list"></ul> </div> <div class="sub-triple"> <label>Value</label> <input type="text" name="value" id="value" placeholder="Classes/Instances" required/> <ul class="val-list"></ul> </div> </div> This "triple" div is dynamic and I want to create as many "triples" as the user wants, that also means the input fields of inside the "triple" section increase as well. I'm confused on how to add javascript to one element of the input. For example I have inputs: category, relation and value and the user wanted 2 or more triples then the input ids could look like category2, relation2 and value2 or something similar to that. let category = document.getElementById("category"); category.addEventListener("keyup", (e) => { removeElements(); listDown(category, sortedClasses, ".cat-list") }); If I lets say clicked on category2 for instance how do I tell that to … -
django how to call view function to template via button
I want to download a csv file and my form is not working. when I try to enter in the URL http://xxx.xx.xx.x:8080/report/ it downloads the file my index.html <table id="tb1" border=1 align="center"> <tr> <th>Permanent Male Staff</th> </tr> <tr> <td><form action="/report/" method=""> <input type="button" value="{{perma_male_staff}}"/> </form></td> </tr> </table> views.py def some_view(request): response = HttpResponse( content_type='text/csv', headers={'Content-Disposition': 'attachment; filename="somefilename.csv"'}, ) perma_male_staff = HsHrEmployee.objects.filter(emp_status=1, emp_gender=1, eeo_cat_code=2).select_related('job_title_code') t = loader.get_template('my_template_name.txt') c = {'data': perma_male_staff} response.write(t.render(c)) return response url.py from rms.views import some_view urlpatterns = [ path('admin/', admin.site.urls), path('report/', some_view) ] -
How to dynamically set the sorting parameter order with null last in django API?
I am receiving sort_by and sort_order as query parameters into our Django API. I have the logic originally like this: class Users: queryset = ... sort_by = self.request.query_params.get('sort_by') sort_order = self.request.query_params.get('sort_order') if sort_order == "desc": sort_by = "-" + sort_by def get_queryset(self): return queryset.order_by(sort_by, "id") The issue I ran into is that when I sort by descending order by a specific parameter, the null values will show up first. I want all null values to be last no matter if I'm sorting asc or desc. I saw that there's a function from the Django docs here but that would mean that I have to have a different function call for whether it's ascending or descending which would make it not elegant: if sort_order == 'desc': return queryset.order_by(F(sort_by).desc(nulls_last=True), "id") else: return queryset.order_by(F(sort_by).asc(nulls_last=True), "id") Is there a better way of doing this? -
Prefetch not working for ForeignKey's related_name? (Results in n + 2 queries)
# models.py class Author(models.Model): name = CharField() class Book(models.Model): title = CharField() author = ForeignKey(Author, related_name="books") # serializer.py class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ["id", "title"] class AuthorSerializer(serializers.ModelSerializer): books = serializers.SerializerMethodField() class Meta: model = Author fields = ["id", "name", "books"] def get_books(self, obj): qs = obj.books return BookSerializer(qs, many=True).data # views.py class AuthorList(generics.ListAPIView): queryset = Author.objects.all().prefetch_related("books") serializer_class = AuthorSerializer Seems relatively straightforward but I'm still getting n + 2 queries? I would expect to get just 2 queries - one for all the authors and one for all the books? If I actually simplify my view's queryset to just Author.objects.all(), I get n + 1 queries. -
Choosing a nested serializer from a dropdown in Django REST Framework
I want to be able to POST / PUT a nested serializer related to an already existing other resource by choosing that other resource from a drop-down button. My current situation, which works but is not ideal to me is the following: I have the following models, with a Dataset existing for a given Project and a given Datasource. Project is a Model which exists independently of Datasource and of Dataset. Its url is projects/projectid/ Datasource is a Model which exists independently of Project and of Dataset. Its url is datasources/datasourceid/ Dataset needs a Project and a Datasource to be created. Its url is projects/projectid/datasets/datasetid class Project(models.Model): """Class that models analytical projects""" title = models.CharField(max_length=300) description = models.TextField(null=True) def __str__(self): return self.title class Datasource(models.Model): """Class that models datasources under projects""" title = models.CharField(max_length=300) description = models.CharField(max_length=300) def __str__(self): return self.title class Dataset(models.Model): """Class that models datasets under projects""" title = models.CharField(max_length=300) project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='datasets') datasource = models.ForeignKey(Datasource, on_delete=models.CASCADE, related_name='datasources') (...) def __str__(self): return self.title Here are the serializers I first created for Datasource and Dataset: class DatasourceSerializer(serializers.ModelSerializer): class Meta: model = Datasource fields = ['id', 'title', 'description'] class DatasetSerializer(serializers.ModelSerializer): queryset = Datasource.objects.all() # datasource = DatasourceSerializer(many=False, read_only=False) , … -
How to fix heroku command not found error
So i've been working on a prject and I'm about to deploy it.I don't get any errors while building but and i get asked to view app after but when i do the web page shows a heroku Application error. I tried running heroku logs --tail --app appname and it shows me the logs and i can see this error which i can't seem to fix. bash: gunicorn: command not found I have my Procfile and with the following command web: gunicorn MFLS.wsgi If any other information is needed I ill be happy to provide. -
Is is possible to order queryset by last word in CharField?
Say I have a Person object with a fullname CharField. Is it possible to filter a queryset by the LAST word in fullname? (And if fullname is just one word, then just use that one word.) E.g. Person.objects.create(fullname="Zoey Aardvark") Person.objects.create(fullname="Brian") Person.objects.create(fullname="Aaron Christopher") Is ordered as Aardvark, Brian, Christopher: Zoey Aardvark Brian Aaron Christopher Or would it frankly be more efficient to just sort the serialized JSON data on my frontend via JavaScript? -
Display the number of students who has enrolled in the course the instructor has created
I am building a website where the instructor can create courses and students can enroll to the courses. I am facing a problem when displaying the number of students that has enrolled to the courses that an instructor has. I am not sure how to get the number of students that has enrolled to the courses that the instructor has. Please help T.T models.py class Course(models.Model): user = models.ForeignKey(Users, on_delete = models.CASCADE) media = models.ImageField(upload_to = 'media/course') title = models.CharField(max_length=300, null = False) subtitle = models.CharField(max_length=500, null = False) description = models.TextField(max_length=5000, null = False) language = models.CharField(max_length=20, null = False, choices=LANGUAGE) level = models.CharField(max_length=20, null = False, choices=LEVEL) category = models.CharField(max_length=30, null = False, choices=CATEGORY) subcategory = models.CharField(max_length=20, null = False) price = models.FloatField(null = True) roles_responsibilities = models.TextField(max_length=2500, null = False) timeline_budget = models.TextField(max_length=250, null = False) req_prerequisite = models.TextField(max_length=2500, null = False) certificate = models.CharField(max_length=5, null = False, choices=CERTIFICATE) slug = AutoSlugField(populate_from='title', max_length=500, unique=True, null=True) class Enrollment(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return "%s %s" % (self.student, self.course) views.py def instructorDashboard(request): user = Users.objects.all() user_id = Users.objects.get(user_id=request.user) course = Course.objects.filter(user = user_id) course_count = course.count() context = {'user':user, 'course_count': course_count} return render(request, … -
Image handling with django-summernote
The image uploads and appears on the text editor but when I post, the image is not on the page. Inspecting the page, I find that the tag is the but no source. settings.py DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' LOGIN_URL = 'users:login' import django_heroku django_heroku.settings(locals()) if os.environ.get('DEBUG') == 'FALSE': DEBUG = False elif os.environ.get('DEBUG') == 'TRUE': DEBUG = True MEDIA_URL = '/media/django-summernote/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/django-summernote/') SUMMERNOTE_THEME = 'bs4' X_FRAME_OPTIONS = 'SAMEORIGIN' -
PROTECT vs RESTRICT for on_delete (Django)
I read the django documentation about PROTECT and RESTRICT to use with "on_delete". PROTECT Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError. Example: class MyModel(models.Model): field = models.ForeignKey(YourModel, on_delete=models.PROTECT) RESTRICT Prevent deletion of the referenced object by raising RestrictedError (a subclass of django.db.IntegrityError). Unlike PROTECT, deletion of the referenced object is allowed if it also references a different object that is being deleted in the same operation, but via a CASCADE relationship. Example: class MyModel(models.Model): field = models.ForeignKey(YourModel, on_delete=models.RESTRICT) To some degree, I could understand the difference between PROTECT and RESTRICT but not exactly so what is the difference between PROTECT and RESTRICT exactly? and when should I use them? -
How to retrieve value from through model using django-tables2?
I have the models below that allows users to create a playlist with many tracks associated to a playlist. I'd like to create a table with django-tables2 that shows 3 columns: the priority of the track, the artist and title in the playlist. How can I write the render_priority function to retrieve the priority value from PlaylistTrack model for the associated track for the playlist? models.py class Artist(models.Model): name = models.CharField(max_length=100) class Track(models.Model): artist = models.ForeignKey( Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist", related_name="tracks", ) title = models.CharField(max_length=100, verbose_name="Title") class Playlist(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False ) name = models.CharField(max_length=50) tracks = models.ManyToManyField(Track, through="PlaylistTrack") description = models.TextField(blank=True, max_length=200) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) slug = AutoSlugField( populate_from="name", unique=True, editable=True, slugify=custom_slugify ) class PlaylistTrack(models.Model): track = models.ForeignKey(Track, on_delete=models.CASCADE, null=True) playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True) priority = models.PositiveSmallIntegerField(default=1) class Meta: ordering = ["priority"] tables.py class PlaylistTable(tables.Table): def __init__(self, *args, **kwargs): super(PlaylistTable, self).__init__(*args, **kwargs) def render_priority(self): pass # get priority value from PlaylistTrack model for track in playlist priority = tables.Column( verbose_name="#" ) class Meta: model = Track fields = ( "priority", "artist", "title", ) -
Django - Can't retrieve Many to Many field from Queryset
I have the following code: exercises = Exercise.objects.filter(teacher=request.user.id).values('id', 'question', 'ans1', 'ans2', 'ans3', 'correct', 'unit', 'resol', 'theme', 'img') This works fine, but the "theme" is a Many to Many Field, the format returns { ..., theme: value } instead of { ..., theme: [value1, value2] } What should I implement to get the desierd format? -
Login in Django built in authentication system with Vue - What should I return after login(request, user)?
I am trying to develope a SPA with Vue in the frontend and Django (without REST framework) in the backend. My view requires the user to be logged in with the @login_required decorador. I also have the sign_in view to login the user, but I don't know what I should return to the frontend after the login(request, user). My views.py @csrf_exempt def signin(request): email = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=email, password=password) if user is not None: login(request, user) ??? @login_required @csrf_exempt def usinas(request): do stuff... -
action decorator not calling method in DRF?
so I have a route api/reviews it works fine for basic CRUD operations but according to DRF documentation, I can add extra actions to post, put, patch requests by using the @action decorator. the route is: POST domain/api/reviews data=irrelevent JSON # reviews/<uuid:id> && reviews # Provides CRUD + List interface for Reviews class ReviewView(viewsets.ModelViewSet): permission_classes = [IsPosterOrSafeOnly] queryset = Review.objects.all() serializer_class = ReviewSerializer pagination_class = Pagination @action(detail=False, methods=['post','put', 'patch'], serializer_class=ReviewSerializer) def rating(self, request): print("100: ", request) from what I understand the way this works is that when I do a post request to the reviews route it will do the post like it normally does and it will do the task in the action decorator. so I tried doing a post request to see if the code inside the 'rating' method gets run and it does not. I have tried setting detail to both True and False including the pk. nothing really seems to work. -
Issue connecting PostgreSQL db to Heroku
I am currently trying to deploy a Python/Django app to Heroku. The build was successful however, I am attempting make a migration to an established postgresql database to connect it to Heroku remote. When I run: heroku run python manage.py migrate I get the following error: ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The Django environment is currently activated in my terminal screen. I ran python to get the version type then ran print(sys.path which showed the Django environment listed. Just for giggles I ran pip install django once again, where a message stating requirement already satisfied came up. So it looks like django is installed, my virtual environment is working, but I cannot make the migration for Heroku... Any advice appreciated. -
Django form field help_text rendering problem
I have the following template: {% if field.help_text %} <p class="helptext"> { field.help_text|safe }} </p> {% endif %} The problem is: help_text is being rendered outside the p tag for a password field. <p class="helptext"> </p> <ul> <li>...</li> <li>...</li> </ul> Am I doing something wrong? Am I missing something? How can I apply "helptext" class to the help_text provided by the passwordfield? -
Django: Instantiating a form in a custom class based view
This is my first post, and I am new to Django so go easy on me! I am trying to convert my function based views into class based views so I can reuse the views easily in other apps, and am struggling with instantiating a form inside the class. I have the following function based view: def object_create(request): def get_date(): today = datetime.datetime.now() enquiry_date = today.strftime("%d/%m/%Y") return enquiry_date initial_dict = { "account_handler" : request.user, "prep_location" : request.user.profile.location, "load_location": request.user.profile.location, "return_location": request.user.profile.location, "status":"Enquiry", "enquiry_date": get_date() } object_form = QuoteForm(request.POST or None, initial = initial_dict) context = { 'form': object_form, } if request.method == 'GET': return render(request, "rental_quotes/form.html", context ) # If we are saving the form if request.method == 'POST': if object_form.is_valid(): new_object = object_form.save() context = { 'object': new_object } found_count = Quote.objects.all().count() request.session['rental_quotes_current_index'] = (found_count-1) request.session['rental_quotes_found_count'] = found_count new_page = json.dumps({ 'url': reverse("rental_quotes-detail", args=[new_object.id]), 'index': found_count-1, 'found_count': found_count, 'content': render_to_string('rental_quotes/pages/detail.html', context) }) return JsonResponse(new_page, safe=False, status=200) else: return render(request, 'rental_quotes/form_block.html', context ) Which works fine. In my attempt at creating a class I can import into a class based view I have: class ObjectCreate(LoginRequiredMixin, View): def get_date(): today = datetime.datetime.now() enquiry_date = today.strftime("%d/%m/%Y") return enquiry_date def get (self, request): … -
urlpatterns wont match the url path
urlpatterns = [ path('cart', auth_middleware(CartViewAndAdd.as_view()) , name='cart'), path('viewcart', auth_middleware(CartOnlyView.as_view()) , name='viewcart'), ] <th><a href="/cart?product={{product.id}}&seller={{price.seller}}" class="btn btn-primary">Add to Cart</a></th> This code was working earlier. I seem to have messed with it. What could be wrong -
how to remember the selected radio button option in diango
i asked this question previously and didn't get any help/solution. so i'm asking again. i'm trying to make sure that even if the user refresh the page or goes back and comes back to that page, the radio button is still the same as what the user selects. N.B: the value of the radio button is saved in sessions <div class="col-md-1 ps-md-1"> <input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}" value="{{option.id}}"> </div> Ajax $('input[type=radio][name=deliveryOption]').on('change', function(e) { e.preventDefault(); $.ajax({ type: "POST", url: '{% url "checkout:cart_update_delivery" %}', data: { deliveryoption: $(this).val(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { document.getElementById("total").innerHTML = json.total; document.getElementById("delivery_price").innerHTML = json.delivery_price; }, error: function (xhr, errmsg, err) {}, }); }); my view def cart_update_delivery(request): cart = Cart(request) if request.POST.get("action") == "post": delivery_option = int(request.POST.get("deliveryoption")) delivery_type = DeliveryOptions.objects.get(id=delivery_option) updated_total_price = cart.cart_update_delivery(delivery_type.delivery_price) session = request.session if "purchase" not in request.session: session["purchase"] = { "delivery_id": delivery_type.id, } else: session["purchase"]["delivery_id"] = delivery_type.id session.modified = True response = JsonResponse({"total": updated_total_price, "delivery_price": delivery_type.delivery_price}) return response when i added a django templating if statement, it kinda work but the radio button is always remember on the last radio button when refreshed. {% for option in deliveryoptions %} <input class="align-middle h-100" type="radio" {% if deliveryoption == %} … -
Django Data Model / Database design problem
Quite new at database design and I'm trying to understand what will be the best way to design a database to be used in django. For a project management app for film vfx work I want to track all the versions and task assigned to artost. My problem is how to differentiate between different worflows keeping the same database. Typically the workflow for a Feature Film is: Project->Sequences->Shots->Tasks->Versions. while a workflow for a tv series is slightly different: Project->Season->Episode->Sequences->Shots->Versions So basically in the first case we don't need Entities / Models for Sesons and Episodes and shots will be contained directly in Sequences. What would be the best way to achieve this model? Should I make 2 apps for different workflows and copying the same classes into each app Models? thanks in advance. https://drive.google.com/file/d/1L3XwtvMhNM3AzotSiAE7yT495QTqBcVs/view?usp=sharing Obviously this simple code would not work as Episode is always need to be define: class Project(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Season(models.Model): name = models.CharField(max_length=2) project_id = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.name class Episode(models.Model): name= models.CharField(max_length=3) season_id = models.ForeignKey(Season, on_delete=models.CASCADE) def __str__(self): return self.name class Sequence(models.Model): name = models.CharField(max_length=3) episode_id = models.ForeignKey(Episode, models.CASCADE) project_id = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.name … -
Using cache invalidation for a user permission django
I am currently working on a cache for user permissions in Django. The structure for enabling users/organizations access to certain areas of the application looks like this: Meaning a User can either have access to a feature via his organization or as a user himself. What I want is a key-value cache that safes all the features a user/organization member has access to as a string. So whenever a user request access to a certain view the permission class first fetches all features for that user from the cache. I have implemented that as follows: class UserPermissionCache: def __init__(self): self.redis = StrictRedis( host=settings.REDIS_RATE_LIMITING_URL, port=settings.REDIS_RATE_LIMITING_PORT, db=settings.REDIS_RATE_LIMITING_DB, ) self.validation = datetime.now().strftime("%m%d%Y%H%M%S") def status_key(self, member): return f"user:features:{self.validation}:{member.uuid}" def set_user_features(self, user, key): features = Feature.objects.filter( Q(enabled_for_all=True) | Q(enabled_for_users=user) | Q(enabled_for_organizations=user.only_organization) ) result = FEATURE_STRING_SEPERATOR.join( feature.code for feature in features ) if not self.redis.set(key, result, settings.USER_FEATURES_TIMEOUT): logging.warning(f"Couldn't set features for user: {user.uuid}") return result def get_user_features(self, member): key = self.status_key(member) try: result = self.redis.get(key) except ConnectionError: logger.error( "ConnectionError, Failed to fetch feature permission for user", extra={"member": member.uuid}, ) return None if result is None: result = self.set_user_features(member, key) result = result.split(FEATURE_STRING_SEPERATOR) else: result = result.decode("utf-8").split(FEATURE_STRING_SEPERATOR) return result def reset_user_features(self, sender, **kwargs): for member in organization_members: … -
Converting to using URL router is causing a ImproperlyConfigured exception
I have been working through the Django Rest Framework tutorial and on the very last step I am encountering the error: Exception Type: ImproperlyConfigured. Exception Value: Could not resolve URL for hyperlinked relationship using view name "snippet-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. When trying to view either /settings/ or /users/ (visiting any user pages yields the same exception but with "user-detail" in place of "snippet-detail") as well as any specific indices of them, etc. All that works is root and login. All my code thus far has been working fine and I'm very confused as to why copy-pasting from the tutorial would yield such catastrophic results In comparing my snippets files with those available on the tutorial's repo I have not been able to find any significant difference (all that I've found is inconsistencies in whitespace). That being said, here is the code I'm using. snippets/views.py: from snippets.models import Snippet from snippets.serializers import SnippetSerializer, UserSerializer from rest_framework import generics, permissions from django.contrib.auth.models import User from snippets.permissions import IsOwnerOrReadOnly from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import renderers … -
How to save data from a webpage into Django database without using a form?
I am trying to save data from my webpage into my Django database. The data does not come from a form - I have built a web-based game with a timer and I would like to store the end value of the timer in my database for each game once the user presses the 'finish' button. The data doesn't come from a form as the timer increments automatically every second and stops when the finish button is pressed - how would i go about saving this to my django database? this is what the django model looks like: class Games(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) startTime = models.DateTimeField(auto_now_add=True) solveTime = models.IntegerField() hintsCount = models.IntegerField() difficultyChoices = [ ('E', 'easy'), ('M', 'medium'), ('H', 'hard') ] difficulty = models.CharField(max_length=2, choices=difficultyChoices, default='M') so for example i would like to be able to send a POST request to the server with {timer: 300, hints:2} which can then be saved with the above model thanks :) -
Deployed django app error: Relation does not exist
I deployed a django app using a postresql database with Heroku. The app works perfectly on my local machine but when I want to create a user or to login using the deployed app, I run into the following error: ProgrammingError at /register/ relation "register_user" does not exist LINE 1: SELECT (1) AS "a" FROM "register_user" WHERE "register_user"... ^ Request Method: POST Request URL: https://the-gecko.herokuapp.com/register/ Django Version: 4.0.3 Exception Type: ProgrammingError Exception Value: relation "register_user" does not exist LINE 1: SELECT (1) AS "a" FROM "register_user" WHERE "register_user"... ^ Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py, line 89, in _execute Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Mon, 21 Mar 2022 19:59:58 +0000 I believe this error has something do to with my postgres database, but I don't know what relevant code to share in that case. Please, let me know if you have any idea how to solve that issue.