Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Activate venv in vs code
I have been trying to activate a virtual environment using Python's built-in module venv from VS Code without unfortunately any success. I don't get any error message, it simply won't activate. However, If I run the venv\Scripts\activate.bat command from the terminal it don't works ... -
Django-wanted to run the time continuously without refreshing the page
I have developed an Django application where it will take the time based on the timezone and it's working properly but when i refresh the page the time change how could I do without refreshing the page.Even i have no idea to implement it in js or ajax.If anyknow how could be possible to implement django code with the js or ajax. single.html {% extends 'base.html' %} {% block content %} <div class="container-md" id='firstcontainer'> <form action="" method="POST" autocomplete="off"> {% csrf_token %} <div class="container-md"> <h3 id ='user'>Search</h3> <div class="row"> <div class="input-group" > <div class="col-md" > <input class="form-control" type="search" placeholder="Search" id='btnsearch' name="finder" > <br> </div> <div class="pull-left"> <button class="btn btn-outline-success" style="width:70px;height:46px;" type="submit" >Search</button> </div> </div> {% if finder %} {% for list in userb %} <h3>User List</h3> <table class="table table-striped table-hover"> <tr> <!-- <th scope="col">ID</th> --> <td><b> Username </b></td> <td>{{list.username }}</td> </tr> <tr> <td> <b>Email</b></td> <td>{{list.email }}</td> </tr> <!-- <th scope="col"> Format</th> --> <tr> <td><b>Time</b></td> <td id='mydate'> {{mydate}}</td> </tr> <!-- <div class="col"> DateTime</div> --> <!-- <th scope="col">TimeZone</th> --> <!-- <th scope="col">Action</th> --> <!-- <th scope="row">{{list.id}}</th> --> <!-- <td>{{list.username }}</td> --> <!-- <td>{{list.email }}</td> --> <!-- for only the date time --> <!-- <div class="col"> {{my_date}}</div> --> <!-- <div class = 'col'>{{my_date}}</div> --> … -
Unable to update post using models in django
I want to prepare a webpage which outputs book name, publisher and author and want to add the data dynamically using admin panel but unable to do it using below code. Please help models.py from django.db import models class researchpaper(models.Model): title = models.CharField(max_length=200) publication = models.CharField(max_length=200) authors = models.CharField(max_length=200) def __str__(self) -> str: return self.title views.py def publications(request): context = { 'researchposts': researchpaper.objects.all() } return render(request, 'lab/publications.html',context) urls.py path('publications', views.publications, name='publications'), html file {% for paper in object_list %} <tr> <td> <h5>2021</h5> <p style="color: black;"><b>{{paper.title}}1. A minimal model for synaptic integration in simple neurons</b></p> <p style="font-size: 14px;"><i>Physica D: Nonlinear Phenomena, 2021</i></p> <p style="font-size: 14px;"><i>Adrian Alva, Harjinder Singh.</i></p> </td> <td><a href="#" target="blank" style="color: dodgerblue;"><i class="ai ai-google-scholar-square ai-2x" style="padding-right: 10px;"></i></a></td> </tr> <tr> <td> <hr> </td> </tr> {% endfor %} -
Input for field is missing even after i type the correct format on the API
I have coded the following: models.py class Job(models.Model): datetime = models.DateTimeField(default=timezone.now) combinedparameters = models.CharField(max_length = 1000) serializers.py class JobSerializers(serializers.ModelSerializer): class Meta: model = Job fields = ['combinedparameters'] views.py @api_view(['POST']) def create_job(request): job = Job() jobserializer = JobSerializers(job, data = request.data) if jobserializer.is_valid(): jobserializer.save() return Response(jobserializer.data, status=status.HTTP_201_CREATED) return Response(jobserializer.errors, status=status.HTTP_400_BAD_REQUEST) Page looks like this: But if i copy {'device': 177, 'configuration': {'port_range': 'TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/2,TenGigabitEthernet1/0/3,TenGigabitEthernet1/0/4,TenGigabitEthernet1/0/5', 'port_mode': 'Access', 'port_status': 'Disabled', 'port_param1': 'Test\\n1\\n2\\n3', 'port_param2': 'Test\\n1\\n2\\n3'}} And click post, got error saying the single quotes have to be double quotes. So i changed it to : {"device": 177, "configuration": {"port_range": "TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/5", "port_mode": "Access", "port_status": "Disabled", "port_param1": "1\\n2\\n3", "port_param2": "1\\n2\\n3"}} I clicked post again and this time the following error comes out: I dont understand why is it happening. The reason why I key in the long format because this is the format i want to save in my database and this format is created upon saving from my html that creates the job -
Grouping imports together from subdirectories
Say I have a django app where I'm using folders and subfolders to organize my models: app models __init__.py accounts user.py profile.py social facebook.py twitter.py linkedin.py admin.py apps.py urls.py views.py My __init__.py file is as follows: from .accounts.user import User from .accounts.profile import Profile from .social.facebook import Facebook from .social.twitter import Twitter from .social.linkedin import LinkedIn Is there any way to group these imports together or make the code shorter? E.g. (obviously doesn't work) from . import * # or from .accounts import * from .social import * -
Trouble ussing Buddy to test a project using Django REST FRAMEWORK POSTGRE AS DB
Hello I'm currently trying to implement Buddy with my little StartUp that is using DJANGO REST FRAMEWORK as a base. I found a very good example on the site. Unfortunately in the exmaple the used a MySql DB and I'm using Postgre as DB. My settings.py is: # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DBname', 'USER': 'DBuser', 'PASSWORD': 'DBpassword', 'HOST': '', 'PORT': '5432', } } } My Buddy execute look somethig like this: pip install -r requirements.txt cd Project python manage.py test I also created postgre service in Buddy like version: latest, Hostname: postgres, Port:5432, Login:DBuser, Password:DBpassword, Name of a database to be created on container startup: DBname When I run the build Test of my project an error message apears like this: connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Action failed: see logs above for details I really don't now how to fix this, it appears that Buddy creates the database correctly but for some reason django does not reconise that it exists. -
Django Data Migrations: Table Doesn't Exist
I am running into the issue described here: Django: Providing initial group with migrations Specifically, I'm working on legacy code which initialized a 'Countries' table from an init_data file. I now need to add countries (e.g. South Sudan). My understanding is that I should use migrations to add this data, so that the prod database and the test machines will be in sync. Here is my attempted migration: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def forwards_func(apps, schema_editor): Country = apps.get_model('countries', 'Country') db_alias = schema_editor.connection.alias Country.objects.using(db_alias).update_or_create(iso='SS', defaults={'name': 'SOUTH SUDAN', 'printable_name': 'South Sudan', 'iso3': 'SSD', 'numcode': 728}) def reverse_func(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('countries', '__latest__'), ] operations = [ migrations.RunPython(forwards_func, reverse_func) ] The new migrations works on an existing database, but when the test pipeline spins up a fresh machine, it fails with django.db.utils.ProgrammingError: (1146, "Table 'test_cc_dev.country' doesn't exist") I understand from the above link that the problem stems from all of the migrations needing to run as a group. I do not understand the solution. Am I supposed to add the whole table again in this migration? The original data was loaded in the 0001_initial.py file like this: def forwards_func(apps, schema_editor): … -
How to make simple drag&drop in django?
So, I have a django website that do some pandas calculations, it takes excel file and do calculations and returns file. So, I'm trying to make work this drag&drop but it's not working. I get this in my view, will not forward file and not looking right. cal.py def OnlyCAL(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] #pandas calculations response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'cal.html', { 'form': form, 'page_title':page_title }) cal.html {% extends "base.html" %} {% load static %} {% block content %} <style type="text/css"> .box__dragndrop, .box__uploading, .box__success, .box__error { display: none; } .box.is-dragover { background-color: grey; } </style> <form class="box" method="post" action="{% url "rec" %}" enctype="multipart/form-data"> {% csrf_token %} <div class="box__input"> <input class="box__file" type="file" name="files[]" id="file" data-multiple-caption="{count} files selected" multiple /> <label for="file"><strong>Choose a file</strong><span class="box__dragndrop"> or drag it here</span>.</label> <button class="box__button" type="submit">Upload</button> </div> <div class="box__uploading">Uploading…</div> <div class="box__success">Done!</div> <div class="box__error">Error! <span></span>.</div> </form> <script> if (isAdvancedUpload) { var droppedFiles = false; $form.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) { e.preventDefault(); e.stopPropagation(); }) .on('dragover dragenter', function() { $form.addClass('is-dragover'); }) .on('dragleave dragend drop', function() { $form.removeClass('is-dragover'); }) .on('drop', … -
how to change page data without refresh using django
I am working on a project like live currency prices and I need to change page data without refresh page.In this project I am using Django and Sql server. I did not get results using the triggers and Ajax because ajax needs an event to run like clicking or timer(that very bad for performance) and triggers can not be processed by Django. Is there a way to do it? Thank you for your help -
Translate sql query on Django
I have two tables: students (that has all the students of a school) and suspensions (all the students that are suspended) id name school_grade 1 Jeff 1 2 Dave 1 3 Susan 2 4 Will 2 5 Peter 3 id reason student_id 1 Missed class 1 2 Arrived 20 times late 2 3 Fight 5 So I need to get statistics of which students of different grades are suspended. So, my query is this. SELECT school_grade, count(school_grade) from students JOIN suspensions ON students.id=suspensions.student_id GROUP BY school_grade; And this query gives me exactly what I want. school_grade number of suspension 3 1 1 2 But I don't understand how to make this query on django. -
I how to check for authenticated user and show then show a different content in django
What am trying to do is have two different user locations. One is from my user model and the other is default from view. I want that anytime a user is authenticated, the location from the model shows but if not logged in the default location should be passed to the view. Views.py class Home(generic.TemplateView): template_name = "Home.html" def get_context_data(self, **kwargs): context = super(Home, self).get_context_data(**kwargs) if User.is_authenticated: map_location = self.request.user.location_on_the_map else: map_location = Point(longitude, latitude, srid=4326) context.update({ 'job_listing': JobListing.objects.annotate( distance=Distance("location_on_the_map", map_location) ).order_by("distance")[0:6] }) return context -
Django 403 Forbidden POST/PUT when requesting from Reactjs (strict-origin-when-cross-origin)
I have a reactjs project that makes requests using API to django-rest-framework. It was working fine and this problem suddenly appeared which is super weird. I'm already using django-cors-headers. My settings.py: INSTALLED_APPS = [ ... 'rest_framework', "corsheaders", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True My reactjs request: fetch('/api/user/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(obj) }) I just want to emphasize that it was working fine and suddenly after editing the code, it stopped working. -
how to prevent user from submitting the same form twice
I have the codes below in my views and models. But I want a situation in which a user cannot submit the same form twice. once a user submits the form he or she can only see a preview of what has been submitted but is unable to submit the same form. Any help would be highly appreciated. Thanks #views.py def index(request): form = MembershipForm() if request.method == 'POST': form = MembershipForm(request.POST) if form.is_valid(): form.save() return redirect("home") return render(request, 'index.html', {'form': form) #models.py class Membership(models.Model): fullname = models.CharField(max_length=500, blank=True, null=True) location = models.IntegerField(default='0',blank=True, null=True) department = models.IntegerField(default='0',blank=True, null=True) last_update = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return str(self.fullname) -
Dynamically change Char/IntegerField choices for each Model instance
I'm wondering if it's possible to dynamically change the choices of an IntengerField for each instance of a Model. I'm working with a video game API and i want PLATFORM_CHOICES to be unique for each game, since not every game is released on the same platform. For example, on the first iteration, the platform choices for game1 could be PlayStation & Xbox, but game2 could be PlayStation, Xbox, Nintendo, & PC. models.py class TestModel(models.Model): PLATFORM_CHOICES = [] platform_type = models.IntegerField(choices=PLATFORM_CHOICES, null=True) game = models.CharField(max_length=200, null=True) api.py def get_games(self): new_url = "{}{}".format(self.url, 'games') data = requests.get(new_url, params=self.query).json() games = data['results'] for game in games: t = TestModel() for platform in game['platforms']: id = platform['platform']['id'] # int name = platform['platform']['name'] # str t.PLATFORM_CHOICES.append((id, name)) # add tuple to list t.save() t.game = game['name'] t.save() I've tried different variations of this but the IntField always ends up empty. Please let me know if there's anymore info I can provide. -
Django Rest Framework - Unable to UPDATE Table Via AJAX through PUT HTTP Method
I have a small project where I have built an API and it feeds the frontend via ajax. All the other CRUD functions work apart from UPDATE. When I use Postman, the UPDATE API works perfectly. So I'm guessing the problem is on the ajax side. I have searched for a solution to no avail. Some help on this would be highly appreciated. Here is my UPDATE API @api_view(['PUT']) def EditProductAPI(request, id): product = Products.objects.get(id=id) serializer = ProductSerializer(instance=product, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_304_NOT_MODIFIED) My Update From <!-- Edit Product Modal --> <div class="container"> <div class="modal fade" id="editProduct" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit Product</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="editProduct" action=""> {% csrf_token %} <input type="hidden" id="Myid" value=""> <div class="form-group mb-3"> <label for="p-name">Product Name</label> <input type="text" class="form-control" id="p-name" name="name" placeholder="Product Name" required> </div> <div class="form-group mb-3"> <label for="p-category">Category</label> <select class="form-control form-select" aria-placeholder="Category" id="p-category" name="category" required> <option selected disabled>Category</option> <option value="Electronics">Electronics</option> <option value="Furniture">Furniture</option> <option value="Toys">Toys</option> <option value="Hardware">Hardware</option> <option value="Medicine">Medicine</option> <option value="Groceries">Groceries</option> </select> </div> <div class="form-group mb-3"> <label for="p-quantity">Quantity</label> <input type="number" class="form-control" id="p-quantity" name="quantity" placeholder="Quantity" required> </div> <div class="form-group mb-3"> <label for="p-price">Price</label> <input type="number" … -
django.db.utils.IntegrityError: (1048, "Column cannot be null") while using nested serializer
i got a problem while trying to serializer.save(). django.db.utils.IntegrityError: (1048, "Column 'person_id' cannot be null") i want to create a POST and PUT request, but i am getting the messege above. it is happand while i am adding a nested serializer at trainee serializer. person and fav_sport fields can not be null = true blank = true it is happans either when depth = 1 i hope you can help me why is that. this is the json i send: { "person":15, "sport_type":[1,2] } i do nested serializer because i want the api returns this at GET and POST and PUT requsets: { "person": { "id": 15, "first_name": "liad3", "last_name": "hazoot3", "birth_date": "1999-01-03", "gender": "M", "is_coach": true, "user": 11 }, "fav_sport": [ { "id": 2, "name": "Swimming", "raiting": 3 }, { "id": 3, "name": "soccer", "raiting": 2 } ] } sport type model class SportTypeDB(models.Model): name = models.CharField(verbose_name='name', max_length=255, unique=True) raiting = models.IntegerField(default=1, validators=[MaxValueValidator(5), MinValueValidator(1)]) spot type serializer class SportTypeSerializer(serializers.ModelSerializer): class Meta: model = SportTypeDB fields = '__all__' person model: class PersonDB(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('D', 'Different'), ) user = models.OneToOneField(User, on_delete=models.CASCADE,unique=True) first_name = models.CharField(unique=False, max_length=100) last_name = models.CharField(unique=False, max_length=100) birth_date = models.DateField() gender = models.CharField(max_length=1, … -
Django - IntegrityError ... NOT NULL constraint failed on save()
I'm very new to Python and Django so please bear with me. I'm running into a persistent error traced back to the "saleitem.save()" line in the below views.py. I'm trying to create a form that will allow me to populate various fields and then save and display that information on an active_listing.html page. views.py def create_listing(request): if request.method == "POST": saleitem = Listing() saleitem.user = request.user saleitem.item =request.POST.get("item") saleitem.description = request.POST.get("description") saleitem.category = request.POST.get("category") saleitem.bid = request.POST.get("bid") saleitem.image = request.POST.get("image_upload") saleitem.save() listings = Listing.objects.all() empty = False if len(listings) == 0: empty= True return render(request, "auctions/active_listing.html",{ "listings": listings, "empty": empty }) else: return render(request, "auctions/create_listing.html") models.py class User(AbstractUser): pass class Listing(models.Model): saleitem = models.CharField(max_length = 60) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller", null=True) description = models.TextField() category = models.CharField(blank = True, max_length= 60) bid = models.DecimalField(max_digits=5, decimal_places=2, default=0) image = models.URLField(blank=True, null=True) listing_status = models.BooleanField(blank=False, default= True) winning_bidder = models.ForeignKey(User, blank= True, on_delete= models.CASCADE, related_name = "winner", null = True) bidding_status = models.BooleanField(default=False) def __str__(self): return self.item I've tried using a Django form rather than an html template as well and run into the same issue. When I populate all the fields in my html form and hit the save button, … -
Django Apache2: Module Not Found
Looking for some help on this. Thanks in advance for any assistance that you are able to provide. Django 3.2.8 Python 3.8.10 Apache 2.4.41 Obtaining the following error when starting django w/apache: mod_wsgi (pid=74176): Failed to exec Python script file '/home/adjutant/srv/dj/soulrendnd/venv/soulrendnd/soulrendnd/wsgi.py'. mod_wsgi (pid=74176): Exception occurred processing WSGI script '/home/adjutant/srv/dj/soulrendnd/venv/soulrendnd/soulrendnd/wsgi.py'. Traceback (most recent call last): File "/home/adjutant/srv/dj/soulrendnd/venv/soulrendnd/soulrendnd/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/adjutant/srv/dj/soulrendnd/venv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/adjutant/srv/dj/soulrendnd/venv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/adjutant/srv/dj/soulrendnd/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/adjutant/srv/dj/soulrendnd/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/adjutant/srv/dj/soulrendnd/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/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 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'soulrendnd' Abbreviated output of tree -if from ~adjutant/srv/dj/soulrendnd/venv: . ./bin ... ./lib ... ./soulrendnd ./soulrendnd/manage.py ./soulrendnd/my_secrets.py ./soulrendnd/soulrendnd ./soulrendnd/soulrendnd/asgi.py ./soulrendnd/soulrendnd/__init__.py ./soulrendnd/soulrendnd/settings.py ./soulrendnd/soulrendnd/urls.py ./soulrendnd/soulrendnd/urls.py.bak ./soulrendnd/soulrendnd/views.py ./soulrendnd/soulrendnd/wsgi.py ./soulrendnd/static ./soulrendnd/templates ./soulrendnd/templates/index.html settings.py import os """ Django settings for … -
Django query with foreign key- output should be from two models
I am creating a querying website, which has two models, which connect with a foreign key. My goal is to have a searching page, where I given in a Person_ID as an input and get both Person and Report data (Report_ID, file_ID, Person_ID, name). Right now upon Person_ID entry it gives out Report data, but for some reasons, it does not give out the Person_ID itself and nothing from the Person table. my model: class Person(models.Model): Person_ID = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255) def __str__(self): return self.Person_ID class Report(models.Model): Report_ID = models.CharField(primary_key=True, max_length=255) file_ID = models.CharField(max_length=255) person = models.ForeignKey(Person, on_delete=models.CASCADE) def __str__(self): return self.Report_ID view.py: class HomePageView(TemplateView): template_name = 'home.html' class SearchResultsView(ListView): model = Person template_name = 'search_results.html' def get_queryset(self): query = self.request.GET.get('q') object_list= Report.objects.filter( Q(person__Person_ID__icontains=query) ) return object_list admin.py class ReportAdmin(admin.ModelAdmin): list_display = ("Report_ID", "file_ID",) admin.site.register(Report) admin.site.register(Person) -
User Model Customisation in Dotnet
I used to work with django , but recently i got a new project with dotnet and I got confused when creating the user model , should I extend IdentityUser or create a user profile and leave the IdentityUser unchanged . -
Can I display model Post and model Topic all in one
Can I display model Post and model Topic all in one and add virtual field for know when loop it in template class Topic(models.Model): title = models.CharField(max_length=250) excerpt = models.TextField(default='0') class Post(models.Model): title = models.CharField(max_length=250) excerpt = models.TextField(default='0') class allon(Topic,Post): def home(request): all_posts = allon.objects.all( ) return render(request, 'forum/home.html', {'edd': all_posts }) -
ODBC Driver 17 for SQL Server: Client unable to establish connection, macOS, django, pyodbc
Everything was working until I restarted my laptop. I have this setup: python 3.8.8 django 3.1.1 pyodbc 4.0.30 pyodbc.drivers(): ['ODBC Driver 17 for SQL Server'] SQLServer cat /etc/odbcinst.ini returns this: [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/usr/local/lib/libmsodbcsql.17.dylib UsageCount=10 cat /etc/odbc.ini returns this: # [DSN name] [MSSQL] Driver = ODBC Driver 17 for SQL Server Server = tcp:<my server>,1433 in the django settings: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } I reinstalled the ODBC Driver with this official Microsoft instruction. But it didn't help. I'm still failing to start the django server and facing this error: django.db.utils.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Client unable to establish connection (0) (SQLDriverConnect)') That's pretty weird that everything was working for a long time until I restarted my laptop (no OS update, just restarting). May be this issue related to exporting some variables with path? Or may be after the ODBC Driver installation on macOS I need to set up this driver somehow? P.S.: jdbc driver works without any issues with the same servername, … -
I keep getting this error NOT NULL constraint failed: lists_listcreate.user_id
I am trying to make a site where users can make lists and then view those lists. How my site is set up is the user creates the list and gives it a name and then they move on to the next page where they can add items to their list. The login prosses works fine and you can go to the creat list page just fine. however, when you hit next on the create list page and try to go to the page where you go to the page where you add items to the list it gives you this error: IntegrityError at /your_lists/new_list/ NOT NULL constraint failed: lists_listcreate.user_id Views: from django.shortcuts import render from .models import List, ListIcon, ListCreate from django.views.generic import TemplateView, CreateView from django.views.generic.edit import FormView from django.contrib.auth.mixins import LoginRequiredMixin from . import models from .forms import AddListItemForm, CreatListForm from django.http import HttpResponseRedirect # Create your views here. class CreateList(CreateView, LoginRequiredMixin): model = ListCreate form_class = CreatListForm template_name ="lists/list_form.html" success_url = '/add_item/' class AddListItem(CreateView, LoginRequiredMixin): model = List form_class = AddListItemForm template_name = "lists/AddListItem.html" def index(requst): list = CreateList.objects.all() if request.method == "POST": if "add_one_more" in requst.POST: list.save() return redirect("/") if "done" in requst.POST: return redirect("/lists/your_lists/") … -
Wagtail CMS how to validate the content of one page before publishing or saving it as draft
I am trying to make a page with Wagtail CMS that validates the content whenever I save/publish the page inside the admin editor. The content that I want to be validated is the content of 3 SnippetChooserPanels from within the page. Basically let's say I have these 3 snippets : SnippetA, SnippetB and SnippetC and these snippets (or Django models because that's what they really are) have the following relationships: SnippetA has one to many relationship with SnippetB SnippetB has one to many relationship with SnippetC. When the user saves/publishes the page I want to verify: that all the 3 snippet types have been chosen that there is a correct relationship between the snippets (ie SnippetC belongs to SnippetB , and SnippetB belongs to SnippetsA, or in other words the 3 snippets are joined together correctly in SQL database terms) Thank you! -
How do you initialize a Django FileField with multiple files?
I have a model that saves multiple uploaded files for a document. I was able to use the FileField widget on the form to allow for multiple file uploads. However, whenever I went to update the document object, the FileField widget would not populate with the initial data. I was finally able to figure out that I needed to set the initial data and a URL on the initial data for the widget to render appropriately. But it just wasn't working out with a list of File objects. How can I get this to work right?