Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: authenticate user using another application
I have two django applications, A and B, which make use of the same User model. The User model is in A , and B sends a request to A for user authentication as follows: # Application B: url = ... # Application A's url data = {'username':request.POST.get('username'), 'password':request.POST.get('password')} resp = requests.post(url, data=data) # A authenticates with the username and password if resp.text == 'True': # login the user: how? user = ... else: # Login fails My question: how do I create an authenticated user in B? -
How can I pull out a row in a GROUP BY Django query?
I have a table like this: EVENT ------------- user_id thumbnail_name 0 event/abc.jpg 0 event/efg.jpg 0 event/xyz.jpg 1 event/lmn.jpg 1 event/opq.jpg 2 event/rsf.jpg How can I GROUP BY user_id and retrieve an arbitrary thumbnail? Expected output: [ {user_id: 0, thumbnail_name: event/abc.jpg}, {user_id: 1, thumbnail_name: event/lmn.jpg}, {user_id: 2, thumbnail_name: event/rsf.jpg}, ] Is this even possible in SQL? -
Django save() method filling a certain field with None when saving with same id
I have this model. class Country(models.Model): countryname = models.TextField(null=True) countryincharge = models.ForeignKey(Employees, on_delete=models.CASCADE,null = True) createdby = models.TextField(null=True) createdtime = models.TextField(null=True) modifiedby = models.TextField(null=True) modifiedtime = models.TextField(null=True) deletedby = models.TextField(null=True) deletedtime = models.TextField(null=True) isdeleted = models.IntegerField(null=True) tenantid = models.TextField(null=True) And create and update functions as following. #Create def countrycreate(request): if request.user.is_authenticated: if request.method == 'POST': id = request.POST.get('id') modelwithdata = Country( countryname=request.POST.get('countryname'), countryincharge_id=request.POST.get('countryincharge'), createdtime = timezone.now(), createdby = request.user.id ) if Country.objects.filter(countryname=request.POST.get('countryname')).exists(): messages.info(request, 'Country already exists!') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: modelwithdata.save() return redirect('/admin/countrylistview') #Update def countryupdate(request): if request.user.is_authenticated: if request.method == 'POST': id = request.POST.get('id') modelwithdata = Country( countryname=request.POST.get('countryname'), countryincharge_id=request.POST.get('countryincharge'), modifiedtime = timezone.now(), modifiedby = request.user.id ) modelwithdata.id = id modelwithdata.save() return redirect('/admin/countrylistview') The problem is when a record is created the createdtime value is saved as intended. But when running the update function the createdtime value is set to None. For unknown reasons. Other fields are working fine. The db is SQLite. Same behaviour happens when use DateTimeField(auto_now_add=True, null=True) and DateTimeField(auto_now=True, null=True). -
django-rest-auth get username from rest-auth/user
I want to retrieve the user details for displaying the username of the user who is logged-in I need to fetch the username from "http://127.0.0.1:8000/rest-auth/user/" from django-rest-auth I am new to reactjs and tried the authentication which was successfully but couldn't get pass this. I have tried this so far axios.get(`http://127.0.0.1:8000/rest-auth/user/`, { headers: { 'Authorization': "token " + localStorage.getItem('token') } } ).then(res => { console.log(res) }).catch(Error => { console.log(Error) }) which returns the forbidden 403 error; Errors Error: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61) Also in the above code I also specified the headers in the following manner headers: { 'Authorization': "token key_from_DRF " } but no luck I have also tried this axios.get(`http://127.0.0.1:8000/rest-auth/user/`, { headers: { 'Content-Type': 'application/json' } } ) .then(res => { console.log(res) }).catch(Error => { console.log(Error) }) which returns the same error as before. How should I execute this request successfully? -
profile update from admin site only
I'm working on a personal portfolio project. I want to add/update the profile dynamically. What I want is to have one profile image and one personal image(about_pic). I want to update them from the admin section/site. I only want to add one profile object. model.py from sorl.thumbnail import ImageField class Profile(models.Model): profile_pic = ImageField(upload_to='profile', blank=True, null=True) background_pic = ImageField(upload_to='profile', blank=True, null=True) # you can leave it for now about_pic = ImageField(upload_to='profile', blank=True, null=True) views.py def home_view(request, tag_slug=None): profile = Profile.objects.all() return render(request, 'mypf/index.html', { 'profile':profile }) index.htm # profile pic {% for p in profile %} <img src="{% if p.profile_pic %} {{ p.profile_pic.url }} {% else %} {% static 'img/natsu.jpg' %} {% endif %}" class="img-fluid rounded-circle"> {% endfor %} # about pic {% for p in profile %} <img src="{% if p.about_pic %} {{ p.about_pic.url }} {% else %} {% static 'img/img2.jpg' %} {% endif %}" width="150px" height="200px" class="img-thumbnail"> {% endfor %} Also, How can I do efficiently without using two loops since there is another HTML code like div, main, section. Is there another way? -
Autocomplete with username and image
I am using autocomplete to dropdown username and user profile picture, i am getting the username correctly but profile picture is showing default images instead of the user profile picture. I do not know if i am passing this right in jquery. And also how to make z-index in autocomplete. Here is what i have tried: Model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) profile_pic = models.ImageField(upload_to='ProfilePicture/', default="ProfilePicture/user-img.png", blank=True) Views: def home(request): all_users = User.objects.values_list('username', flat=True) all_img = Profile.objects.all().distinct() context = { 'all_users': all_users, 'all_img': all_img, } jQuery: <script type="text/javascript"> //TAG AUTOCOMPLETE FORM DROPDOWN USER NAMES $(function() { var availableTags = [ {% for user in all_users %} "{{user|safe}}", {% endfor %} ]; $(".autocomplete").autocomplete({ source: availableTags, }).data("ui-autocomplete")._renderItem = function (ul, item) { var image = "<div>{% for img in all_img %}{% if img.profile_pic %}<img src='{{ img.profile_pic.url }}'{% endif %}{% endfor %}" + " height='55' /> " + item.label + "</div>"; return $("<li></li>") .data("item.autocomplete", item) .append(image) .appendTo(ul); }; }); </script> -
HOW I GET USERNAME
can you tell me any one how i get username from user.. because My condition is not working in below code /....................................................................................................... e.html <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Welcome {{request.user}} </a> views.py def registration_view(request): # if this is a POST request we need to process the form data template = 'home/login.html' if request.method == 'POST': print("post") # create a form instance and populate it with data from the request: form = RegisterForm(request.POST) # check whether it's valid: if form.is_valid(): print("okk valid") if User.objects.filter(username=form.cleaned_data['username']).exists(): messages.error(request,'Username already exists') return render(request, template, { 'form': form, 'error_message': 'Username already exists.' }) elif User.objects.filter(email=form.cleaned_data['email']).exists(): messages.error(request,'Email already exists') return render(request, template, { 'form': form, 'error_message': 'Email already exists.' }) elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']: messages.error(request,'Password do not match ') return render(request, template, { 'form': form, 'error_message': 'Passwords do not match.' }) else: # Create the user: user = User.objects.create_user( form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password'] ) user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] # user.date = form.cleaned_data['date'] print("save reached") user.save() # Login the user login(request, user) messages.success(request,"Created your account succcessfully in thumbsapp ") return redirect('home') -
Choice for each item in field in models
If i have 5 diffent sport in Sports then in Intrest model i want to put level to each of those 5 sports seprately,and want to print.How to do it. exampl:cricket=Advance Football=Beginner like this class Sports(models.Model): Sport=models.CharField(max_length=30) class User(models.Model): user=models.CharField(max_length=30) class Intrest(models.Model): user_name=models.Foreignkey(User,on_delete=models.CASCADE) sport=models.Foreignkey(Sports,on_delete=models.CASCADE) LEVEL=( ('1','Beginer'), ('2','Intermediate'), ('3','Advance'), ('4','Nevel Played'), ) Level=models.CharField(max_length=30,choices=LEVEL)1','Beginer'), ('2','Intermediate'), ('3','Advance'), ('4','Nevel Played'), ) Level=models.CharField(max_length=30,choices=LEVEL) -
Django Rest framework in android backend
Is Django REST framework a good choice for an Android backend? and do you have any documentation (step by step) on how to connect django rest framework on android? i dont have problem in django, my concern is i dont know how to connect the android app tp django. -
How to create a comment box with user mention feature in django?
I am trying to create a comment box for my django app with user mention feature. When a user trying to comment with "@" then the list of users should be listed and selected for mentioning. Also when a user is mentioned in comment then a notification should be sent to the user. I searched for implementing this. But I am getting only a regular comment box. Is there any way to implement. Also you can suggest any available app library for comments with this feature. Thank you in advance. -
Unable to switch Django's databases settings using environment variables
I am trying to switch the database settings of my Django application using environment variables. So I made few changes in my settings.py file like this - print(os.environ.get('DATABASE')) if os.environ.get('DATABASE') == "DEVELOPMENT": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } else: print("i m here") DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('DATABASE_NAME'), 'USER': os.environ.get('DATABASE_USERNAME'), 'PASSWORD': os.environ.get('DATABASE_PASSWORD'), 'HOST': os.environ.get('DATABASE_HOST'), 'PORT': os.environ.get('DATABASE_PORT'), }, } Then I activated Python3 VirtualEnviroment and executed export DATABASE=DEVELOPMENT as shown in picture below - When I start my application I get this from the print() - None i m here None i m here It has also raised and exception - Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/core/checks/model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/db/models/base.py", line 1274, in check *cls._check_constraints(), File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/db/models/base.py", line 1840, in _check_constraints connection.features.supports_table_check_constraints or File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ … -
ElasticSearch suggest from multiple documents
I want to make an autocomplete like Google. When you make a search for an actor name, it mixe searches and actors results. I use Django with django-elasticsearch-dsl and elasticsearch-dsl-py. I have 2 documents indexed, movies and actors with a suggest filter. @registry.register_document class MovieDocument(Document): class Index: # Name of the Elasticsearch index name = 'movies' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = Movie # fields to index fields = ['title'] @registry.register_document class ActorDocument(Document): class Index: # Name of the Elasticsearch index name = 'actors' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = Actor # fields to index fields = ['name'] My Suggest suggestions es = MovieDocument.search().suggest( 'autoc', 'leonardo ', completion={ 'field': 'title', 'skip_duplicates': True, 'size':10 }, ) es = es.execute().to_dict() How can I modify my suggest to allow search in both documents ? -
Why my form in Django is not valid ? Never do the condition
I'm trying to save the default data of my form and model with a simple function in Django but when I use the condition of is_valid() never enter to the condition. What can I do ? This is for views.py def entreno1B(request): if request.method == 'POST': form=Entreno(request.POST) if form.is_valid(): print("is valid") form.save() return render(request, 'training/entrenosB1.html') my model is class Entrenos(models.Model): tiempo1D1 = models.FloatField(max_length=1000,default=0.0) tiempo2D1 = models.FloatField(max_lenght=1000,default=0.0) and my form is class Entreno(forms.ModelForm): class Meta: model = Entrenos fields = ('tiempo1D1','tiempo2D1',) Please Help. I don't know what is my error. Thank you -
How to display in a dropdown menu a value from a Django model that is associated in M2M relationship?
I have the following table structure where a task is associated with an objective (M2M relationship because many tasks can be associated to many objectives): # Task model from objective.models import Objective class Task(models.Model): ACTIVE = 'Active' CANCELLED = 'Cancelled' FINALIZED = 'Finalized' STATUS = [(ACTIVE, ACTIVE), (CANCELLED, CANCELLED), (FINALIZED, FINALIZED)] id = models.AutoField(primary_key=True) objective = models.ManyToManyField(Objective) task = models.CharField(null=False, max_length=140) status = models.CharField(max_length=24, choices=STATUS, default=ACTIVE) # Objective model class Objective(models.Model): COMPLETED = 'Completed' NOT_COMPLETED = 'Not completed' STATUS = [(COMPLETED, COMPLETED), (NOT_COMPLETED, NOT_COMPLETED)] id = models.AutoField(primary_key=True) objective = models.CharField(null=False, max_length=60) status = models.CharField(max_length=24, choices=STATUS, default=NOT_COMPLETED) I have a view where the user can edit the task values and there's a dropdown menu where the user can change the objective that is associated with the task. The dropdown menu displays the current objectives from the user but I need to select manually the objective that is associated with that task. # Task: Finish the automation project. # Content of the dropdown menu objectives: Routine activities, Sprint 2, Quarterly meeting What I want is that when I open the view that display a task, the dropdown menu should be displaying automatically that objective that is associated with the task and when … -
heroku deployment, relation "django_session" does not exist
I've build a simple browser game on Python+Django, which is using session/cookies to track the score. The game it self doesn't have any database. When I'm deploying to heroku, I got this type of error ProgrammingError at / relation "django_session" does not exist LINE 1: SELECT (1) AS "a" FROM "django_session" WHERE "django_sessio... ^ Request Method: GET Request URL: https://lesgogo.herokuapp.com/ Django Version: 3.0.7 Exception Type: ProgrammingError Exception Value: relation "django_session" does not exist LINE 1: SELECT (1) AS "a" FROM "django_session" WHERE "django_sessio... ^ Exception Location: /app/.heroku/python/lib/python3.8/site-packages/django/db/backends/utils.py in _execute, line 86 Python Executable: /app/.heroku/python/bin/python Python Version: 3.8.3 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python38.zip', '/app/.heroku/python/lib/python3.8', '/app/.heroku/python/lib/python3.8/lib-dynload', '/app/.heroku/python/lib/python3.8/site-packages'] Server time: Sat, 13 Jun 2020 04:00:23 +0000 what I've tried: deployed successfully to heroku without views.py (the logic part with session in that file), static files like img and css were loaded/showed properly I was here and tried that: python manage.py migrate --fake sessions zero # then your sessions migrate will be python manage.py showmigrations sessions [ ] 0001_initial # then migrate with --fake-initial again python manage.py migrate --fake-initial added, and pushed back to heroku, didn't worked. my settings.py file is pretty much default, so all middlewares are there, I just added my app … -
Does Django close and delete TemporaryUploadedFiles and InMemoryUploadedFiles?
I have read through all the documentation for TemporaryUploadedFiles and InMemoryUploadedFiles but they talk about clean up. I know that Python Temporary Files need to be closed in order to be deleted automatically. @api_view(['POST', ]) def test(request): #img is type InMemoryUploadedFile for img in request.FILES.get('images'): Model.objects.image = img Model.save() #vid is type TemporaryUploadedFile for vid in request.FILES.get('videos'): Model.objects.video = vid Model.save() In the code above, are the TemporaryUploadedFiles and InMemoryUploadedFiles deleted and cleaned up automatically? -
Easiest way to import and export csv files to models without django-admin
I am new to django and learning a lot through this forum while building a small app however I am stuck at point in the development and will be able to complete my app with this segment. I have read online lot of documentation around how to import and export csv files into django models however all the codes/docs I read need the code to be written to map the columns manually from the csv to models. However I want to build a form where I want the user to select the table name from the dropdown and upload the csv file accordingly. Can this be achieved easily by dynamically comparing the model fields to csv headers and import if all of them match? This would be a huge help if you can put me int he right direction towards how this can be achieved. I am currently using oracle as my app database. Thank you so much. -
How to connect Detail Class Based View to Template URL Mapping?
How to connect Detail Class Based View to Template URL Mapping? Here is views.py file in myapp: class ModelDetailView(DetailView): model = models.mymodel template_name = 'mymodel_detail.html' Here is urls.py of myapp .....path('<pk>', ModelDetailView.as_view(), name = 'detail')........... Here is mymodel_detail.html file: ........<li><a href="{% url 'myapp:detail' {{object.id}} %}">{{ object.title }}</a></li>....... I want that when I click on object.title, it leads me to its detailed view? How do I do that? Have also tried: (urls.py) path('(?P<pk>[-\W]+)/', ModelDetailView.as_view(), name = 'detail') and path('detail<pk>', ModelDetailView.as_view(), name = 'detail'), -
Convert Boolean To Custom String
I have boolean values in my database and within a Django project I am printing them to a pdf. Its very minor but id like them to print as yes/no rather than true/false. I know that I could use yesno if I was outputting booleans in a template: https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#yesno But I am outputting these within a function. I also know I could use an if/else statement, but was hoping for something a bit cleaner. IE - Is there a short, clean way to convert boolean values to custom strings. Thank you. -
NoReverseMatch at /store/
I am building a e.com website using Django and python .. there is little issue with main.html here im sharing the code and error screenshot help me with these guys error image i got stuck with '''Error during template rendering In template C:\Users\vinay\Documents\project\ecom\store\templates\store\main.html, error at line 16 Reverse for '' not found. '' is not a valid view function or pattern name. 6 <head> 7 <title>Ecom</title> 8 9 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" /> 10 11 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> 12 13 <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> 14 15 <script type="text/javascript"> 16 var user = '{{request.user}}' 17 18 function getToken(name) { 19 var cookieValue = null; 20 if (document.cookie && document.cookie !== '') { 21 var cookies = document.cookie.split(';'); 22 for (var i = 0; i < cookies.length; i++) { 23 var cookie = cookies[i].trim(); 24 // Does this cookie string begin with the name we want? 25 if (cookie.substring(0, name.length + 1) === (name + '=')) { 26 cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); ''' -
Dynamically Update SelectMultiple Widget Option Attributes in Django Form
I'm utilizing Django Forms for my web application's front-end filter functionality, and I'm making a few Field & Widget customizations so that I may present multi-select checkboxes as follows: [x] Doug Funny (1) [ ] Skeeter Valentine(5) [x] Patti Mayonnaise(3) [ ] Roger Klotz (9) Upon selecting an option, I'm able to dynamically update the checkbox field labels (the counts, specifically) by overriding my Forms init method as follows: class FiltersForm(forms.Form): ... dateRadio = forms.ChoiceField(required=True, choices=CHOICES, widget=forms.RadioSelect) studentCheckbox = MyModelMultipleChoiceField(widget=MyMultiSelectWidget, queryset=Student.objects.all(), required=False) gradeCheckbox = forms.MultipleChoiceField(required=False) ... def __init__(self, *args, **kwargs): super(FiltersForm, self).__init__(*args, **kwargs) students = Student.objects.values(...).annotate(count=Count(...)) self.fields['studentCheckbox'].queryset = Student.objects.all() # dynamically updating the field's label here to include a count self.fields['studentCheckbox'].label_from_instance = lambda obj: "%s (%s)" % (students.get(pk=obj.pk)['name'], students.get(pk=obj.pk)['count']) But rather than "hardcode" the counts in the field label, I'd like to dynamically set the count as a 'data-count' attribute on each of the widget's option fields. In my attempt to do so, I've subclassed forms.ModelMultipleChoiceField as MyModelMultipleChoiceField. It's my hope to override the label_from_instance function in MyModelMultipleChoiceField to dynamically access the obj (by pk) and set a data-count attribute in the process. For some reason, however, the label_from_instance function isn't being called from the Form's lambda (self.fields['studentCheckbox'].label_from_instance). I've also … -
Pass model data from one view to another view using Django
I am new to Django and stuck on this problem. Basically page1 will ask the user for the name and address. I am doing this by using a model form. My model looks something like this class Person(models.Model): first = models.Charfield(max_length=100) last = models.CharField(max_length=100) street = models.CharField(max_length=100) state = models.CharField(max_length=100) country = models.CharField(max_length=100) phone = models.CharField(max_length=100) c_num = models.CharField(max_length=100) c_exp = models.CharField(max_length=100) And my form on my first page looks like this: class PersonForm(forms.ModelForm): class Meta: model = Person fields = ['first', 'last', 'street', 'state', 'country', 'phone'] So I basically get the users information on the first page using the form. Then that updates my model but leaves the c_num and c_exp blank. Then on the second page I want to display the information that the user just entered and also prompt for the c_xxx properties. However, I am not sure how to update the current Person object. How would I search through all objects to find the current one the user is creating? -
Putting Submit button at the bottom of the form
I want the submit button to be at the bottom of the form. I have tried using <div>, <div float="left">, <div float="right">, <br> and <span>. So far the only solution I have come up with is to repeat <br> multiple times which is a messy solution and one that is only compatible on laptops the same size as mine. <form method="post" action=""> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div float="left"> {# Include the visible fields #} {% for field in form.visible_fields %} <br class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} </br> {{ field }} {% endfor %} </div> <div float="right"><input type="submit" value="Submit"></div> </form> -
ModuleNotFoundError: Import issues
Facing an issue with import with a Django project while following this tutorial. I want to import the views from core/views.py onto global level to api/api.py. Below is my folder structure: api |--api | |--init.py | |--api.py | |--settings.py | |--urls.py | |--wsgi.py | | |--core |--serializers.py |--views.py |--models.py |--urls.py *|...*.py In views.py, I have: from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from . import models from . import serializers from django.apps import apps from rest_framework_extensions.mixins import NestedViewSetMixin class ContactViewSet(NestedViewSetMixin, ModelViewSet): queryset = models.Contact.objects.all() serializer_class = serializers.ContactSerializer class RoleViewSet(NestedViewSetMixin, ModelViewSet): queryset = models.Role.objects.all() serializer_class = serializers.RoleSerializer Now, for the import in api/api.py, I have: from rest_framework import routers from api.core import views as core_views router = routers.DefaultRouter() router.register(r'contact', core_views.ContactViewSet) router.register(r'role', core_views.RoleViewSet) However, when I run, python manage.py runserver, I get the error: .... File "C:\Program Files\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\me\Documents\project\api\api\urls.py", line 3, in <module> from .api import router File "C:\Users\me\Documents\project\api\api\api.py", line … -
django relation "accounts_pies" does not exist, after chaning a model class name
I created a new model and ran makemigration, and then decided the edit the name by removing and 's'. class Pies(models.Model): pihostname = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.name to class Pie(models.Model): I reran makemigrations again and it noted the class name update, but I am still pulling an error from some sql query somewhere I can't find. ProgrammingError at /admin/accounts/pies/ relation "accounts_pies" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_pies" ^ Request Method: GET Request URL: http://192.168.42.13:8082/admin/accounts/pies/ Django Version: 3.0.6 Exception Type: ProgrammingError Exception Value: relation "accounts_pies" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_pies" ^ Exception Location: /home/bubba/Env/trader/lib/python3.7/site-packages/django/db/backends/utils.py in _execute, line 86 Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.3 Python Path: ['.', '', '/home/bubba/Env/trader/lib/python37.zip', '/home/bubba/Env/trader/lib/python3.7', '/home/bubba/Env/trader/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/bubba/Env/trader/lib/python3.7/site-packages'] Server time: Sat, 13 Jun 2020 00:42:34 +0000 Traceback Switch to copy-and-paste view /home/bubba/Env/trader/lib/python3.7/site-packages/django/db/backends/utils.py in _execute return self.cursor.execute(sql, params) … ▶ Local vars The above exception (relation "accounts_pies" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_pies" ^ ) was the direct cause of the following exception: /home/bubba/Env/trader/lib/python3.7/site-packages/django/core/handlers/exception.py in inner How do I fully update django to my new class name assignment?