Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17)
I built an website in Django & went to go upload it to aws using zappa following this tutorial. I am running a virtual environment using python3.8.1. When I deploy using Zappa I get this error: Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code. Checking the logs using zappa tail I get this: ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). When I check the sqlite3 version I get this: (env)$ python Python 3.8.1 (default, Dec 27 2019, 18:06:00) >>> import sqlite3 >>> sqlite3.sqlite_version '3.31.1' When I check for just sqlite (just to be sure) I get this: >>> import sqlite Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'sqlite' When I check the Django version I get this: >>> django.VERSION (3, 0, 4, 'final', 0) I tried to use these resources to solve it but couldn't get anywhere (I think because I am new & confused): How to upgrade sqlite 3.8.2 to >= 3.8.3 How to upgrade sqlite3 version in Python from 3.7.17 to > 3.8 Using SQLite3 with Django 2.2 and Python 3.6.7 … -
How can I set subapps in django?
I have two apps under one project and decide to move these two apps under apps parent directory. My current structure is, project - app1 - app2 - project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py New structure I am trying to have, project - templates - static - apps - app1 - app2 - project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py Following to this, How to keep all my django applications in specific folder I edited my settings.py from os.path import abspath, basename, dirname, join BASE_DIR = dirname(dirname(abspath(__file))) PROJECT_ROOT = dirname(__file__) sys.path.insert(0, join(PROJECT_ROOT, 'apps')) INSTALLED_APPS = [ .... 'apps.app1.apps.App1Config', 'apps.app2.apps.App2Config', ] I got an error that ModuleNOtFoundError: No module named 'app1' Where should I have to edit to fix this issue? -
Run a if clause on a @receiver in Django
I have a model Client which uses a @receiver to update its fields whenever a User is created. class Clients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") city = models.CharField(max_length=200, verbose_name="Cidade") postal = models.CharField(max_length=8, validators=[RegexValidator(r'^\d{4}(-\d{3})?$')], verbose_name="Código Postal") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Meta: verbose_name_plural = "Clientes" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Clients.objects.create(user=instance) instance.clients.save() Is there a way to only run this if the user created belongs to a specific group? -
Using Django form FileField with custom file
I'm creating a form builder for my project. It builds forms dynamically according to fields specified in database. There are 3 tables: form, form fields and form fields values. Now I'm trying to bind data from form values to form fields. It works well, for example like this: if (field.field_type == 'long_text'): new_field = forms.CharField(label=field.label, initial = value, required=False, widget=forms.Textarea(attrs={'class': 'form-control'})) But this doesn't work for FileField: new_field = forms.FileField(label=field.label, required = False, initial = initialData) As far as I understand, "initial" data has to be in certain format: this has to be an object with url and name attributes This is what I do: try: ''' data is stored in JSON {url:'', name:''} format ''' valueData = json.loads(value) initialData.initial = valueData['name'] initialData.url = valueData['url'] initialData.name = valueData['url'] except: pass new_field = forms.FileField(label=field.label, required = False, initial = initialData) Form is still empty. No "clear" checkbox, no url to click and "no file selected". What can I do to make this file input work? Do I need to emulate model's filefield? -
Looking for read-write lock in Django using PostgreSQL, e.g., SELECT FOR SHARE
I am locking for a read-write lock in Django, using PostgreSQL. I know select_for_update On top, I need SELECT FOR SHARE I founds this super old Django-ticket I couldn't find any third party library implementing this for Django Now I am wondering: Is there a good reason this was not implemented in the Django-ORM? Does anyone know any third party library for this? Or any easy work around? -
Translating Django site into multiple languages?
I have a a Django site with 10-15 models/tables. Each row needs to be translated into at least 4 or 5 languages. What is the most efficient way of implementing localization? I've read you can use .po files. But one would have to mark every single single that needs to be translated, which seems tedious. There are modules that create additional fields for additional languages. This seems to blown up the DB unreasonably. -
Django, ModelChoiceField() and initial value with formset not working
I have the form below in my forms.py. I am setting the self.fields['start'] to ModelChoiceField with queryset=Flow.objects.all(). class GroupForm(ModelForm): class meta: model = Group fields=['conditionn', 'start'] def __init__(self, *args, **kwargs): super(GroupForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.fields['condition'] = forms.CharField(label='Post Condition', widget=forms.TextInput( attrs={'placeholder': 'The system displays the "Home" button'})) #to check what is in the initial initial = kwargs.get('initial', {}) print("wow",initial) self.fields['start'] = forms.ModelChoiceField(label='Success or Abort', widget=forms.Select, queryset=Flow.objects.all()) GroupInlineFormSet = inlineformset_factory(ParentModel, BoundedFlowGroup, form=BoundedFlowGroupForm) In my views, I have class UpdateGroup(Updateview): ... def get_context_data(self, **kwargs): print(self.object) context = super(UseCaseUpdateView, self).get_context_data(**kwargs) if self.request.POST: .... else: context['Another_form'] = AnotherFormSet(instance=self.object, prefix='group') groupQuerySet=context['Another_form'].instance.group_set.all() flowQuerySet=basicGroupQuerySet[0].flow_set.all() context['boundedGroupNested_form'] = BoundedGroupNestedFormSet(initial=[{'start':flowQuerySet}], instance=self.object, prefix='boundedFlowGroup') return context .... Now, in the view, I am trying to set the start initial values with initial=[{'start':flowQuerySet}]. When I print out the flowQuerySet I got the correct values I would need for the start field. However, when I view my render template, I am see all the instances of Flow instead of the ones from the flowQuerySet. So, If the are 1,2,3,4,5,6 Flows and flowQuerySet has only 5, 2,1 - I want only 5,2,1 as selection option in the ModelChoiceField of start, but I am still getting 1,2,3,4,5,6. How do I set the model's instances for … -
Getting complete and exact definition of a Django model attribute
Suppose that I have User model as this: class User(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40, blank=True, null=True) password = models.CharField(min_lengj) connections = models.DecimalField(max_digits=3, default=0, blank=False) ... (other attributes) For a special use case I need to know the exact definition of its fields so I can get definition of connections as a DecimalField with max_digits equal to 3 and default equal to 0 and cannot be blank. How I can acheieve this? -
Django templates won't load but HttpResponse will (repost)
I recently began learning django and have been running into some trouble and I can't figure out why. My problem is quite simple: whenever I try to run my homepage with a template, it throws up a 404 error. My file hierarchy is as such: crm accounts templates accounts dashboard.html urls.py views.py crm urls.py In crm/urls, I have from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')) Then in accounts/urls, there is, from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] And in views, I have from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'accounts/dashboard.html') My dashboard.html is just a basic html file with a title and h1, that's it. Also, whenever I change return render(request, 'dashboard.html') to return HttpResponse('home') in my home function, it decides to show. I have tried recreating the project, uninstalling and reinstalling django, renaming a few things, but none of them seemed to work. -
Django admin: Replicating InLine data when using "Save as New"
I have 2 models: class Series(models.Model): puzzles = models.ManyToManyField(Puzzle, through='SeriesElement', related_name='series') class SeriesElement(models.Model): puzzle = models.ForeignKey(Puzzle, on_delete=models.CASCADE, verbose_name='Puzzle', ) series = models.ForeignKey(Series, on_delete=models.CASCADE, verbose_name='Series', ) puzzle_index = models.PositiveIntegerField(verbose_name='Order', default=0, editable=True, ) class Meta: unique_together = ['puzzle', 'series', 'puzzle_index'] ordering=['puzzle_index'] and the admin Page of Series displays an inline of SeriesElement. class SeriesAdmin(admin.ModelAdmin): save_as = True inlines = (SeriesElementInline,) When I am clicking "save as new", then an error occur going through the net, I gathered that I need to override save_formset, and the following approach seems to be almost working: def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) pdb.set_trace() # for debug for i in instances: if hasattr(i, 'puzzle_id') and not i.puzzle_id: i.puzzle_id = request.puzzle_id # not working i.puzzle_index= request.puzzle_index # not working i.save() formset.save_m2m() super(SeriesAdmin, self).save_formset(request, form, formset, change) However I am not able to figure out how I could recover the original puzzle_id and puzzle_index to be able to re-create SeriesElements that refer to the new series in the code, what should I put instead of request.puzzle_id and request.puzzle_index to retrieve the original values? PS: here is the content of request.POST where all elements seem to be accessible, but I don't know how to get them properly: … -
How do you not create an object when creating a User in Django?
I have a Client model with an User ForeignKey. So, whenever I create a Client I also create an User. This is the Client model: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") city = models.CharField(max_length=200, verbose_name="Cidade") postal = models.CharField(max_length=8, validators=[RegexValidator(r'^\d{4}(-\d{3})?$')], verbose_name="Código Postal") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Meta: verbose_name_plural = "Clientes" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Client.objects.create(user=instance) instance.client.save() And this is the view: @login_required(login_url='./accounts/login/') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() # this creates the user with first_name, email and last_name as well! group = Group.objects.get(name='Clients') user.groups.add(group) user.refresh_from_db() # load the profile instance created by the signal user.client.address = form.cleaned_data.get('address') user.client.city = form.cleaned_data.get('city') user.client.postal = form.cleaned_data.get('postal') user.client.nif = form.cleaned_data.get('nif') user.client.mobile = form.cleaned_data.get('mobile') return redirect('client') else: form = SignUpForm() return render(request, 'backend/new_client.html', {'form': form}) And this the form: class SignUpForm(UserCreationForm): address = forms.CharField(max_length=200, label="Morada", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Av. da Liberdade, 170',})) nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Deve conter 9 dígitos',})) mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Deve conter 9 dígitos',})) city = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Lisboa',})) postal = forms.CharField(max_length=8, … -
Django database structure change to allow multiselect
I am working on a project that requires some database structure changes to allow the users to select multiple values at once. My current structure consists of a chained model relationship as follow: class Service_Specific(models.Model): title = models.CharField(max_length=100, help_text="title of service specific") category = models.ForeignKey(Service_Category, on_delete=models.CASCADE, null=True, help_text="Id of service category") group = models.ForeignKey(Service_Group, on_delete=models.CASCADE, null=True, help_text="Id of service group") type = models.ForeignKey(Service_Type, on_delete=models.CASCADE, null=True, help_text="Id of service type") variant = models.ForeignKey(Service_Variant, on_delete=models.CASCADE, null=True, blank=True, help_text="Id of service variant") tags = TaggableManager(blank=True) def __str__(self): return '%s / %s / %s / %s' %(self.group, self.type, self.variant, self.title) def save(self, *args, **kwargs): self.category = self.variant.category self.group = self.variant.group self.type = self.variant.type return super(Service_Specific, self).save(*args, **kwargs) For now, this model is used to add services to a user who is a Service Provider and it's working fine. ( 1 service at a time ) example (service_variant = "guitar lessons" -> service_specific = "electric guitar" ) The issue is that users tend to offer multiple services related to the same service_variant and they got annoyed because they can not select them all at once. Can somebody help me find the right strategy ?? Thank you. here is my provider service model: class ProviderService(models.Model): provider … -
how can i insert dynamic fields of a form in django into database
i have a form with checkbox inputs the number of inputs is dynamic because i get it from the database,in my form i might have 2 or 3 or N .. checkbox.then from these input the user will check some or all of them and then he click the submit button the problem is that only one input is saved into database and how can i insert it all. can any one help me please i hope the problem is clear.this is my code for the form : ` <form method="post" action="createQcm"> {% csrf_token %} {% for mati in quest %} <INPUT type="checkbox" value ="{{mati.id_question }}" name="choix" > {{mati.questionA }}</input></br></br> {% endfor %} <input type="hidden" name="s" value="{{idQ}}" readonly> ` the view: ` def createQcm(request): q=request.POST["choix"] r=request.POST["s"] rep = contenir(idQuestion=q,idQuiz=r) rep.save() return render(request,'myblog/subject.html') ` -
Django - Checking if user has logged in before
when a user signs up, they get redirected to the homepage. If it is their first time logging in, I want to display a div, however if it is not their first time, I do not want this div to appear. Currently, I am relying on date_joined andlast_login to do this check. However this only checks dates and not the time. Therefore the div will still appear until the date has changed. I only want the div displayed once. This is when the user first logs in. Here is my code so far: views.py: def home(request): context={} user = request.user if user.last_login.date() == user.date_joined.date(): context['isFirstTime'] = 'isFirstTime' else: pass return render(request, 'home.html', context) template: {% if isFirstTime %} <div style="width: 300px; height: 300px; background-color: green;"> </div> {% endif %} Does anybody know how I can alter this so it works with the current time and not the current date. This way the div is only displayed when a user first logs in. Anybody know a solution? Thank you. Also date_joined and last_login are datetime objects stored in the database. -
Django matching a url with paramater to start
In Django 3 I've got a site I'm working on where I need to match a paramater at the start of the url. So test.com/the-data-slug What is odd is I can't figure out why the following code dosen't work. It dosen't match at all. path('<slug:data-slug>/', DataLandingView.as_view(), name="data_landing") I did get the following to work, but I know path is prefered over re_path. re_path(r'^(?P<data-slug>\w+)/$', DataLandingView.as_view(), name="data_landing") I'm really curious what I'm doing wrong with the path call, or is this just something path can't do? -
DRF get only the first serialized instance for list view?
I'm working on a real estate app and want the listings to show only the first image of the Listing. Currently it is showing all images. class Image(models.Model): photo = models.ImageField(blank=True, upload_to=get_image_filename) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) class ImageSerializerForListingList(serializers.ModelSerializer): photo = serializers.ImageField() class Meta: model = Image fields = ('photo', ) class ListingListSerializer(serializers.HyperlinkedModelSerializer): image = ImageSerializerForListingList(many=True, required=False, source='image_set') class Meta: model = Listing fields = ('url', 'address', 'image', ) def get_first_image(self, obj): image = obj.image_set.all().first() return ImageSerializerForListingList(image, many=True).data This is still showing all images, Any advice on this? -
Unable to connect Django Rest framework application with GCP cloud SQL
I created a could SQL instance on GCP for MySql 5.7. I am trying to connect it with Django Rest framework application. I am also using Docker to containerize Django application. I am running Django application on localhost but for MySql I want to use GCP cloud Sql. I got the public IP address of the cloud Sql instance once it was up and running. Then I created a database eitan_database with user jeet and password root. In Django project's settings.py file I updated the database settings as following - DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'eitan_database', 'USER': 'jeet', 'PASSWORD': 'root', 'HOST': '35.239.xxx.x', 'PORT': 3306, } } I have used public IP for HOST and for PORT Mysql default 3306. I don't understand what is wrong with the database configuration but when I run server I get the following error. Traceback (most recent call last): eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection eitan-application_1 | self.connect() eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner eitan-application_1 | return func(*args, **kwargs) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect eitan-application_1 | self.connection = self.get_new_connection(conn_params) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner eitan-application_1 | return func(*args, **kwargs) eitan-application_1 | File … -
Download button with function, react
I am using Django and react to make a website. I want to be able to download a websitepost, locally on my computer as a website user. <button className={styles.button} onClick={() => {}}> </button>` How do i finish this button? And what functionality am I missing? -
Accessing localhost not possible on MacOS
my situation is that the website I'm building has a landing page the main App page and the API section. They are respectively reachable with [domain_name], app.[domain_name] and api.[domain_name]. When calling those I don't have any problems reaching them in any browser. When I host them however in my local environment then api.localhost does only work when I call it with Postman. When I try to ping the api.localhost it only says: ping: cannot resolve api.localhost: Unknown host On other systems, this will get a response. In terms of Django Cors stuff, it all seems to be managed correctly as it is working on other systems. But I can add any code if asked for such, just don't want to add everything that I can think of from the Django project. I have no idea what to try or what to change so any help would be beneficial. -
How can form fields be rendered manually in django-bootstrap-datepicker-plus
I have django-bootstrap-datepicker-plus set up in my app. Upon completion, I noticed that my form fields are stacked on rows screenshot whereas I would love to manually render some of the fields on the same row. Although I know the reason for that is because the form is rendered using {% bootstrap_form form %} Here is my rendered template code snippet below. {% extends 'accounts/no_header_footer.html' %} {% block content %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {{ form.media }} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script> <div class="profile-create-form-container"> <form class="profile-create-form" data-certificates-url="{% url 'ajax_load_certificates' %}" data-grades-url="{% url 'ajax_load_grades' %}" data-relationships-url="{% url 'ajax_load_relationships' %}" data-states-url="{% url 'ajax_load_states' %}" enctype="multipart/form-data" id="ProfileCreateForm" method="POST" runat="server"> {% csrf_token %} <fieldset class="form-group text-center"> <span class="navbar-brand"> <img alt="..." height="40px" src="..." width="40px"> Basic Information </span> </fieldset> {% bootstrap_form form %} <div class="container"> <div class="text-center"> <button class="btn btn-dark" type="submit"> <i class="fa fa-save"></i> Save and Continue </button> </div> </div> </form> </div> The question I have is, is it possible to render each form field manually? -
Cannot get Foreignkey Model to Save to Sqlite Database with Django
I have looked over every article on everything that has ever been posted and none of the resolutions seem to fix my issues. I can't seem to get input from my view to save to my database. Theoretically the user will input a contact and business and the contact will associate with the business and the contact will be added however I am like 99% sure I am wrong somewhere, I am just 100% sure I don't know where: Models from django.db import models class Business(models.Model): business_name = models.CharField(max_length=30, unique=True) date_created = models.DateField(auto_now=True) def __str__(self): return self.business_name class Contact(models.Model): name = models.CharField(max_length=30) title = models.CharField(max_length=30) number = models.CharField(max_length=13) email = models.EmailField() business = models.ForeignKey(Business, on_delete=models.CASCADE) def __str__(self): return "%s - %s" % (self.name, self.business) Forms from django import forms from .models import Contact, Business class ContactForm(forms.ModelForm): def __init__(self, business, *args, **kwargs ): super(ContactForm, self).__init__(business, *args, **kwargs) self.fields['business'].queryset = forms.ModelMultipleChoiceField(queryset=business) class Meta: model = Contact fields = ['name', 'title', 'number', 'email', 'business'] class BusinessForm(forms.ModelForm): class Meta: model = Business fields = ['business_name'] Views def add_contact(request): all_contacts = Contact.objects.all if request.method == "POST": business = get_object_or_404(Business, business_name=request.POST['business']) form = ContactForm(request.POST, instance=business) # print(form) if form.is_valid(): new_form = form.save(commit=False) new_form.business = form.business print(new_form) … -
ValueError at /admin/listings/listing/add/
Invalid format string Request Method: POST Request URL: http://localhost:8000/admin/listings/listing/add/ Django Version: 3.0.4 Exception Type: ValueError Exception Value: Invalid format string Exception Location: C:\Users\Ayesha Siddiqha\btre_project\venv\lib\site-packages\django\db\models\fields\files.py in generate_filename, line 305 Python Executable: C:\Users\Ayesha Siddiqha\btre_project\venv\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Ayesha Siddiqha\btre_project', 'C:\Users\Ayesha ' 'Siddiqha\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\Ayesha ' 'Siddiqha\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\Ayesha ' 'Siddiqha\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\Ayesha Siddiqha\AppData\Local\Programs\Python\Python38-32', 'C:\Users\Ayesha Siddiqha\btre_project\venv', 'C:\Users\Ayesha Siddiqha\btre_project\venv\lib\site-packages'] -
Unable to host django on IIS using Fast CGI (wfastcgi). Getting 500 error in browser
I am unable to host a basic django project in IIS. I have been breaking my head over 2 days now and help would be greeeaaatly appreciated :). I have enabled IIS, CGI, and others under the Application Development in IIS. This is my folder structure after creating a simple django project via the below command: django-admin startproject dijky Folder structure: + C:\inetpub\wwwroot + dijky + dijky - __init__.py - settings.py - urls.py - wsgi.py - manage.py - web.config - wfastcgi.py I have copied the wfastcgi.py file into my project folder. I have then Added a website named "dijky" with the below settings Under the Machine name in IIS, Clicked on FastCGI Settings, and have given the Full path and Arguments as so: Then gave the environment variables as: I even tried setting the WSGI_HANDLER to dijky.wsgi.application, since the file C:\inetpub\wwwroot\dijky\dijky\wsgi.py has: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dijky.settings") application = get_wsgi_application() Both don't work My web.config XML file is: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="djangoappiis" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Users\xxxxxxx\Anaconda3\envs\djangy\python.exe|C:\inetpub\wwwroot\dijky\wfastcgi.py" resourceType="Unspecified" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\dijky" /> <add key="DJANGO_SETTINGS_MODULE" value="dijky.settings" /> </appSettings> </configuration> After Starting the server … -
Create a field with grouped attributes from the model in DRF
I want to group a specific attributes from a model instead of serializing them individually more or less like this class MyModel(models.Model): attr1 = models.IntegerField() attr2 = models.IntegerField() attr3 = models.CharField() and serialize will output this { # other attrs "grouped_attrs" : {"attr1": 23, "attr2": 848, "attr3": "foo"} # other attrs } -
Server Connection Refused - Django/Postgresql
I want to preface that everything works on my other computer but with the new macbook I got, I am trying to determine the cause of the issue. The issue is when attempting to run python manage.py runserver with my Django project with PostgreSQL. I have made sure to install all my node modules and dependencies, I have re-installed PostgreSQL using homebrew and have started my postgres. waiting for server to start....2020-03-11 13:49:40.157 EDT [88879] LOG: starting PostgreSQL 12.2 on x86_64-apple-darwin18.7.0, compiled by Apple clang version 11.0.0 (clang-1100.0.33.17), 64-bit 2020-03-11 13:49:40.159 EDT [88879] LOG: listening on IPv6 address "::1", port 5432 2020-03-11 13:49:40.159 EDT [88879] LOG: listening on IPv4 address "127.0.0.1", port 5432 2020-03-11 13:49:40.160 EDT [88879] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432" 2020-03-11 13:49:40.168 EDT [88880] LOG: database system was shut down at 2020-03-11 13:45:10 EDT 2020-03-11 13:49:40.171 EDT [88879] LOG: database system is ready to accept connections done server started But for whatever reason, I get the following: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/neme/.local/share/virtualenvs/project-azure-87EjIYum/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/Users/neme/.local/share/virtualenvs/project-azure-87EjIYum/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, …