Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to define mongodb ArrayField in Djongo's model
class question(models.Model): question_id = models.IntegerField() choice = models.CharField(max_length=100) tags = models.ArrayField(models.CharField(max_length=100)) ERROR: packages\djongo\models\fields.py", line 116, in _validate_container for field in self.model_container._meta._get_fields(reverse=False): AttributeError: 'CharField' object has no attribute '_meta' I want to add a ArrayField in my models using djongo models. i hope 'tags' looks like ['tag1', 'tag2', 'tag3' ...]. But djongo requeirs model_container, but i only want an array contains strings, not a model ,please help~~ -
Django - Pagination display
I am having an issue figuring out my pagination for django. Following the docs everything works correctly if I am on the first page or the last page, but I have code duplicating. Everything I have tried I end up getting some sort of exception, mostly empty page exception. I understand that this is because my solutions involve not checking if page_obj.has_previous or .has_next. I am not sure how to solve this and any help would be greatly appreciated. I will attach a screen shot so you can see what I mean. pagination: <div class="pagination justify-content-center pt-3"> <nav aria-label='pagination'> <ul class="pagination step-links"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label='Previous'> <span aria-hidden='true'>&laquo;</span> </a> </li> <li class="page-item"> <a class='page-link'> {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} </a> </li> {% endif %} {% if page_obj.has_next %} <li class="page-item"> <a class='page-link'> {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} </a> </li> <li class="page-item"> <a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label='Next'> <span aria-hidden='true'> &raquo; </span> </a> </li> {% endif %} </ul> </nav> </div> As you can see the '2 of 3' gets duplicated. I see exactly why it gets duplicated in my code but if I delete one of the list items … -
Django / Nginx / uWSGI - CSRF verification failed
I am trying to authenticate myself on my server by making a POST request using python requests module. Unfortunately I have the following error : Forbidden (403) CSRF verification failed. Request aborted. I have been trying other people Nginx's configuration (see here, here, or here) but the request still fails. I am not familiar with this task. Can someone help me figure out my mistake please? Code with the requests on the client side import requests username_django = 'username' password_django = 'password' server_django_ca = '/path/to/ca.pem' login_url = 'https://login_url' api_url = 'https://api_url' def get_django_authentication_token( login_url, username, password, server_django_ca ): #hilens.info('NOW AUTHENTICATING USER') request_session = requests.Session() request_session.headers.update({'referer': 'HiLens'}) response = request_session.get( login_url, verify=server_django_ca ) token = response.cookies['csrftoken'] print(f'Token 1 = {token}') headers = {'X-CSRFToken': token} # THIS REQUESTS FAILS - returns a csrf verification failed login_response = request_session.post( login_url, data={ 'username':username, 'password':password, 'next':'/ihm_maquette/set_hi_lens_detection'}, verify=server_django_ca, headers = headers ) print(login_response.text) token = request_session.cookies['csrftoken'] print(f'Token 2 = {token}') if login_response.status_code == 200: #hilens.info('AUTHENTICATION WORKED') return request_session, token else: print('Login response error') def send_post_request_to_django( username_django, password_django, login_url, api_url, server_django_ca, bboxes ): datas = {} for bbox in bboxes: label = int(bbox[4]) if label == 0: datas['label'] = 'No Mask' elif label == 1: datas['label'] = … -
Heroku not updating database
Recently I deployed my Django blog app in Heroku, its running fine. When I create a new account or blog post, it will updated easily, but after a hour, its not there. every time, db. resets to the old value. how can I pass over it? -
Viewing s3 files in browser
I have created a bucket in s3 and successfully uploaded files to it with django storages. However, when I try to access the files in the browser, I get the following error: IllegalLocationConstraintException The eu-south-1 location constraint is incompatible for the region specific endpoint this request was sent to. I have also realised I do not have region name included in my URL(https://docs.s3.amazonaws.com/media/admin/2.pdf...). Could that be the problem? If so, how do I set it to append the region name? What could be missing here? -
I have models four models called Profile, Experience, Work Education, Social Work. How can I make something like this on admin panel?
I tried using Jazzmin theme for my admin but couldn't build something like this. I want Profile, Experience and other models in horizontal line in admin panel. -
Django UUIDField default value
I have a django model to which I would like to add a UUIDField : uuid = models.UUIDField( default = uuid.uuid4, unique = True, editable = False ) I'd like this uuid to be unique, however at migration of an existing database, I have the following error : django.db.utils.IntegrityError: (1062, "Duplicate entry '3ba46cb5f7f340ffa43e348cb789901a' for key 'carbon.uuid'") How can I provide to default an other uuid if this one is already used ? -
i want to see all the users in django admin panel and i can select more than one user
hello i had done some modification in models and get the User.username and inserted them in a user_list and in multiselectfield(choices=user_list) is was working fine but in the case as i made/create a new user and i go to the application to select multiple users, my newly made user is not showing there until i restart the django server my model is like that: class Video(models.Model): listo = [] user = User.objects.all() for i in user: a = (str(i), str(i)) listo.append(a) print("this is listo", listo) caption = models.CharField(max_length=100) video = models.FileField(upload_to="video/%y",null=True,blank=True) show_to = MultiSelectField(choices=User.username) # show_to = models.ForeignKey(User, on_delete=models.CASCADE) url_video= models.URLField(blank=True) def __str__(self): return self.caption the thing i want is to instantly show the newly made user in the django application so i could not restart the server again and again. thanks in advance! -
Is it secure to use firebase tokens for authentication between my server and an application?
I'm thinking about using firebase to authenticate users. Users could sign up via a pyqt app. Their email address and password would be sent via a POST request to my server (Django). On my server, I would use firebase (pyrebase) to sign them up. I would then store the firebase token in the database on my server, and also return the token to the user and save it there locally. Afterwards, I would always (or until the user logs in again which would return a new token) use this token to authenticate the user and let them access my database. Would this be secure? Something like this: On sign-up: User: token = requests.post(url, {"email": email, "pwd": pwd) Server: response = auth.create_user_with_email_and_password(email, pwd) token = response['idToken'] c.execute('INSERT INTO Tabel (email, token) VALUES(?, ?)', (email, token)) return token After sign-up: User: some_data = requests.post(url, {"token": token, "email": email) Server: token_in_database = c.execute("SELECT token FROM Tabel WHERE email = (?)", (email,)).fetchone() if token == token_in_database: return some_data -
TypeError: Test loader returned an un-runnable object
Not sure what these test errors are in Django when I try running: python shepard.py test --settings=core.settings.test Tests in each django app failing with: Error in shepherd.core.tests.test_exampleapp TypeError: Test loader returned an un-runnable object. Is "shepard.core.tests.test_authorization" importable from your current location? Maybe you forgot an __init__.py in your directory? Unrunnable object looks like: None of type <class 'NoneType'> with dir ['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] -
Problem with aldryn_form after update Django and Django CMS
I'm trying to update my requirements.txt I got Django=1.11.29, DjangoCMS=3.7.4, aldryn-forms=5.0.4 and try to update to => Django=3.2, DjangoCSM=3.9.0, aldryn-forms=6.2.1. But when I upgrade packages, ./manage.py migrate and do ./manage.py cms list plugins the FormPlugin is no more installed. Here my origin requirements.txt : aldryn-apphooks-config==0.6.0 aldryn-boilerplates==0.8.0 aldryn-categories==1.2.0 aldryn-common==1.0.5 aldryn-forms==5.0.4 aldryn-translation-tools==0.3.0 asgiref==3.3.4 backports.csv==1.0.7 beautifulsoup4==4.9.1 bleach==3.1.5 cachetools==4.1.1 certifi==2020.6.20 chardet==3.0.4 cmsplugin-svg==0.1.2 cssselect==1.1.0 cssutils==1.0.2 defusedxml==0.6.0 dj-database-url==0.5.0 Django==1.11.29 django-absolute==0.3 django-admin-sortable2==0.7.7 django-appconf==1.0.4 django-appdata==0.3.0 django-bootstrap3==14.1.0 django-ckeditor==5.9.0 django-classy-tags==1.0.0 django-cms==3.7.4 django-cms-tools==0.7.1 django-emailit==0.2.4 django-filer==1.7.1 django-formtools==2.2 django-js-asset==1.2.2 django-macros==0.4.0 django-mptt==0.11.0 django-multiupload==0.5.2 django-parler==2.1 django-polymorphic==2.1.2 django-ranged-response==0.2.0 django-sekizai==1.1.0 django-simple-captcha==0.5.14 django-sizefield==1.0.0 django-sortedm2m==3.0.2 django-standard-form==1.1.1 django-tablib==3.2 django-tools==0.46.1 django-treebeard==4.3.1 djangocms-admin-style==1.5.0 djangocms-attributes-field==1.2.0 djangocms-column==1.11.0 djangocms-file==2.4.0 djangocms-googlemap==1.4.0 djangocms-installer==1.2.3 djangocms-link==2.6.1 djangocms-local-navigation==1.4.1 djangocms-picture==2.4.0 djangocms-slider==0.2.5 djangocms-snippet==2.3.0 djangocms-style==2.3.0 djangocms-text-ckeditor==3.10.0 djangocms-video==2.3.0 easy-thumbnails==2.7 et-xmlfile==1.0.1 html5lib==1.1 icdiff==1.9.1 idna==2.8 importlib-metadata==1.7.0 jdcal==1.4.1 jsmin==2.2.2 lxml==4.5.2 odfpy==1.4.1 openpyxl==3.0.5 packaging==20.4 Pillow==7.2.0 pprintpp==0.4.0 premailer==3.7.0 pyparsing==2.4.7 python-slugify==4.0.1 pytz==2020.1 PyYAML==5.3.1 requests==2.24.0 six==1.15.0 sorl-thumbnail==12.6.3 soupsieve==2.0.1 sqlparse==0.3.1 tablib==2.0.0 text-unidecode==1.3 typing-extensions==3.10.0.0 tzlocal==2.1 Unidecode==1.1.1 urllib3==1.25.10 webencodings==0.5.1 xlrd==1.2.0 xlwt==1.3.0 YURL==1.0.0 zipp==3.4.1 Here my requirements.txt after upgrade : aldryn-apphooks-config==0.6.0 aldryn-boilerplates==0.8.0 aldryn-categories==1.2.0 aldryn-common==1.0.5 aldryn-forms==6.2.1 aldryn-translation-tools==0.3.0 asgiref==3.4.1 backports.csv==1.0.7 beautifulsoup4==4.9.3 bleach==4.0.0 cachetools==4.2.2 certifi==2021.5.30 chardet==4.0.0 cmsplugin-svg==0.1.2 cssselect==1.1.0 cssutils==2.3.0 defusedxml==0.7.1 dj-database-url==0.5.0 Django==3.2.6 django-absolute==0.3 django-admin-sortable2==1.0 django-appconf==1.0.4 django-appdata==0.3.2 django-bootstrap3==15.0.0 django-ckeditor==6.1.0 django-classy-tags==2.0.0 django-cms==3.9.0 django-cms-tools==0.7.1 django-emailit==0.2.4 django-filer==2.0.2 django-formtools==2.3 django-js-asset==1.2.2 django-macros==0.4.0 django-mptt==0.12.0 django-multiupload==0.5.2 django-parler==2.2 django-polymorphic==3.0.0 django-ranged-response==0.2.0 django-sekizai==2.0.0 django-simple-captcha==0.5.14 django-sizefield==1.0.0 django-sortedm2m==3.0.2 django-standard-form==1.1.1 django-tablib==3.2 django-tools==0.48.3 django-treebeard==4.5.1 djangocms-admin-style==2.0.2 djangocms-attributes-field==2.0.0 djangocms-column==1.11.0 djangocms-file==3.0.0 djangocms-googlemap==2.0.0 djangocms-installer==2.0.0 djangocms-link==3.0.0 djangocms-local-navigation==1.4.1 djangocms-picture==3.0.0 … -
How to sync two database data in django tests?
I am using two databases, default and readonly, as the name suggests that default is used to write and readonly used to read. Till this, it works fine. and Then in my models, I changed database managers for reading from particular database data, as I cannot use Django routers due to the complexity. in models, there is a Manger for readonly database, like this: objects = models.Manger() readonly = objects.db_manager("readonly") And In views, I am using Model.readonly.all(). So far so good. Problem comes in while testing views. def test_event_view(): e = Event.objects.create(self.event_data) url = reverse('event-detail', kwargs={'slug': e.slug}) response = self.client.get(f"{url}?state=Florida") self.assertOK(response) # Should be 2 == status_code/100 Because view is reading from readonly and this test is creating an object in default, so it says event does not exist on readonly database. SO my question is how to handle this situation? -
CreateView switch model
i have a problem with my CreateView. I wish I could have two different models that change based on the url it finds. I also have problems with success_url, I don't know how to pass it a parameter. url.py path('crea-<tipo>', CreaView.as_view(), name="crea") views.py class CreaView(StaffMixin, CreateView, tipo): if tipo == "gruppo": model = Gruppi elif tipo == "esercizio": model = Esercizio fields = '__all__' template_name = 'staff/crea.html' success_url = '/backoffice/lista/<tipo>' -
Unable to customize the primary key pattern in Django
I have 3 models, Student, Course and Fee. I want to create a report which will bring all the data contained by these 3 models, together, with an ID of its own. The models: class Student(models.Model): roll_number=models.IntegerField(primary_key=True) name=models.CharField(max_length=50) email=models.EmailField(max_length=60) city=models.CharField(max_length=20) class CourseChoices(models.Model): courses=models.CharField(max_length=30, blank=True) def __str__(self): return self.courses class Course(models.Model): roll_number=models.ForeignKey(Student, on_delete=CASCADE) course=models.ForeignKey(CourseChoices, on_delete=CASCADE) class Fee(models.Model): roll_number=models.ForeignKey(Student, on_delete=CASCADE) amount_to_be_paid=models.DecimalField(max_digits=7, decimal_places=2, default=0) discount=models.DecimalField(max_digits=5, decimal_places=2, default=0) Final_amount_to_be_paid=models.DecimalField(max_digits=5, decimal_places=2, default=0) Amount_received=models.DecimalField(max_digits=5, decimal_places=2, default=0) Balance=models.DecimalField(max_digits=5, decimal_places=2, default=0) batch=models.IntegerField() Now, a student may pay his/her fee in installments, so that will create multiple instances in the track report. I want the user to track each transaction with the primary key/id. Below is an example: I have additional model which brings everything together: class Report(models.Model): id = models.IntegerField(primary_key=True) student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) fee = models.ForeignKey(Fee, on_delete=models.CASCADE) def _get_next_id(self): last = Report.objects.all().aggregate(models.Max('id'))['id__max'] print(last) # last = Report.objects.aggregate(max_id=models.Max('id'))['max_id'] if last: last += 1 self.id = "{}{:04d}".format('HB', last) elif not last: last = 1 self.id = "{}{:04d}".format('HB', last) def save(self, *args, **kwargs): if not self.id: self.id = self._get_next_id() super().save(*args, **kwargs) The view for Fee: def fee_view(request): if request.method=='POST': fm_fee=FeeForm(request.POST) if fm_fee.is_valid(): fee=fm_fee.save() Report.objects.create(student=fee.roll_number, fee=fee, course=Course.objects.get(roll_number=fee.roll_number)) fm_fee=FeeForm() return render(request, 'account/fee.html', {'form1':fm_fee}) else: fm_fee=FeeForm() return render(request, 'account/fee.html', … -
Django JWT auth: Why the view returns always AnonymUser?
I am using JWT auth to login users. Username and password are sent in Body, however, in the customized response, an anonymUser is always returned. I think the problem is that in settings.py stands 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', and when I generate a token before and then send it in Headers the user is identified. Bit the thing is, that I cannot use 2 views in order to generate token and decode it, everything has to be in one view and I don't know how to login the user in the view and then get token and decode it. @api_view(('POST',)) def check_token(request): token_refresh = RefreshToken.for_user(request.user) print(request.user) # AnonymUser print(request.user.id) # None print(str(token_refresh.access_token)) data = {'token': str(token_refresh.access_token), 'refresh_token': str(token_refresh)} aT = str.encode(str(token_refresh.access_token)) try: valid_data = TokenBackend(algorithm='HS256').decode(aT, verify=False) print(valid_data) data['uuid'] = valid_data['user_id'] data['validUntil'] = valid_data['exp'] data['clientId'] = 'default' return JsonResponse(data) except ValidationError as v: print("Validation error", v) -
TemplateDoesNotExist at /konfigure
TemplateDoesNotExist at /konfigure index.html Request Method: GET Request URL: http://127.0.0.1:8000/konfigure Django Version: 3.2 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: /home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages/django/template/loader.py, line 47, in select_template Python Executable: /home/ramil/Desktop/plandeki/env/bin/python Python Version: 3.9.5 Python Path: ['/home/ramil/Desktop/plandeki/trampulin_app', '/home/ramil/miniconda3/lib/python39.zip', '/home/ramil/miniconda3/lib/python3.9', '/home/ramil/miniconda3/lib/python3.9/lib-dynload', '/home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages'] Server time: Wed, 04 Aug 2021 11:10:58 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/ramil/Desktop/plandeki/trampulin_app/templates/index.html (Source does not exist) django.template.loaders.filesystem.Loader: /home/ramil/Desktop/plandeki/build/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages/django/contrib/admin/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages/django/contrib/auth/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages/rest_framework/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/trampulin_app/konfigurator/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/trampulin_app/upcservice/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages/cloudinary/templates/index.html (Source does not exist) -
how do I search with Comma-separated values in Django rest framework?
I have values in database like : Injection Mold Injection Mold,PVC Mold Stack Mold PVC Mold I am filtering it through get method. I pass queries like : http://0.0.0.0:8000/api/v1/plastic_mold/filter/?type[]=Stack%20Mold,Injection Mold,Gas Injection Mold,PVC Mold the results I get are from only Single value fields. How do I search and get values from Injection,PVC Mold these, comma seperated values. Here is my code : if 'type[]' in request.query_params: type = request.GET.get('type[]').split(',') #dict(request.query_params)['type[]'] print(type) for item in type: query1.add(Q(type__icontains=item), Q.OR) Please help me out! -
How to setup python app in cpanel on HostGator?
I have developed one website using Django I want to host the website in HostGator but in HostGator c panel there is no setup python in software's what to do how set path in HostGator -
Print all attributes from an object with Django templates
I am a novice programmer, I am learning python and Django on my own. I got stuck in a part of my application: I have many models with many attributes, and I have a window and a template for each of them. The idea is to show in each one, a table with all its content with an sql query in the file view.py objects.all () My code: MODELS.PY from django.db import models class MFuel(models.Model): marca = models.TextField(db_column='Marca', blank=True, null=True) # Field name made lowercase. modelo = models.TextField(db_column='Modelo', blank=True, null=True) # Field name made lowercase. potencia_electrica_kw = models.BigIntegerField(db_column='Potencia_electrica_kW', blank=True, null=True) # Field name made lowercase. fecha_oferta = models.DateTimeField(db_column='Fecha_oferta', blank=True, null=True) # Field name made lowercase. pais_proyecto = models.TextField(db_column='Pais_Proyecto', blank=True, null=True) # Field name made lowercase. proyecto = models.TextField(db_column='Proyecto', blank=True, null=True) # Field name made lowercase. uds = models.FloatField(db_column='Uds', blank=True, null=True) # Field name made lowercase. precio_eur = models.FloatField(db_column='Precio_EUR', blank=True, null=True) # Field name made lowercase. precio_usd = models.FloatField(db_column='Precio_USD', blank=True, null=True) # Field name made lowercase. precio_unitario_eur = models.FloatField(db_column='Precio_Unitario_EUR', blank=True, null=True) # Field name made lowercase. ratio_eur_kw = models.FloatField(db_column='Ratio_eur_KW', blank=True, null=True) # Field name made lowercase. largo_mm = models.FloatField(db_column='Largo_mm', blank=True, null=True) # Field name made lowercase. ancho_mm = models.FloatField(db_column='Ancho_mm', blank=True, null=True) … -
How to list only active users in dropdown menu
I want to list all active users in dropdown list. But all users are listed in the dropdown How can I do it? template <form method="post"> {% csrf_token %} {{ form|crispy }} <input type="hidden" name="customer_id" value="{{ customer.id }}"> <button type="submit" class="btn btn-primary btn-sm">Assign</button> </form> forms class AssignForm(forms.ModelForm): class Meta: model = Customer fields = ('user',) views form = AssignForm(request.POST or None) if request.POST: customer_id = request.POST.get('customer_id', None) customer = Customer.objects.get(id=customer_id) user = UserProfile.objects.get(id=request.POST.get('user', None)) customer.user = user customer.save() # form.save() return redirect('user:customer_list') models class UserProfile(AbstractUser, UserMixin): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) ... -
unable to Send compressed gzip data using Django Rest framework
I am sending JSON file in Django Rest APIView framework. I want to reduce the size of the file. Implemented below code but Receving below error: @api_view(['GET','POST']) def myMethod(request): from rest_framework.response import Response if request.method == 'POST': import gzip # ****Some code lines here to generated small json*** myJson = json.dumps(parsed, indent=4) compressedContent = gzip.compress(myJson.encode('utf-8'), 5) # compressedContent is byte format return Response(compressedContent, status=status.HTTP_200_OK) As mentioned in this link, I implemented middleware too. Django rest framework, set the api response Content-Encoding to gzip MIDDLEWARE = [ 'django.middleware.gzip.GZipMiddleware', ... ] Trying to call from Postman and it is showing below error. UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte. 500, Internal server error. Is there a way I can setup Accept-Encoding somewhere. I cannot figureout this. Please note postman has Accept-Encoding to gzip, deflate, br Could you please answer what is the problem? Thanks -
Problem this deploy django project to Heroku
I try deploy django app to heroku and get errors: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to tandt-online-webchat. remote: To https://git.heroku.com/tandt-online-webchat.git ! [remote rejected] master -> master (pre-receive hook declined) error: не удалось отправить некоторые ссылки в «https://git.heroku.com/tandt-online-webchat.git» I done all what need: git add . git commit -m "releze heroku vers 1" and when i do git push heroku master i get this error I have all needs files: Procfile and requirements.txt In Procfile i have: web: gunicorn web_chat.wsgi and to requirements.txt I input pip freeze, and i shure what i have gunicorn her. What I do wrong? -
Select2 working incorrectly with Formsets
I have script like this and this working with only first form, others are frozen and did not work at all. $(document).ready(function() { $('#id_membership-0-company').select2(); }); I'm not able to change # to . because of every new form have new id like id_membership-0-company, id_membership-1-company and so on, and all my forms have same class (this field don't have separate class) I'm not able to just add all id's inside this function because of it works only when the page is loaded so only id 0 will work this way I was try to do something like this: add onclick="addRow()" inside "Add form" button html tag and this code in script. Without Timeout function it doesn't work because script executes too fast. It works for two forms (if I press "Add form" button) but not working if I adding more id's (in this scenario after the second form many more incorrect forms created for this field) function addRow() { function activateForms(){ $('#id_membership-0-company').select2(); $('#id_membership-1-company').select2(); } setTimeout(activateForms, 1000); } How to fix that? I need select2 widget for first field of every form? -
Django + postgreSQL : why migrating did work even though I hadn't given my db info?
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', } } It's my settings.py. DATABASE 'test' has password, but I did not enter it. and for testing, I tried migrating: creating superuser did work, too. but in psql, postgres-# \dt Did not find any relations. I thought this message means DB not connected with Django, is it right? If so, how could migrating work w/o error messages like no connection? Is there no relationship between migration and DB? -
How to connect django-allauth user with custom user model
I made a socialmedia application which i use django signup and login form,,,also i use django allauth. I added a editprofile option for user editing,, with django login user can edit their profile but with google login user cannot able to edit his/her profile. Then it gives ( UserProfile matching query does not exist.) this error. please help me to solve this problem models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') full_name = models.CharField(max_length=200,blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) bio = models.TextField(blank=True) cover_pic = models.ImageField(upload_to='cover_pics',blank=True) dob = models.DateField(blank=True,null=True) facebook = models.URLField(blank=True) def __str__(self): return str(self.user) views.py @login_required def edit_profile(request): currunt_user = UserProfile.objects.get(user=request.user) form = EditProfile(instance=currunt_user) if request.method == "POST": form = EditProfile(request.POST, request.FILES, instance=currunt_user) if form.is_valid(): form.save(commit=True) form = EditProfile(instance=currunt_user) return HttpResponseRedirect(reverse('login_app:profile')) context = { 'title': 'Edit Profile - FriendsBook', 'form':form } return render(request,'login_app/edit_profile.html',context) Error message: DoesNotExist at /accounts/edit_profile/ UserProfile matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/edit_profile/ Django Version: 3.2.5 Exception Type: DoesNotExist Exception Value: UserProfile matching query does not exist. Exception Location: C:\Users\admin\Desktop\djangoclass\social media\socialenv\lib\site-packages\django\db\models\query.py, line 435, in get Python Executable: C:\Users\admin\Desktop\djangoclass\social media\socialenv\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\admin\\Desktop\\djangoclass\\social media\\socialmedia', 'c:\\program files\\python39\\python39.zip', 'c:\\program files\\python39\\DLLs', 'c:\\program …