Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: delete object with a button
In my website in the user page I've got a list of all the items he added to the database. Next to the items there's a delete button. I'd like the user to be able to delete that item through the button.Thanks a lot! models.py class Info(models.Model): utente = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) band = models.CharField(max_length=200) disco = models.CharField(max_length=200) etichetta_p = models.CharField(max_length=200) etichetta_d = models.CharField(max_length=200) matrice = models.CharField(max_length=200) anno = models.PositiveIntegerField(default=0) cover = models.ImageField(upload_to='images/', blank=True) view.py (I'm not sure about this part) def DeleteInfo(request, id=None): instance = get_object_or_404(Info, id=id) instance.delete() return redirect ('search:user') urls.py path('<int:id>/delete', views.DeleteInfo, name='delete'), html template: {% if object_list %} {% for o in object_list %} <div class="container_band"> <div class=album_band> <!-- insert an image --> {%if o.cover%} <img src= "{{o.cover.url}}" width="100%"> {%endif%} </div> <div class="info_band"> <!-- insert table info --> <table> <tr><th><h3>{{o.band}}</h3></th></tr> <tr><td> Anno: </td><td> {{o.anno}} </td></tr> <tr><td> Disco: </td><td> {{o.disco}} </td></tr> <tr><td> Etichetta: </td><td> {{o.etichetta_d}} </td></tr> <tr><td> Matrice: </td><td> {{o.matrice}} </td></tr> </table> </div> <div class="mod"> <table> <tr><td><button> Update </button></td></tr> <tr><td><button> Delete </button></td></tr> </table> </div> </div> {% endfor %} {%endif%} </div> -
Question objects need to have a primary key value before you can access their tags
i am trying to save both FK data as well as tags into same model. FK is the user. user has to submit the question and tags like stack overflow. but i am not able to save both of them. it looks some issue at my views. Can you please help. ValueError at /qanda/askquestion/ Question objects need to have a primary key value before you can access their tags. Request Method: POST Request URL: http://127.0.0.1:8000/qanda/askquestion/ Django Version: 2.2.4 Exception Type: ValueError Exception Value: Question objects need to have a primary key value before you can access their tags. Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/taggit/managers.py in get, line 424 Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 Python Version: 3.7.4 Python Path: ['/Users/SRIRAMAPADMAPRABHA/Desktop/IampythonDEV/iampython', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/SRIRAMAPADMAPRABHA/Library/Python/3.7/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'] Models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question_number = models.AutoField(primary_key=True) question_category=models.ForeignKey(Question_Category,related_name='questioncategory',on_delete=models.CASCADE) question_title=models.CharField(max_length=250) question_slug = models.SlugField(unique=True, max_length=250) question_description=RichTextField() question_tags = TaggableManager() question_posted_at=models.DateTimeField(default=datetime.now,blank=True) question_status= models.IntegerField(choices=STATUS, default=1) question_updated_on= models.DateTimeField(auto_now= True) def __str__(self): return self.question_title views.py @login_required def createQuestion(request): if request.method == 'POST': form = QuestionAskForm(request.POST) if form.is_valid(): new_question=form.save(commit=False) question_title = request.POST['question_title'] new_question.slug = slugify(new_question.question_title) new_question=request.user new_question.save() form.save_m2m() messages.success(request,'You question is succesfully submitted to the forum') return redirect('feed') else: form = QuestionAskForm() return render(request,'qanda/askyourquestion.html',{'form':form}) I want to submit both foreign key and as well as … -
Django static files are not loading with NGINX
Im trying to publish my first Django App on production Server with NGINX. project --app1 --app2 --config settings.py wsgi.py urls.py --venv manage.py nginx configuration server { listen 80; server_name my_IP_adress; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/websites/testAPP; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } In my settings I have the folow code BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_DIR = environ.Path(__file__) STATIC_URL = '/static/' STATIC_ROOT = str(ROOT_DIR('statics')) STATICFILES_DIRS = [ str(BASE_DIR.path('static')), ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] an in urls.py I added ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) But, whe I run collectstatoc on production Server, I get this Error: settings.py", line 24, in <module> str(BASE_DIR.path('static')), AttributeError: 'str' object has no attribute 'path' How can I fix it? -
Reading Pandas dataframe into postgresSQL with Django
Based on this question Saving a Pandas DataFrame to a Django Model I'm trying to add data from excel to my Model. So my model looks like this: class Company(models.Model): KIND = ( (0, "Corporate"), (1, "Start Up"), ) name = models.CharField(verbose_name="full company", max_length=50) address = models.CharField(max_length=100) kind = models.IntegerField(default=0) My excel that is loaded into dataframe looks like this(df): name address kind id 1 Ubisoft Dowtown 0 2 Exxon Tuas Link 1 Now I followed the suggestion in that question and ended up creating the following code in my views.py: from django.shortcuts import render from django.shortcuts import redirect from sqlalchemy import create_engine # Create your views here. from django.http import HttpResponse from django.conf import settings import pandas as pd from importer.models import Company def importer(request): df=pd.read_excel("datafile.xlsx") df.columns=["id", "name", "address", "kind"] df.set_index("id", inplace=True) print(df.dtypes) user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] database_url = 'postgresql://{user}:{password}@localhost:5433/{database_name}'.format( user=user, password=password, database_name=database_name, ) engine = create_engine(database_url, echo=False) df.to_sql(Company, con=engine, if_exists='append') So it seems that it loads dataframe correctly but then I get error when it is trying to append data to the database in postgresSQL, because I get the following error when I access route corresponding to importer view: Traceback (most recent call … -
Nginx upstream server values when serving an API using docker-compose and kubernetes
I'm trying to use docker-compose and kubernetes as two different solutions to setup a Django API served by Gunicorn (as the web server) and Nginx (as the reverse proxy). Here are the key files: default.tmpl (nginx) - this is converted to default.conf when the environment variable is filled in: upstream api { server ${UPSTREAM_SERVER}; } server { listen 80; location / { proxy_pass http://api; } location /staticfiles { alias /app/static/; } } docker-compose.yaml: version: '3' services: api-gunicorn: build: ./api command: gunicorn --bind=0.0.0.0:8000 api.wsgi:application volumes: - ./api:/app api-proxy: build: ./api-proxy command: /bin/bash -c "envsubst < /etc/nginx/conf.d/default.tmpl > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'" environment: - UPSTREAM_SERVER=api-gunicorn:8000 ports: - 80:80 volumes: - ./api/static:/app/static depends_on: - api-gunicorn api-deployment.yaml (kubernetes): apiVersion: apps/v1 kind: Deployment metadata: name: release-name-myapp-api-proxy spec: replicas: 1 selector: matchLabels: app.kubernetes.io/name: myapp-api-proxy template: metadata: labels: app.kubernetes.io/name: myapp-api-proxy spec: containers: - name: myapp-api-gunicorn image: "helm-django_api-gunicorn:latest" imagePullPolicy: Never command: - "/bin/bash" args: - "-c" - "gunicorn --bind=0.0.0.0:8000 api.wsgi:application" - name: myapp-api-proxy image: "helm-django_api-proxy:latest" imagePullPolicy: Never command: - "/bin/bash" args: - "-c" - "envsubst < /etc/nginx/conf.d/default.tmpl > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'" env: - name: UPSTREAM_SERVER value: 127.0.0.1:8000 volumeMounts: - mountPath: /app/static name: api-static-assets-on-host-mount volumes: - name: api-static-assets-on-host-mount hostPath: path: /Users/jonathan.metz/repos/personal/code-demos/kubernetes-demo/helm-django/api/static My … -
from django.allauth.account.adapter import DefaultAccountAdapter ModuleNotFoundError: No module named 'django.allauth'
I have installed django-allauth with docker-compose exec web pipenv install django-allauth, but I recieve an erro from django.allauth.account.adapter import DefaultAccountAdapter ModuleNotFoundError: No module named 'django.allauth', when I use docker-compose exec web python manage.py makemigrations. Thaks for your help :) -
Django dynamic change of LANGUAGE_CODE to use 1 template and 3 translated model fields
I want to use one single template to be displayed in 3 different languages depending on the LANGUAGE_CODE, so I would like to alter the value of LANGUAGE_CODE value and selecting the language from a dropdown menu in my template. My model contains translated fields in 3 languages class Recipe(AuditBaseModel): recipe_id = models.AutoField(primary_key=True) recipe_code = models.CharField(max_length=30, null=False, blank=False) recipe_name = models.TextField(verbose_name=_('recipe_name'), blank=True, null=True) recipe_name_eng = models.TextField(blank=True, null=True) recipe_name_nor = models.TextField(blank=True, null=True) My template is able to show each field depending on the LANGUAGE_CODE {% get_current_language as LANGUAGE_CODE %} {% if LANGUAGE_CODE == 'en-gb' %}<h2>{{ recipe_form.recipe_name_eng.value }}</h2> {% elif LANGUAGE_CODE == 'nb' %}<h2>{{ recipe_form.recipe_name_nor.value }}</h2> {% elif LANGUAGE_CODE == 'es' %}<h2>{{ recipe_form.recipe_name.value }}</h2> {% endif %} Also, in my template, I have a dropdown menu for language selection <li><a href="">Language</a> <ul class="sub-menu"> <li><a href="">English</a></li> <li><a href="">Norsk</a></li> <li><a href="">Espanol</a></li> </ul> </li> How can I dynamically alter the value of LANGUAGE_CODE in my settings.py when the user selects a specific language from the template menu? Any better idea without using i18n? Many thanks in advance -
ERROR: MySQL_python-1.2.5-cp27-none-win_amd64.whl is not a supported wheel on this platform
So i am setting up an old project its python2 and django1 where i'm stuck with installtion of requirement.txt This is the main error i'm getting while installing Building wheel for MySQL-python (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/rehman/projects/comparedjs/bin/python2 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-KyvPG6/MySQL-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-KyvPG6/MySQL-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-jCT7NK cwd: /tmp/pip-install-KyvPG6/MySQL-python/ Complete output (38 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mariadb -I/usr/include/mariadb/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o In file included from _mysql.c:44: /usr/include/mariadb/my_config.h:3:2: warning: #warning This file should not be included by clients, include only <mysql.h> [-Wcpp] #warning This file should not be included by … -
is it ok to use formview instead of updateview, createview in Django?
so I'm new here in django and have already get the point of some generic views but it really gives me a hard time to understand the UpdateView, CreateView and DeleteView all information that I search still not giving me a point on how to use them. So I have a form registration which have username and password but they are in different table or model to save; you may take a look on the forms.py, And trying UpdateView its giving me only an error to my project. So as I found in some forums, i can't use UpdateView to a foreign key table for its looking only a primary key So instead of using them I use FormView replacing by the 3 generic view for now. Is it ok to use the FormView as an option aside the 3 generic view? Here is my source code. forms.py: from django import forms class UserCredentialForm(forms.Form): username = forms.CharField(label = 'Email', widget = forms.TextInput( attrs = { 'id': 'id_login_username', 'class': 'form-control', 'autocomplete': 'off', } ), required = False) password = forms.CharField(label = 'Password', widget = forms.PasswordInput( attrs = { 'id': 'id_login_password', 'class': 'form-control', } ), required = False) class UserInfoForm(forms.Form): year = … -
do i need to learn all functions of programming language? [duplicate]
I am new to programming, i know basics of programming. I also write some code in python, php and javascript. Every programming language has hundreds of builtin functions. For example, every programming language has different functions of string, array, int and file I/O etc. Plus framework functions like django, laravel and codeiginter etc. Do i need to learn all builtin functions? for example if i learn php do i need to learn all functions of php plus laravel/codeiginter or if i learn asp.net do i need to learn all functions of c# and asp.net? i don't think it is possible, because there are hundreds of functions in programming language, functions return types and functions parameters? -
Order Union by created_at
I have a graphene.Union of two models and i'm tying to order the response by created_at field, witch is a matching field for both models. Is there of doing that? Schema.py class PostUnion(graphene.Union): class Meta: types = (PostType, Post2Type) @classmethod def resolve_type(cls, instance, info): # This function tells Graphene what Graphene type the instance is if isinstance(instance, Post): return PostType if isinstance(instance, Post2): return Post2Type return PostUnion.resolve_type(instance, info, search) class Query(graphene.ObjectType): all_posts = graphene.List(PostUnion, search=graphene.String(), limit=graphene.Int()) def resolve_all_posts(self, info, search=None, limit=None): if search: filter = ( Q(id__icontains=search) | Q(title__icontains=search) ) return (list(Post.objects.filter(filter)) + list(Post2.objects.filter(filter)))[:limit] return (list(Post.objects.all()) + list(Post2.objects.all()))[:limit] { allPosts(Order: "created_at") { ... on PostType { id title createdAt } ... on Post2Type { id title createdAt } } } -
SMTPSenderRefused (530, b'5.7.0 Authentication Required)
I make a website with django and im having some troubles whit the reset password feature in deployment with heroku (works fine locally), when i try to use it, an error pops up: SMTPSenderRefused at /password-reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError a68sm8842573qkd.10 - gsmtp', 'webmaster@localhost') Request Method: POST Request URL: https://mytobiapp.herokuapp.com/password-reset/ Django Version: 3.0.4 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError a68sm8842573qkd.10 - gsmtp', 'webmaster@localhost') Exception Location: /app/.heroku/python/lib/python3.6/smtplib.py in sendmail, line 867 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] settings.py EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST="smtp.gmail.com" EMAIL_PORT=587 EMAIL_USE_TLS= True EMAIL_HOST_USER = os.environ.get("GMAIL") EMAIL_HOST_PASSWORD = os.environ.get("CONTRASEÑA_GMAIL") I already tried to allow acces to less secure apps and use the displayunlockcaptcha feature of google, but nothing seems to work. Any help will be apreciated -
setting django project for production / development enviroment
I am writing a Django project that it needs to be divided as production/development, but however my project looks like this, how can I organize in order to execute python manage.py runserver for dev or prod. . ├── apps │ ├── account │ │ ├── migrations │ │ │ └── __pycache__ │ │ └── __pycache__ │ ├── course │ │ ├── migrations │ │ └── __pycache__ │ ├── quizgame │ │ ├── migrations │ │ │ └── __pycache__ │ │ └── __pycache__ │ └── site │ └── __pycache__ └── app └── __pycache__ 16 directories -
how do i fix this warning?
i wanted to create a simple web aplication using django, and when i run through the terminal the command: django-admin startproject my site and i get the error ''django-admin'' is not recognized as an internal or external command, operable program or batch file. i have tried running cmd as administrator but at the end the same result the problem i guess is this warning: WARNING: The script sqlformat.exe is installed in 'C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. can anyone help me how to find a solution p.s i'm very new to programming -
GeoDjango maps on Django forms
I want to have a GeoDjango LeafLet map on my form. On another page I succesfully implemented this, but I do struggle on my forms (CreateView and UpdateView). I do get this errorin my browser console: Uncaught ReferenceError: L is not defined at loadmap (new:109) forms.py from leaflet.forms.fields import PointField from leaflet.forms.widgets import LeafletWidget from django.contrib.gis import forms class TourStepForm(forms.ModelForm): required_css_class = 'required' place = forms.PointField( widget=LeafletWidget(attrs=LEAFLET_WIDGET_ATTRS)) class Meta(): model = Toursteps exclude = ('tour',) views.py class CreateTourStepView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'tour_admin/tour_list.html' success_url = '/' form_class = TourStepForm model = Toursteps template_name = 'tour_admin/toursteps_form.html' def get_context_data(self, **kwargs): context = super(CreateTourStepView, self).get_context_data(**kwargs) return context def get(self, request, *args, **kwargs): self.tour_id = get_object_or_404(Tour, pk=kwargs['tour_id']) return super(CreateTourStepView, self).get(request, *args, **kwargs) def form_valid(self, form): if form.is_valid(): self.tour_id = self.kwargs.get('tour_id') form.instance.tour_id = self.tour_id form.instance.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('tour_detail', kwargs={'pk':self.tour_id}) steps.html {% extends 'tour_admin/admin_base.html' %} {% load crispy_forms_tags %} {% load leaflet_tags %} {% leaflet_css plugins="forms" %} {% leaflet_js plugins="forms" %} {% block content %} {% if user.is_authenticated %} <div class=""> <h1>Step:</h1> <form enctype="multipart/form-data" class="tour-form" method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> {% else %} <h1>Not authorised!</h1> {% endif %} {% endblock %} -
want to convert response from django api into java object in android
want to convert response from django api into java object in android. Im currently able to display it in logcat but cant convert it to string or object to process it. this is my code. ''' final RequestQueue requestQueue= Volley.newRequestQueue(getActivity()); JsonArrayRequest arrayRequest=new JsonArrayRequest(Request.Method.GET, URL, null, new Response.Listener() { @Override public void onResponse(JSONArray response) { Log.e("Rest Response",response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Rest response",error.toString()); } }); requestQueue.add(arrayRequest); ''' -
How to query reverse foreign key in django?
I am trying to filter queryset for a reverse foreign key. Here are my two models:- class BranchModel(basemodel.BaseModel): company = models.ForeignKey(CompanyModel, on_delete=models.PROTECT) name = models.CharField(max_length=30, default="Head Office") user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='branch_owner') class User(AbstractUser): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) objects = UserManager() I want to get all the users of a branch. I tried to use this queryset:- User.objects.filter(branchmodel__user=self.request.user) but it is giving me empty result. how can i modify this? -
Running Django on Windows Using an IIS Server
I'm trying to run Django on Windows Using an IIS Server, I'm following a nice tutorial: https://www.youtube.com/watch?v=CpFU16KrJcQ&fbclid=IwAR37FtYd2ZveEIxBy1FAiqOkp3jpwwjyMQwuGnnaUW_renNHogfrMEbXNUs I get stuck at the point where I wfastcgi-enable Here is the output of the error .. ERROR ( message:Configuration error Filename: redirection.config Line Number: 0 Description: Cannot read configuration file due to insufficient permissions . ) An error occurred running the command: ['C:\\Windows\\system32\\inetsrv\\appcmd.exe', 'set', 'config', '/section:system.webServer/fastCGI', '/+[fullPath=\'"C:\\Users\\\\pyt hon.exe"\', arguments=\'"C:\\lib\\site-packages\\wfastcgi.py"\', signalBeforeTerminateSeconds=\'30\']'] Ensure your user has sufficient privileges and try again. I don't know how to set privileges to accept the command .. can anybody help? -
Django signals for two types of users
I'm trying to build an app that will have two different user types. Currently I have one type of user called - Tenant Profiles. I'm trying to add in Landlord Profiles type also. Both profiles are derived from Django's in-built auth_users. I have taken last_name field from auth_users to True or False and I'm trying to build Landlord/Tenant profiles based on this condition. I have tried to modify the signals.py file, but have had no luck so far. With code attached below it allows you register, but only creates account for auth_users. If I use commented code in signals.py it will create Tenant Profile. signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Tenant_Profile, Landlord_Profile # This function aims to create a profile everytime a user registers @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): #if created: #Tenant_Profile.objects.create(tenant=instance) if created and User.last_name == False: Tenant_Profile.objects.create(tenant=instance) elif created and User.last_name == True: Landlord_Profile.objects.create(landlord=instance) # kwargs just accepts any additional keyword arguments on the end of the function @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): #instance.tenant_profile.save() if User.last_name == False: instance.tenant_profile.save() elif User.last_name == True: instance.landlord_profile.save() views.py def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if … -
Pagination in Wagtail with {%for %} cycle
I have some problem with understanding django pagination in Wagtail cms. I read this topic Pagination in Wagtail So it is not works well for me. In my templates for get products i use this code {% for product in page.get_children.specific %} <div class="col-12 col-sm-6 col-lg-4"> <div class="single-best-receipe-area mb-30"> {% image product.product_photo width-400 %} <div class="receipe-content"> <a href="{% pageurl product %}"> <h5>{{ product.title }}</h5> </a> </div> </div> </div> {% endfor %} and then: <ul class="pagination"> {% if product.has_previous %} <li><a href="?page={{ product.previous_page_number }}"><i class="fa fa-angle-left"></i></a></li> {% endif %} {% for page_num in product.paginator.page_range %} <li {% if page_num == product.number %}class="active" {% endif %}><a href="?page={{ page_num }}">{{ page_num }}</a></li> {% endfor %} {% if product.has_next %} <li><a href="?page={{ product.next_page_number }}"><i class="fa fa-angle-right"></i></a></li> {% endif %} </ul> in my models.py i use this: class ProductsPage(Page): body = models.CharField(max_length=255, blank=True, help_text = 'Описание страницы') product_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text='Фотография Категории' ) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ImageChooserPanel('product_image'), ] def get_context(self, request): context = super(ProductsPage, self).get_context(request) all_product = OneProduct.objects.live() paginator = Paginator(all_product, 1) # Show 3 product per page page = request.GET.get('page') try: product = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first … -
AH01630: client denied by server configuration wsgi.py
I just configured my apache server and I did it patiently but I'm getting this error Forbidden You don't have permission to access this resource. Apache/2.4.41 (Ubuntu) Server at 139.162.198.195 Port 80 [authz_core:error] AH01630: client denied by server configuration: /home/project/project/wsgi.py Thanks in advance. -
Django auto primary key field increments instead of taking released ids
I'am using models.AutoField(primary_key=True) for my model, so id field is automatically incremented. Number of rows in a table stays always under 1000, because outdated rows are always deleted, so AutoFiled could use released ids, but it doesn't - it always increments. Can i make it to take free integers from released ids? -
NoReverseMatch at /products/drama/ - Reverse for 'product' not found. 'product' is not a valid view function or pattern name
Creating Product tag works alone, but if I add any entry in product (which should be linked with product tag) it produced error. Here is Url from app: from django.contrib.auth import views as auth_views from django.urls import path, include from django.views.generic import TemplateView from django.views.generic.detail import DetailView from main import views from main import forms from main import models path( "products/<slug:tag>/", views.ProductListView.as_view(), name="products", ), Here is models.py: class ProductTag(models.Model): name = models.CharField(max_length=40) slug = models.SlugField(max_length=48) description = models.TextField(blank=True) active = models.BooleanField(default=True) objects = ProductTagManager() def __str__(self): return self.name def natural_key(self): return (self.slug,) class ActiveManager(models.Manager): def active(self): return self.filter(active=True) class Product(models.Model): name = models.CharField(max_length=40) description = models.TextField(blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) slug = models.SlugField(max_length=48) tags = models.ManyToManyField(ProductTag, blank=True) active = models.BooleanField(default=True) in_stock = models.BooleanField(default=True) date_updated = models.DateTimeField(auto_now=True) objects = ActiveManager() def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE ) image = models.ImageField(upload_to="product-images") thumbnail = models.ImageField( upload_to="product-thumbnails", null=True ) Here is views.py: class ProductListView(ListView): template_name = "main/product_list.html" paginate_by = 4 def get_queryset(self): tag = self.kwargs["tag"] self.tag = None if tag != "all": self.tag = get_object_or_404( models.ProductTag, slug=tag ) if self.tag: products = models.Product.objects.active().filter( tags=self.tag ) else: products = models.Product.objects.active() return products.order_by("name") I think problem is somewhere in 'joining' between … -
Pwa and allauth with django/python
I enabled PWA installation withn django-pwa plugin correctly. I'm also using allauth for loggin/registration and authentication which works from the accounts/ url (for eg: accounts/login). With these allauth urls, the PWA installation is not working, manifest file is not found. Do you know what shall I configure to enable the installation for those URLs as well? Here are my PWA settings: PWA_APP_NAME = 'asdfadsfasdf' PWA_APP_DESCRIPTION = "asdfadsfasf" PWA_APP_THEME_COLOR = '#0A0302' PWA_APP_BACKGROUND_COLOR = '#3F214B' PWA_APP_DISPLAY = 'standalone' PWA_APP_SCOPE = '/' PWA_APP_ORIENTATION = 'any' PWA_APP_START_URL = '/' PWA_APP_ICONS = [ { 'src': '/static/images/logo192.png', 'sizes': '192x192' } ] PWA_APP_ICONS_APPLE = [ { 'src': '/static/images/logo512.png', 'sizes': '512x512' } ] PWA_APP_SPLASH_SCREEN = [ { 'src': '/static/images/logo512.png', 'sizes': '512x512' } ] #PWA_APP_DIR = 'ltr' PWA_APP_LANG = 'en-US' PWA_APP_DEBUG_MODE = True here is my urls.py settings urlpatterns = [ path('', include('withdraw.urls')), path('', include('users.urls')), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('pwa.urls')), ] -
How do I get an appropriate loader to handle this file type in Django?
I have just started a django and react project. Whenever I try and load some css be it plain css or from bootstrap I get the following error: I followed the following tutorial: https://www.valentinog.com/blog/drf/ I move my .bablrc and my webpack.config.js into my project root folder. Previously it was inside the frontend app folder. Please let me know what I am missing! ERROR in ./src/components/App.js 39:6 Module parse failed: Unexpected token (39:6) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | render() { | return ( > <Table striped bordered hover> | <thead> | <tr> @ ./src/index.js 1:0-35 Below are my files: My webpack.config.js: module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; My package.json: { "name": "frontend", "version": "1.0.0", "main": "index.js", "scripts": { "dev": "webpack --mode development ./src/index.js --output ./static/frontend/main.js", "build": "webpack --mode production ./src/index.js --output ./static/frontend/main.js" }, "keywords": [], "author": "", "license": "ISC", "description": "", "devDependencies": { "@babel/core": "^7.9.0", "@babel/plugin-proposal-class-properties": "^7.8.3", "@babel/preset-env": "^7.9.0", "@babel/preset-react": "^7.9.4", "babel-loader": "^8.1.0", "css-loader": "^3.4.2", "react": "^16.13.1", "react-dom": "^16.13.1", "ts-loader": "^6.2.2", "webpack": "^4.42.1", "webpack-cli": "^3.3.11" }, "dependencies": { …