Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
an employee who created the app left, how do we access the Heroku account as the app stopped working
an employee who created the app left, how do we access the Heroku account as the app stopped working an employee who created the app left, how do we access the Heroku account as the app stopped working an employee who created the app left, how do we access the Heroku account as the app stopped working -
How to avoid infinite recursion in self-referencing many-to-many relation
In order to implement a delegation system in my Django application, I have a self-referencing many-to-many relation on my person model: from django.contrib.auth.models import AbstractUser from django.db import models class Person(AbstractUser): delegates = models.ManyToManyField("self", symmetrical=False, blank=True, null=True, default=None) I believe there are two pitfalls (ways to trigger infinite recursions) to this approach: If User A set himself as delegate (probably dumb but feasible) If User A set User B as delegate and User B set User A as delegate What would be the right approach to avoid such cases? -
IntegrityError at /sheets/create/ NOT NULL constraint failed: sheets_sheet.sheetGroup_id
When filling out a form for my model, every field is filled in properly but then it breaks when I go to submit it. I have made migrations and migrated, as well as adding blank=True, null=True. models.py # There is a bunch of more fields, but this seems to be the field breaking it sheetGroup = models.ManyToManyField(SheetGroup, blank=True, null=True) forms.py class CreateSheet(forms.ModelForm): class Meta: model = models.Sheet fields = '__all__' views.py def createSheet(request): form = forms.CreateSheet() # for group in SheetGroup.objects.all().order_by('name'): # form.sheetGroup.add(group) if request.method == 'POST': form = forms.CreateSheet(request.POST) form.author = request.user if form.is_valid(): form.save() return redirect('sheets:list') else: form = forms.CreateSheet() return render(request, 'sheets/createSheet.html', { 'form': form }) This is the error message being given: https://ibb.co/JFF4pd3 whenever I submit the form (with every field being filled out properly). -
How to use conda and django-admin startproject properly in 2019
I would like to know the latest steps to use Django with Conda or if I should be using another anaconda tool altogether. My research has not shown me clear 2019 solutions to this. I have found this which appears to start launching the boilerplate code directory structure directly in the djangoenv. I may need this ironed out in my head, but I thought we use the creation of the environment separate from the code we wish to run with it. I have a MBP with Mojave 10.14.6 using VSCode and conda to manage my environments for Pyhton. I am a little confused on where I should be creating a directory structure with the manange.py and where I should be having an environment built from. I think the top level django application directory needs to be created with a mkdir and the resulting .env file should be frozen from within that structure by first creating a conda environment and installing django there, then using conda list --export to freeze the environment created. conda create --name django-app python=3.7.4 conda activate django-app # installs to the ## Package Plan ## environment location: /Users/me/anaconda3/envs/django-app conda install django ## Package Plan ## environment location: … -
How to serve Django static files during development without having to run "collectstatic"?
I have a Django version 2.2.6 application that has my Django static files being served up from a separate dedicated file server. I use the Django "collectstatic" command to update the static files on my file server whenever one of them changes. I also use the django-pipeline package so that each static file contains a special string in the file name. This prevents my users' browsers from loading a static file from cache if I've updated that file. This configuration works perfectly. I'm now in a phase in which I'm making constant changes to my CSS file to create a new look and feel to my website and it's a pain to have to remember to run the collectstatic command after each little change I make. Is there a way I can temporarily "toggle" this collectstatic configuration off while I'm doing development so that I don't have to constantly run the collectstatic command? I seem to recall there was a way to change the main urls.py file and set DEBUG = True to do something like this back in Django 1.8 but I don't see it mentioned in the latest Django documentation. What is the current "best practice" for doing … -
Django full text search: how to combine multiple queries and vectors?
I have a from with three inputs: category, location, and keywords. If all three fields are filled in the form, the relationship of the results should be AND, and otherwise will only fetch results by location. I have been trying to combine these three inputs for Django full-text search but it fetches results matching the location only. Here is my code for views.py: class SearchServices(generic.ListView): model = Service context_object_name = 'services' template_name = 'services/search.html' def get_queryset(self): qs = Service.objects if self.request.GET['location'] != '': lat_long = self.request.GET['location'].split(',') user_location = Point(float(lat_long[1]), float(lat_long[0]), srid=4326) keywords = self.request.GET['keywords'] category = self.request.GET['category'] query = SearchQuery(keywords) & SearchQuery(category) vector = SearchVector('title', 'description', StringAgg('tag__name', delimiter=' ')) + SearchVector(StringAgg('category__slug', delimiter=' ')) if self.request.GET['location'] != '': qs = qs.filter(location__distance_lte=(user_location, D(km=2))) if category != '': qs = qs.annotate(search=vector).filter(search=query).distinct() qs = qs.annotate(rank=SearchRank(vector, query)).order_by('-rank') qs = qs.annotate(distance=Distance('location', user_location)).order_by('distance') return qs Any pointers as to what I am doing wrong here would be highly appreciated. -
How to save Document in django?
\html <form> <table> <td colspan="2" style="text-align: center;"><h2 style="font-weight: bold;">Document</h2></td> </tr>{% for d in doc %} <tr> <td><p style="text-transform: capitalize;">{{d.Description}}</p></td> <td><input type="file" name="file" value="{{d.id}}"/></td> </tr> {% endfor %} </table> <input type=submit value="Submit" class="enroll w3-button w3-white w3-border w3-border-green w3-round-large w3-hover-green"> </form> \views def newEnroll(request): id = request.POST.get('ids') studentname = StudentProfile(id=id) doc = request.POST.get('file') document = DocumentRequirement(Description=doc) insert_doc = StudentsSubmittedDocument( Remarks = document ) insert_doc.save() \models class DocumentRequirement(models.Model): Description = models.CharField(max_length=500,blank=True) class StudentsSubmittedDocument(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, on_delete=models.CASCADE,blank=True,null=True) Document_Requirements = models.IntegerField(null=True,blank=True) Document = models.FileField(upload_to='files/%Y/%m/%d',null=True,blank=True) Remarks = models.CharField(max_length=500,blank=True,null=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) i have 3 models that I combine in views, i just want to save an document on every StudentsSubmittedDocument(Students_Enrollment_Records), "DocumentRequirement(Document)", please help me on these problem. no error detected but no data save in the database. -
How to access fields from this complex query-set given below?
I want to fetch fields from this queryset but basic slicing operation didn't work. [{"model": "core.userdetails", "pk": 1, "fields": {"username": "uposia", "first_name": "Uday", "last_name": "Posia", "password": "12345", "avatar": "IMG_4347_HGdzPIG.jpg", "about": "Python Django Developer", "slogan": "Live Young, Live Free"}}] -
Restrict access to reset_password form of Django in PasswordResetView in case the user is already logged in
Currently, I have a user model that can access account related information based on its session. I am using the django auth PasswordResetView. The password reset form is used to reset password if the user has forgotten his/her password. But this django view is also accessed by the user when he is already logged in. How can I restrict the user to access this page. I cannot find solution for this problem, since its a total abstraction and nothing is present in my views.py file. This is how my urls.py file looks like : from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainapp.urls')), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name="logout"), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name="password_reset"), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name="password_reset_done"), path('password_reset_confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name="password_reset_confirm"), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name="password_reset_complete"), path('change_password/', auth_views.PasswordChangeView.as_view(template_name='users/change_password.html', success_url="/"), name="password_change"), # path('password_change_done/done/', auth_views.PasswordChangeDoneView.as_view(template_name='users/password_change_done.html'), name="password_change_done"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) A logged in user should not be able to access password_reset_form since it is only meant when the password is forgotten and when the user is already logged in. It does not make sense for the user to access password_reset.html. … -
How to set apache permissions for a Postgresql in Ubuntu for a Django project?
Ok so I did not set apache permissions for db.sqlite3 as I intend to use postgresql, but I did give permission to my whole django project folder. Now, should I just make a postgresql user and a db and assign the credentials in the settings.py and leave it like that? Also, I'm not really sure what to put in the "HOST" and "PORT" entries if that's the case? DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": 'mydbname_db', "USER": 'myuser', "PASSWORD": 'mypass', "HOST": "", "PORT": "", } } -
User login system in Django, with MongoDB as the primary database
So, here is the thing. I want the best method to log users on my website. I've already made a registration system that registers details of Users in the mongoDB using model forms. I don't understand how to login the user in th website. Do I fetch the user data from the DB and match with the the form data entered by the user to log in, what is the best practice? -
How to make fast the import of an excel file containing more than 5000 lines into sqlite database with django
Import xls file (more than 5000 lines) into my sqlite database takes so long def importeradsl(request): if "GET" == request.method: else: excel_file = request.FILES["excel_file"] #you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) #getting a particular sheet by name out of many sheets worksheet = wb["Sheet 1"] #iterating over the rows and getting value from each cell in row for row in worksheet.iter_rows(min_row=2): row_data = list() for cell in row: row_data.append(str(cell.value)) #Get content fields DerangementCuivre models #Client nd = row_data[0] nom_client = row_data[3] nd_contact = row_data[4] #Categorie code_categorie = row_data[6] acces_reseau = row_data[8] etat = row_data[9] origine = row_data[10] code_sig = row_data[11] agent_sig = row_data[13] date_sig = dt.datetime.strftime(parse(row_data[14]), '%Y-%m-%d %H:%M:%S') date_essai = dt.datetime.strftime(parse(row_data[15]), '%Y-%m-%d %H:%M:%S') agent_essai = row_data[18] try: date_ori = dt.datetime.strptime(row_data[19], '%Y-%m-%d %H:%M:%S') except ValueError as e: print ("Vous", e) else: date_ori = dt.datetime.strftime(parse(row_data[19]), '%Y-%m-%d %H:%M:%S') agent_ori = row_data[20] code_ui = row_data[21] equipe = row_data[22] sous_traitant = row_data[23] date_pla = dt.datetime.strftime(parse(row_data[24]), '%Y-%m-%d %H:%M:%S') date_rel = dt.datetime.strftime(parse(row_data[25]), '%Y-%m-%d %H:%M:%S') date_releve = dt.datetime.strptime(row_data[25], '%Y-%m-%d %H:%M:%S') date_essais = dt.datetime.strptime(row_data[15], '%Y-%m-%d %H:%M:%S') pst = pytz.timezone('Africa/Dakar') date_releve = pst.localize(date_releve) utc = pytz.UTC date_releve = date_releve.astimezone(utc) date_essais = pst.localize(date_essais) date_essais = date_essais.astimezone(utc) code_rel = row_data[26] localisation = row_data[27] cause = … -
How to store multiple images for a single row/object in Django so that I can retrieve them or perform other query operations easily?
I am trying to build an api for a mobile application about house rents. The user may post multiple images of his house while posting an ad. How do I save them? I thought of Creating one-to-many relationship with My Ad class and an Image class, is there anything better? I've given a part of what I am talking about. class RentPost(models.Model): id = models.AutoField() title = models.CharField(max_length = True) description = models.Textarea() class Images(models.Model): post = models.ForeignKey(RentPost, on_delete= models.CASCADE) -
Boto3 deprecation warning on import
I'm trying to use boto3 in a python/django project. I've done this before, but it's throwing me a warning when running localhost -- which is breaking the request I'm trying to run. I'm on python version 3.7. I've seen the issue raised in the GitHub repo for boto3, most referring to errors when running pytest. My issue doesn't seem to fall in line with the latest PR https://github.com/boto/botocore/issues/1615 I'm not too sure where to turn. Any advice is much appreciated. from . import urllib3 File "/Users/neilballard/.local/share/virtualenvs/Volley-ldVCpc8_/lib/python3.7/site-packages/botocore/vendored/requests/packages/urllib3/__init__.py", line 10, in <module> from .connectionpool import ( File "/Users/neilballard/.local/share/virtualenvs/Volley-ldVCpc8_/lib/python3.7/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py", line 38, in <module> from .response import HTTPResponse File "/Users/neilballard/.local/share/virtualenvs/Volley-ldVCpc8_/lib/python3.7/site-packages/botocore/vendored/requests/packages/urllib3/response.py", line 9, in <module> from ._collections import HTTPHeaderDict File "/Users/neilballard/.local/share/virtualenvs/Volley-ldVCpc8_/lib/python3.7/site-packages/botocore/vendored/requests/packages/urllib3/_collections.py", line 1, in <module> from collections import Mapping, MutableMapping File "<frozen importlib._bootstrap>", line 1032, in _handle_fromlist File "/Users/neilballard/.local/share/virtualenvs/Volley-ldVCpc8_/lib/python3.7/collections/__init__.py", line 52, in __getattr__ DeprecationWarning, stacklevel=2) DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working I've confirmed that "import boto3" is causing the issue. I've removed boto3, reinstalled, tried different version of boto3 & urllib. -
DJANGO: Cannot start gunicorn from service configuration file
I cannot start gunicorn from the configuration file. it runs perfectly from: gunicorn --bind 0.0.0.0:8000 myproject.wsgi service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=nigsdtm WorkingDirectory=/home/nigsdtm/django_projects/PID/PID_webinterface ExecStart=/home/nigsdtm/django_projects/PID/PID_webinterface/pidvirtualenv/bin/$ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ mysite.wsgi:application [Install] WantedBy=multi-user.target project root(where manage.py is located):/home/nigsdtm/django_projects/PID/PID_webinterface virtual env: /home/nigsdtm/django_projects/PID/PID_webinterface/pidvirtualenv sudo systemctl status gunicorn.socket: gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (listening) since Wed 2019-10-16 13:49:57 UTC; 2h 47min ago Listen: /run/gunicorn.sock (Stream) file /run/gunicorn.sock - ok /run/gunicorn.sock: socket sudo journalctl -u gunicorn.socket: Oct 16 12:19:00 nigsdtm systemd[1]: Listening on gunicorn socket. Oct 16 12:22:22 nigsdtm systemd[1]: gunicorn.socket: Unit entered failed state. sudo systemctl status gunicorn: - not ok gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2019-10-16 13:58:04 UTC; 2h 41min ago Main PID: 1038 (code=exited, status=203/EXEC) Oct 16 13:58:04 nigsdtm systemd[1]: Started gunicorn daemon. Oct 16 13:58:04 nigsdtm systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Oct 16 13:58:04 nigsdtm systemd[1]: gunicorn.service: Unit entered failed state. Oct 16 13:58:04 nigsdtm systemd[1]: gunicorn.service: Failed with result 'exit-code'. Oct 16 14:05:47 nigsdtm systemd[1]: [/etc/systemd/system/gunicorn.service:12] Missing '='. curl --unix-socket /run/gunicorn.sock localhost curl: (56) Recv failure: Connection reset by peer sudo … -
Where complicated template logic should reside?
I am wondering where complicated template logic should reside when using MVC framework like Django. For example, I want to display the list of some models with their children's children's children's models grouping by their category. Grouping some model's children's children's children's model is only for displaying purpose. Embedding this logic is too complicated to implement in Template. However, I think model shouldn't care about how it would be displayed, and controller is not for the place for reusable logic. If I could create middleware between template and controller, that seems right choice, but I can't do that. Where should complicated logic for template resides? -
How to add new field to existing django model postgres
Let's suppose I have the following model: class Test(models.Model): field_one = models.CharField(max_length=80) Now, we have created 2-3 Model objects with field_one field. p1 = Test(field_one="Object1") p1.save() p2 = Test(field_one="Object2") p2.save() Later, I realised that I need to add another field field_two to my Test model. class Test(models.Model): field_one = models.CharField(max_length=80) field_two = models.IntegerField(default=3) Now, Doing makemigrations & migrate and running server. which will prompt the following error django.db.utils.ProgrammingError: column mainapp_test.field_two does not exist I understand that this error occurs due to my 2 existing objects in PostGresDB doesn't have field_two column. Is there any effective way to add the column to my objects with some default value? & How to solve this problem? -
Why is my code not rendering a list of table on my web page?
I have a model D100Generator with an incrementing primary key. I am trying to mimic the Django tutorial pt. 3, substituting a list of table names for the questions that should be rendered on the index.html page. When I run the code, I get a bullet point, but no text. Is my latest_table_list not being populated? Or is it I'm calling the wrong thing? I am very new to Python, web development and Stack Overflow, so forgive me if the formatting and explanation is poor on this. I suspect I'm not calling the table_name field correctly, but nothing I've tried has been able to work. I tried setting the line item for the list as: <li><a href="/generators/{{ d100Generator.d_100_id }}/">{{ d100Generator.table_name }}</a></li> and as: <li><a href="/generators/{{ d100Generator.id }}/">{{ d100Generator.table_name }}</a></li> neither of which will help display as desired. The D100Generator Model class D100Generator(models.Model): d_100_id = models.AutoField(primary_key=True) field_of_interest = models.ForeignKey(FieldOfInterest, on_delete=models.CASCADE) subreddit_post_id = models.ForeignKey(Subreddit, on_delete=models.CASCADE, blank=True, null=True) module_id = models.ForeignKey(Module, on_delete=models.CASCADE, blank=True, null=True) generic_website_id = models.ForeignKey(GenericWebsite, on_delete=models.CASCADE, blank=True, null=True) table_name = models.CharField('table name', max_length=100) system = models.CharField(max_length=150) genre = models.CharField(max_length=250) chart_type = models.CharField('Die used', max_length=15) chart_instructions = models.TextField('Chart instructions & explanation') roll_1 = models.TextField('1', blank=True, null=True) roll_2 = models.TextField('2', blank=True, null=True) roll_3 … -
Difficult queryset for prefetch
I have models: class Inote(IDeclaration): Time = models.DateTimeField(auto_now=True) Author = models.ForeignKey(User, related_name='%(class)ss') __unicode__ = lambda s: str(s.id) + ' (%s)'%(s._meta.model_name) class Article(Inote): Title = models.CharField(max_length=50) The models are linked by multitable inheritance. In my view I try get Articles through prefetch_related in queryset of User: class UserList(ListView): model = User def get_queryset(self): qs = super(UserList, self).get_queryset().prefetch_related('inotes__article') for q in qs: for i in q.inotes.all(): if hasattr(i,'article'): print i.article return qs If I apply prefetch_related('inotes__article') to qs, I get roughly what I want - three queries: SELECT ••• FROM "auth_user" SELECT ••• FROM "testapp_inote" WHERE "testapp_inote"."Author_id" IN ('1', '2', '3', ...) SELECT ••• FROM "testapp_article" INNER JOIN "testapp_inote" ON ("testapp_article"."inote_ptr_id" = "testapp_inote"."id") WHERE "testapp_article"."inote_ptr_id" IN ('1', '2', '3', '4') But I cann't know what inote is article and in this regard I have used if hasattr(i,'article') to distinguish its. And I wanted to solve this problem through Prefetch, but if I do this: prefetch = Prefetch("inotes", Inote.objects.filter(article__isnull=False)) qs = super(UserList, self).get_queryset().prefetch_related(prefetch) then I have many queries for each inote in my db. Then I tried Prefetch("inotes__article", Inote.objects.filter(article__isnull=False), but has FieldError on inotes__article. How to use correctly Prefetch to solve my problem. Could you share examples or links about complex queries in … -
Is It possible login Django admin via PyQt5?
I'd like to know if it's possible to login to django via PyQt5. I have been trying a few things but without much success. Below, I try a solution with PyQt5's QtNetwork. This is my code: import json import sys import requests from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLineEdit, QMessageBox, QLabel from PyQt5.QtCore import pyqtSlot from PyQt5 import QtCore, QtGui, QtNetwork from django.test import Client from querystring import querystring class AppLogin(QMainWindow): def __init__(self): super().__init__() self.title = 'Login in the Desktop Application' self.left = 500 self.top = 300 self.width = 380 self.height = 180 self.username = None self.password = None self.button = None self.nam = QtNetwork.QNetworkAccessManager() def __call__(self, *args, **kwargs): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # Create an username textbox self.username = QLineEdit(self) self.username.move(20, 20) self.username.resize(280, 40) self.username.setPlaceholderText('Usuário') # Create a password textbox self.password = QLineEdit(self) self.password.setEchoMode(QLineEdit.Password) self.password.move(20, 80) self.password.resize(280, 40) self.password.setPlaceholderText('Senha') # Create a button in the window self.button = QPushButton('Login', self) self.button.move(20, 140) # connect button to function login self.button.clicked.connect(self.login) self.show() @pyqtSlot() def login(self): # User and passwd in my desktop app user = self.username.text() passwd = self.password.text() # My Django app Url url = "http://127.0.0.1:8000/login" data = {'username': user, 'password': passwd} # Here, I use QtNetWork to takes … -
Is it safe to manually change object id in Django
I have an Inline model in django admin, which appearance is ordered by id. I want to add functionality to change the appearance ordering via changing the id's directly. So I will do something like one = Model.objects.get(id=1) two = Model.objects.get(id=2) one.id, two.id = two.id, one.id one.save() two.save() Which does the trick, but I feel that it is not safe. Might it cause any troubles or issues? Are there a better way to achieve proper ordering in django admin? -
create or update user password in serializers rest_framework django
I want to check if the user exists, update the password(OTP). else create a new User (with one API). Note: My model is customized for mobile and OTP system. views.py: class GetOTP(APIView): def post(self, request, *args, **kwargs): mobile_number = request.data.get('mobile', False) mobile = check_mobile(mobile_number) if not mobile['status']: return Response(mobile) else: mobile = str(mobile['details']) otp = otp_generate(mobile) if otp: print('<------------------> ',otp) temp_data = {'mobile': mobile, 'password': otp} serializer = CreateOrGetUserSerializer(data=temp_data) serializer.is_valid(raise_exception=True) serializer.save() return Response({'status': True, 'details': 'Account created'}) else: return {'status': False, 'details': 'err to send OTP'} serializers.py : class CreateOrGetUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'mobile', 'password', ] def create(self, validated_data): user = User.objects.create_user(**validated_data) return user -
setup server for django application in Windows Server 2012 R2 Standard
I must setup a network computer (running Windows Server 2012 R2 Standard) as a production server for django applications, real quick. This is what I've already done: Installed Python 3.7.4 (64 bits version) Installed nginx 1.17.4 Installed virtualenv Created a virtual environment for hosting my application Have my django project ready and running ok with "manage.py runserver" Where do I go from here? I'm sorry, but I couldn't find instructions simple and atraightforward enough for me so far. I could use IIS or Apache as well, but only if it's simpler than nginx. -
Updateview setting user to null
When using updateview for some reason my user value is being set to null. I have a create view where the user is automatically set to the current user and when I view the database everything works as expected. The issue is that when I use updateview the value is being reset to null. All other values work as expected. Does anyone know how to prevent the value from being reset to null? class model_testform(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="author", null=True, blank=True, on_delete=models.SET_NULL) class view_testform(CreateView): model = model_testform form_class = form_testform template_name = "testform.html" def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user form.save() return super(view_testform, self).form_valid(form) def get_success_url(self, *args, **kwargs): form = form_testform messages.add_message(self.request, messages.SUCCESS, 'New Block was submitted') return reverse("testform:view_testform") class view_testformUpdate(UpdateView): model = model_testform form_class = form_testform template_name = "testformUpdate.html" def get_success_url(self, *args, **kwargs): form = form_testform messages.add_message(self.request, messages.INFO, 'Block was Updated') return reverse("testform:view_testform") -
Django loaddata from fixture returns error
Hello there i'm trying to move my django project from SQLite to PostgreSQL and in order to do that i need to populate the DB with some initial values. I already have 4 different fixture files with the initial data. These files are inside a fixtures directory inside the app. One per model and one including all initial data that i currently have on my SQLite DB. I already Created the DB in PostgreSQL and made the proper changes to the settings.py file in order to move to the PostgreSQL DB. The problem is that when i use python manage.py loaddata InitialData command it returns an error Traceback (most recent call last): File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "reg_producto" does not exist LINE 1: ...eg_producto"."Name", "reg_producto"."CMS_id" FROM "reg_produ... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = …