Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting 400 bad request on angular post request how can i fix this
please i need help on my angular and django project and i'm getting a 400 bad response error when i make a post request,the project work flow is as follows, the user signup(which is successful) then get redirected to a profile form then when i try making a post request after filling the profile i get a 400 err, below is my code and d err response angular services.ts addProfile(profile: Iprofile): Observable<Iprofile>{ const url = 'http://127.0.0.1:8000/user/profiles'; return this.httpClient.post<Iprofile>(url, profile) .pipe( map(response => response), catchError(this.handleError) ); } create profile component.ts addUpdateProfile(){ if (this.profile) { this.dataService.updateProfile(this.profileForm.value) .subscribe(item => this.profiles.push(this.profileForm.value)); } else { this.dataService.addProfile(this.profileForm.value) .subscribe(item => this.profiles.push(this.profileForm.value)); } } django urls path('profiles', CreateProfileView.as_view(), name='user-profile'), django views class CreateProfileView(generics.ListCreateAPIView): queryset = Profile.objects.all() serializer_class = UserDetailSerializer err response Bad Request: /user/profiles [14/May/2020 17:07:04] "POST /user/profiles HTTP/1.1" 400 46 will b glad if anyone can help me -
Getting 'ERR_TOO_MANY_REDIRECTS' error when using custom Middleware in Django
I am trying to use a custom Middleware to restrict page access when the user is not authenticated. I have defined a list of URLs in 'settings.py' which are supposed to be exempted from this restriction. But when I try to access any page, I get an 'ERR_TOO_MANY_REDIRECTS' error. Please feel to ask for more clarification and code references if required. settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'accounts.middleware.LoginRequiredMiddleware', ] LOGIN_URL = 'home' LOGIN_REDIRECT_URL = '/' LOGIN_EXEMPT_URLS = [ r'^accounts/login/$', r'^accounts/register/$', r'^accounts/logout/$', ] middleware.py import re from django.conf import settings from django.shortcuts import redirect EXEMPT_URLS = [] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): print('inside init') self.get_response = get_response def __call__(self, request): print('inside call') response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): print('inside view_process') path = request.path_info.lstrip('/') print(path) #assert hasattr(request, 'user') if not request.user.is_authenticated: print('user not authenticated') if not any(url.match(path) for url in EXEMPT_URLS): print('redirecting to login url') return redirect(settings.LOGIN_URL) urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home, name = 'home'), path('product', views.product, name = 'product'), path('createOrder', views.createOrder, name = 'createOrder'), path('updateOrder/<str:pk>', views.updateOrder, name = … -
How to trigger AJAX request without POST request in Django?Rather initiate onClick
So I am new in here , currently working on a Django project. So I was facing an Issue. Let me give a detailed description of the problem: So I have a model called Music: class Music(models.Model): musicid = models.AutoField(primary_key=True) title = models.CharField(max_length=200) # category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') audio = models.FileField(upload_to='music/') published_at = models.DateTimeField(default=datetime.now , blank=True) def __str__(self): return str(self.musicid) View File is as follows def index(request): songs = Music.objects.all() context = { 'title':'Home', 'songs':songs, } return render(request , 'index.html',context) So now in my html i render all my music which i am storing in my local DB. They can be easily fetched via the getting the url of audio file.Now I made a common Player for all my songs. Here comes the real ISSUE. Suppose I have 10 songs , and I click any one of them , how do I send an AJAX request with the specific music id so that I can render the audio url for that specific song. <audio id="music" class="current-track" > <source src="{{songs.audio.url}}" type="audio/mpeg"> </audio> here songs is the queryset of the specific song id. I am using AJAX as it's clearly evident I dont want the page to redirect to somewhere else … -
Django issue on reversing custom action url
I'm trying to test a custom url I've created in a ModelViewSet. Here's the code The problem comes with reverse_action() method. I keep getting the following error: > self.url = MacroViewSet.reverse_action(url_name='add-student', args=[self.macro.id]) E TypeError: reverse_action() missing 1 required positional argument: 'self' This previous question, as the django rest framework guide itself, show the following solution view.reverse_action('set-password', args=['1']) I don't understand what is that view object and why my code breaks -
Alternative method of using slug in newer versions of django
I have been following along the Try django 1.10 URL Shortening Playlist (CodingEntrepreneur) and I am fairly new at django. In the 20th video of the series, they used slug regex with URLs, however when I tried the same, it threw an error, and someone has commented that slug doesn't work with "paths". Can someone please help me with finding the alternative to it? -
After signup redirect user to login page
I am using django-allauth , after signing up on site the user is sent to profile page but I want the user to go to the login page after signing up with a message "your account has been created" Is there any way to do this? -
Django: _meta.get_fields() : include_parents=False : Shows fields derived from inheritance
I have the following model: class CommonModel(models.Model): """ Default Common Variables In Database """ class Meta: abstract = True created_by = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_created_by", null=True, blank=True,on_delete=models.SET(get_sentinel_user)) modified_by = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_modified_by", null=True, blank=True,on_delete=models.SET(get_sentinel_user)) deleted_by = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_deleted_by", null=True, blank=True,on_delete=models.SET(get_sentinel_user)) is_deleted = models.BooleanField(default=False) created_date = models.DateTimeField(blank=True) deleted_date = models.DateTimeField(null=True, blank=True) modified_date = models.DateTimeField(auto_now=True) class Article(CommonModel): title = models.CharField(max_length=256) intro_image = models.ImageField(null=True, blank=True, upload_to=doc_hash) description = models.TextField(null=True, blank=True) url = models.CharField(max_length=256, null=True, blank=True) slug = models.SlugField(editable=False) I am trying the following in ipython > Article._meta.get_fields() (<django.db.models.fields.AutoField: id>, <django.db.models.fields.related.ForeignKey: created_by>, <django.db.models.fields.related.ForeignKey: modified_by>, <django.db.models.fields.related.ForeignKey: deleted_by>, <django.db.models.fields.BooleanField: is_deleted>, <django.db.models.fields.DateTimeField: created_date>, <django.db.models.fields.DateTimeField: deleted_date>, <django.db.models.fields.DateTimeField: modified_date>, <django.db.models.fields.CharField: title>, <django.db.models.fields.files.ImageField: intro_image>, <django.db.models.fields.TextField: description>, <django.db.models.fields.CharField: url>, <django.db.models.fields.SlugField: slug> I try with include_parents=False > Article._meta.get_fields(include_parents=False) (<django.db.models.fields.AutoField: id>, <django.db.models.fields.related.ForeignKey: created_by>, <django.db.models.fields.related.ForeignKey: modified_by>, <django.db.models.fields.related.ForeignKey: deleted_by>, <django.db.models.fields.BooleanField: is_deleted>, <django.db.models.fields.DateTimeField: created_date>, <django.db.models.fields.DateTimeField: deleted_date>, <django.db.models.fields.DateTimeField: modified_date>, <django.db.models.fields.CharField: title>, <django.db.models.fields.files.ImageField: intro_image>, <django.db.models.fields.TextField: description>, <django.db.models.fields.CharField: url>, <django.db.models.fields.SlugField: slug> It shows the same results. I think it should not show the fields inherited from the CommonModel Can some explain what does include_parents=False in this case will do. -
Elastic-beanstalk build pre-deploy and run command post-deploy
I am new to Elastic-beanstalk. I tried using CLI but got little confused. I have a typescript project which has to build first and then dist folders contents need to be deployed. Currently I manually build and compress dist folder into zip file and then upload. Also, there is a command to run from production enviroment which I currently do by switch all my enviroment and then manually migrate. I know there is some thing called extentions or config file. Please guide me to automate the above process with those extentions. # pre-deploy yarn build # generated file in dist folder # deployed the folder # post-deploy # in production enviroment npm run migrate -
Django CRC Calculator?
Trying to build an endpoint that takes an input string, polynomial and initial value and outputs a CRC value. Everything I've found so far only support existing algorithms and do not take additional inputs. I finally found one that takes all kinds of inputs (pycrc) but it seems to only do so via CLI. How would I go about incorporating pycrc into Django? Thanks! -
How to rewrite this postgres constraint to be more in line with django 2.2?
THis is the raw query that I write for postgres for the check constraint ALTER TABLE rea_asplinkage ADD CONSTRAINT asp_sub_project_positive_integer CHECK ( jsonb_typeof(linkage-> 'root' -> 'in_sub_project') is not distinct from 'number' and (linkage->'root'->>'in_sub_project')::numeric % 1 = 0 and (linkage->'root'->>'in_sub_project')::numeric > 0 ); And the way I create the migration is this way # Generated by Django 2.2.10 on 2020-05-16 12:59 from django.db import connection, migrations class Migration(migrations.Migration): dependencies = [("rea", "0029_asplinkage")] operations = [ migrations.RunSQL( sql=""" ALTER TABLE rea_asplinkage ADD CONSTRAINT asp_sub_project_positive_integer CHECK ( jsonb_typeof(linkage-> 'root' -> 'in_sub_project') is not distinct from 'number' and (linkage->'root'->>'in_sub_project')::numeric % 1 = 0 and (linkage->'root'->>'in_sub_project')::numeric > 0 ); """, reverse_sql=""" ALTER TABLE rea_asplinkage DROP CONSTRAINT "asp_sub_project_positive_integer"; """, ) ] And this works. But this means that my original model does not show the constraint in the class Meta of the ASPLinkage model class ASPLinkage(TimeStampedModel, SoftDeletableModel, PersonStampedModel, OrganizationOwnedModel): linkage = JSONField(default=default_linkage_for_asp) objects = OrganizationOwnedSoftDeletableManager() I have tried ExpressionWrapper and RawSQL in creating the constraints inside the class Meta, but it still doesn't work. For reference, I have looked at the examples found in https://github.com/django/django/blob/master/tests/constraints/models.py#L12 I have also looked at Separate Database and State migration via https://realpython.com/create-django-index-without-downtime/#when-django-generates-a-new-migration But I still cannot get it to work So … -
SSL Problem with GAE App Engine w/o custom domain/SSL certificate
I deployed my locally functioning django project with two apps to the GAE. I also tested the MySQL DB at GCP by using the proxy tool provided by GCP. Although I have successfully deployed the project to the App Engine, it is not working on the GAE. I tested the URL with Chrome, IE and Safari. This is what Chrome says: This site can’t provide a secure connection <project-id>.oa.r.appspot.com sent an invalid response. Try running Windows Network Diagnostics. ERR_SSL_PROTOCOL_ERROR This is what curl says: (ll_env)> curl https://<project-id>.oa.r.appspot.com curl : The request was aborted: Could not create SSL/TLS secure channel. At line:1 char:1 + curl https://<project-id>.oa.r.appspot.com + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand I tested following settings without success: USE_X_FORWARDED_HOST = True on the settings.py ALLOWED_HOSTS = ['*'] on the settings.py -
In Django what is the right way of adding form field from another form in a formset?
I've got some nested formsets within a formset and I'd like to flatten it but I'm struggling with creating the fields. So far I have the below; class BaseHostFormset(BaseModelFormSet): def add_fields(self, form, index): super(BaseHostFormset, self).add_fields(form, index) form.nested = VLanInlineFormset(instance=form.instance, data=form.data if form.is_bound else None, files=form.files if form.is_bound else None, prefix='Vlan-%s-%s' % ( form.prefix, VLanInlineFormset.get_default_prefix())) for nested_form in form.nested.forms: for field in nested_form: if field.name is not None and nested_form['vlan_name'].value() is not None: field_name = nested_form['vlan_name'].value() + "_" + field.name form.fields[field_name] = nested_form[field.name] but when I iterate over the form I get; AttributeError: 'BoundField' object has no attribute 'get_bound_field' Which makes sense I think as the add_fields method is expecting a forms.CharField object but I want to keep the attirbutes from the other forms fields. What would be the right way to do this? -
Django TestCase not creating/deleting model instances
I'm having a few problems when running some of my tests. For instance say I have a view # view.py class DeleteAccount(DeleteView) model = User ... As expected, when I send a valid post request, the given User object is deleted. However, when I make this request from a test, the User object is not deleted: # tests.py class DeleteAccountTest(TestCase): def test_delete_user(self): email = 'test@email.com' user = User.objects.create_user(email=email) response = self.client.post(reverse('delete_account', args=[email])) self.assertEqual(response.status_code, 302) delete_user = User.objects.filter(email=email) self.assertFalse(delete_user.exists()) This final assertion fails as the deleted user is still in the db. Since this works outside of tests, I am assuming there is something going on behind the scenes that I am not seeing. I am getting the same problem when creating Model objects in views too. An explanation to what I'm doing wrong would be greatly appreciated. Thanks -
Why am i getting the error NoReverseMatch at /?
I am trying to build a blogsite on django. I am a beginner and I don't know why am I getting this error. Please help me solving this error. I am providing my code views.py, models.py, and base.html file #models.py from django.db import models from django.urls import reverse class Post(models.Model): author = models.ForeignKey( 'auth.User', on_delete = models.CASCADE, null = True ) title = models.CharField(max_length = 20, default='') text = models.TextField() def __str__(self): return self.title def get_absolute_url(self): # new return reverse('blog_post_details', args=[str(self.id)]) views.py from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView from .models import Post class HomeResponse(ListView): model = Post template_name = 'home.html' class PostDetail(DetailView): """docstring for PostDetail""" model = Post template_name = 'post_detail.html' class NewPost(CreateView): model = Post template_name = 'new_post.html' fields = '__all__' This is my code for urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.HomeResponse.as_view(), name='blog_name'), path('post/new/', views.NewPost.as_view(), name='blog_new_post'), path('post/<int:pk>/',views.PostDetail.as_view(),name='blog_post_details'), ] base.html browser shows error for this code.It says Reverse for 'blog_post_details' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$'] <!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <header> <h1>Django Blog</h1> <h4 style="float: right;"><a href="{% url 'blog_new_post' %}">+ New Post</a></h4> <hr> </header> <a href="{% url 'blog_name' %}">Home</a> … -
Read url content and perform operation in python
I'm trying to get data from URL containing space-separated value line by line and perform some operations on each line. The URL contains: 586763334343 1523718907817 NullPointerException 586763434443 1523718907818 IllegalAgrumentsException .... Here, 1st string is the request-id, 2nd string is a timestamp (in UTC) and the 3rd string is the Exception Name. I'm trying to read each line from URL and convert the timestamp to date-time and append to a list such that my list looks something like this. [ { second: 12, minute: 27, hour: 21, data: 'NullPointerException' }, { second: 12, minute: 27, hour: 21, data: 'NullPointerException' } ] How can I read the url and perform convert timestamp into date-time and append it to a list ? -
I want to make a chatbot using pycharm Django and dialogflow. Can anyone help me with that?
I want to make a dynamic chatbot that will take the query from the user and will go to the website directly to fetch the information about that query.. the url of the website will be already given from which it will search. -
Django - Reload model definition runtime - metaclass
I'm writing a model class based on EAV paradigm. The implementation is based on python metaclass that is responsible to "create" the model interface so all django features (admin, forms, class base views,...) can work without any further changes. The model definition (fields list and related type) is done using the admin interface. What I'm not able to do is to reload the model on save event after any changes is made in the admin interface. It's clear that the solution is very useful only if I can do the model changes without the need of restart the engine. Is there a way to force the model reload for a django model without restarting the engine? -
Jquery iteration not showing all column
this is my code : $('#addrowbtn1').on('click', function () { var cnt = $('#testTable tr th').length; var html = ''; //html += '<tr class="tempcls" id="tr' + k + '">'; var i =0; html += '<tr id="tr'+k+'">\n' + '<td style="display: none"><input type="text" value=0></td>'+ '{% for x in headers %}\n' + ' <td id="t' + +k+ i++ + '" align="center">\n' + ' {% if x.ddlist_len == 0 and x.type == "str" %}\n' + ' <input type="text" name="f' + i + '' + k + '">\n' + ' {% elif x.ddlist_len == 0 and x.type == "num" %}\n' + ' <input type="number" name="f' + i + '' + k + '">\n' + ' {% else %}\n' + ' {% if x.name == "Common_Name" %}\n' + ' <select class="select_d">\n' + ' {% for y in x.ddlist %}\n' + ' <option value="{{y.id}}">{{ y.value }} </option>\n' + ' {% endfor %}\n' + ' </select>\n' + ' {% else %}\n' + ' <select>\n' + ' {% for y in x.ddlist %}\n' + ' <option value="{{y.id}}">{{ y.value }} </option>\n' + ' {% endfor %}\n' + ' </select>\n' + ' {% endif %}' ' {% endif %}\n' + ' </td>\n' + '{% endfor %}\n' + '</tr>' k++; //html += '</tr>'; … -
Hosting a django app on a subpath using Nginx
The django app is being run using Gunicorn at 10.0.11.12:8199 My Nginx config is as follows, I'm forced to use location since the app is being hosted on some sort of a shared hosting service (https://www.feralhosting.com/). They give us access to servername.feralhosting.com/myusername where we can install software and access them using servername.feralhosting.com/myusername/softwarename location /softwarename { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_x_host; proxy_set_header X-NginX-Proxy true; rewrite /(.*) /myusername/$1 break; proxy_pass http://10.0.11.12:8199/; proxy_redirect off; } When I visit servername.feralhosting.com/myusername/softwarename or a route like servername.feralhosting.com/myusername/softwarename/admin I get the 404 Django page saying the URL wasn't found. Django itself seems to work fine only the URL mapping seems to be causing issues. An example of a path in my main urls.py file is path('softwarename/admin/', admin.site.urls) all paths are similarly configured. Thanks for any help in advance. -
how to ensure that only one data record is valid at a time - Django Rest Framework
I want to import records via csv file but I have to ensure that only one "product" is valid at a time. model: class Product(models.Model): Product_id = models.AutoField('ID', primary_key=True) Product_number = models.CharField('Artikelnummer', max_length=200, null=False, blank=False) Product_name = models.CharField('Artikelbezeichnung', max_length=200, null=True, blank=True) Product_vf = models.DateTimeField('valid_from', default=now) Product_vu = models.DateTimeField('valid_until', null=True, blank=True) Product_ia = models.DateTimeField('Hinzugefügt am', auto_now=True) Product_deleted = models.BooleanField('Gelöscht', default=False) When creating a new instance of product I want to check, that only one product (referenced by Product_number) is valid in a validity period- for Instance: Product1 - valid from 01/01/2020 until 31/12/2020 ==> valid Product1 - valid from 01/01/2021 until 31/12/2021 ==> valid Product1 - valid from 01/05/2020 until 31/12/2022 ==> not valid Is there a appropriate approach for this? where should I put this check, in the Product-Serializer class? serializer.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' -
Invalid data. Expected a dictionary, but got list
i trying to write code in django ...i am these error in the response... error : <{"non_field_errors":["Invalid data. Expected a dictionary, but got list."]}> can one help on these please...i am fresher with django rest ... models.py class Intermediate(models.Model): checked = models.BooleanField(default=False) CourseValue = models.CharField(max_length=255, default=True) CourseId = models.IntegerField(default=True) CourseLabel = models.CharField(max_length=255, default=True) serializers.py class IntermediateSerializers(serializers.ModelSerializer): class Meta: model = models.Intermediate fields = ('id', 'checked', 'CourseValue', 'CourseId', 'CourseLabel', ) views.py class IntermediateViewSet(viewsets.ModelViewSet): serializer_class = serializers.IntermediateSerializers queryset = models.Intermediate.objects.all() def update(self, request, *args, **kwargs): is_many = isinstance(request.data, list) print(f"In Dataset serializer") if is_many: serializer = self.get_serializer(data=request.data[0], many=True) if serializer.is_valid(): # serializer.save() self.perform_update(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: serializer = self.get_serializer(data=request.data[0]) print(f"serializer is {serializer}") if serializer.is_valid(): # serializer.save() self.perform_update(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to use postgresql database from a remote machine in django app?
I and my team member are working on a single project and we are using django and postgresql. The database is on his machine and when i try to run migrate it wont work giving an error. What can be done how can i access it? -
Analyzing log files according to timestamp in django
I'm trying to make an API for analyzing log files. The API will take a list of log files ("logFiles" -> array of strings) and count of parallel file processing ("parallelFileProcessingCount" -> integer) as input and outputs the number of exceptions grouped by time range and exception type. At any moment "parallelFileProcessingCount" files should be processed simultaneously if more than "parallelFileProcessingCount" files are remaining. If processing for any file is finished then the next file should be picked immediately for processing, so that "parallelFileProcessingCount" files are being processed at every moment, if more than "parallelFileProcessingCount" files are remaining. The format of the log file is as follows:- 586763334343 1523718907817 NullPointerException 586763434443 1523718907818 IllegalAgrumentsException where 1st string is the request-id, 2nd string is a timestamp (in UTC) and the 3rd string is the Exception Name. It can be assumed that all the files are for a single day and entries in files are sorted by time (in UTC). The 15 min range will start from the start of the day (00:00), until the end of the day(24:00), so there will be 96-time ranges. Example: Input: { "logFiles": ["https://example.file/log1.txt"], "parallelFileProcessingCount": 1 } Output: 21:15-21:30 IllegalAgrumentsException 1,21:15-21:30 NullPointerException 2, 22:00-22:15 UserNotFoundException 1,22:15-22:30 ....... -
Google Cloud App Engine - Django App using PostGreSQL looses SQL connection
I have been using PostGreSQL via Google Cloud App Engine for my Django Application. Lately, I have started seeing following issue : ... File "/env/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/env/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/env/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/env/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/env/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/env/lib/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections My database settings are as follow : if os.getenv('GAE_APPLICATION', None): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': '/cloudsql/MYAPP:europe-west2:MYAPP', 'NAME': 'MYNAME', 'USER': 'MYUSER', 'PASSWORD': access_secret_version("MYSECRET_SQL_PASSWORD"), 'PORT': '5432', } } -
Django form not valid - not null constraint
I have been looking at this issue for quite a while now. My form just keeps being invalid. model.py class GroupMember(models.Model): Groupname = models.ForeignKey(DareGroups, on_delete=models.CASCADE) Username = models.ForeignKey(DareUser, on_delete=models.CASCADE) IsAdmin = models.BooleanField(default=False) @receiver(post_save, sender=DareGroups) def create_GroupAdmin(sender, instance, created, **kwargs): if created: GroupMember.objects.create(Groupname=instance,Username=get_current_authenticated_user().dareuser,IsAdmin=True) #print(instance) def __str__(self): return self.Groupname.Groupname + "_"+self.Username.Username.username view.py def index(request): if request.user.is_authenticated==True: print('we zijn hier 1') if request.method == "POST": print('we zijn hier 2') if 'newgroup' in request.POST: formgroup = GroupsForm(request.POST) if formgroup.is_valid(): print('komen we dan hier?') formgroup.save() return redirect('index') elif 'newchallenge' in request.POST: formchallenge = NewChallengeForm(request.POST) if formchallenge.is_valid(): formchallenge.save() return redirect('index') elif 'addmember' in request.POST: formaddmember=AddMemberToGroupForm(request.POST) print('we zijn hier 3') print(formaddmember.data) if formaddmember.is_valid(): print('we zijn hier 4') formaddmember.save() else: print('we zijn hier 5') formaddmember.save() print(formaddmember.errors) return redirect('index') else: formgroup = GroupsForm() formchallenge=NewChallengeForm() formaddmember=AddMemberToGroupForm() return render(request,"DareU/index.html",{'formgroup':formgroup,'formchallenge':formchallenge,'formaddmember':formaddmember}) else: return render(request,"DareU/index.html") forms.py class AddMemberToGroupForm(forms.ModelForm): class Meta: model = GroupMember fields = ('Groupname', 'Username','IsAdmin') def __init__(self, user=None, **kwargs): super(AddMemberToGroupForm, self).__init__(**kwargs) self.fields['Groupname'].queryset = DareGroups.objects.filter(groupmember__IsAdmin=True) HTML <div class='container has-text-left' id="myForm3"> <h2 class="title is-2">Add member to group</h2> <form method="POST" class="post-form"> {% csrf_token %} {{ formaddmember.as_p }} <button type="submit" class="button is-small is-success" name="addmember">Save</button> <button type="button" class="button is-small is-danger cancel" onclick="closeForm3()">Close</button> </form> </div> So, I can't get passed the is_valid check. If I do try to …