Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, access an object through another object
I use many-to-many relationships and would like to access an object through another object. In my example I want to get to the product through a meal. I created two meals and a few products and I tried in the shell to get to the product through a meal, but the result is None. Models class Product(models.Model): name = models.CharField(max_length=30) kcal_on_100g = models.IntegerField(default=0) carbon_on_100g = models.IntegerField(default=0) protein_on_100g = models.IntegerField(default=0) fat_on_100g = models.IntegerField(default=0) def __str__(self): return self.name class Meal(models.Model): name = models.CharField(max_length=100) product = models.ManyToManyField(Product) def __str__(self): return self.name In Shell: In [1]: from account.models import Meal In [2]: meal = Meal.objects.all() In [3]: for i in meal: ...: print(i.product) ...: account.Product.None account.Product.None -
Convert subclass of existing Django model instances
I am dealing with an update issue on a django project i am working on. I have a populated db containing a table A. During update phase I subclassed A with another model B. Now I want to take some of A's instances and make them become B's instances. Is there any way to achieve that? -
Instance Error On Foreign Key Field Django
Im stumped and need help on my function. I have two tables student and student information. Student information is all guardian information of that student. I separated this data from the main student table so you can add as many guardians as you want to a students file with new records. The error I'm getting is as followed. Cannot assign "'1'": "StudentInformation.studentpsid" must be a "Student" instance. Attached you will see my code. Studentpsid in student information is a foreign key from student. def ImportStudentGuardian(request): AuthTokenP(request) print("Getting student guardian data from SIS for K-8") #Pulls K-8 Guardians url = "removed for posting" payload = {} token = APIInformation.objects.get(api_name="PowerSchool") key = token.key headers = {'Authorization': 'Bearer {}'.format(key)} response = requests.request("GET", url, headers=headers, data = payload) encode_xml = response.text.encode('utf8') xml_string = ET.fromstring(encode_xml) students = xml_string.findall("student") for student in students: #XML Values psid = student.find("id").text try: mother = student.find("contact").find("mother").text except Exception: mother = "" try: father = student.find("contact").find("father").text except Exception: father = "" if Student.objects.filter(studentpsid=psid).exists(): print("Accessing guardian information.") m = StudentInformation.objects.create(studentpsid=psid,guardian_name = mother, relation = "Mom") <---- Function Fails here print("Record doesn't exist for mom, creating record.") m.save() d= StudentInformation.objects.create(studentpsid=psid,guardian_name = father, relation = "Dad") print("Record doesn't exist for dad, creating record.") d.save() … -
How to "run" SQL Queries in Angular w/ Django REST Api
I'm currently building a web app using Angular 9 with a Django backend, and I'm trying to think of the best way to essentially run a SQL query. The app is mainly for data management and entry, but there needs to be an export feature on the underlying tables. What I'd like to do is: Run "SQL" query to get the underlying data which is then displayed in Angular Filter the data by various fields (I'm using mat components for this) Export the data to Excel I know how to do steps 2 and 3, and the displaying data part in step 1, but I cannot figure out how to actually query the data. In Django, the models (truncated to focus on id fields I need to join on) are: class client(models.Model): parent_client_id = models.ForeignKey(client_parent, on_delete=models.CASCADE) client_id = models.AutoField('Client ID', primary_key=True) def __str__(self): return self.client_name class manufacture(models.Model): parent_manufacture_id = models.ForeignKey(manufacture_parent, on_delete=models.CASCADE) manufacture_id = models.AutoField('Manufacture ID', primary_key=True) def __str__(self): return self.market_name class table(models.Model): table_id = models.AutoField('Table ID', primary_key=True) client_id = models.ForeignKey(client, on_delete=models.CASCADE) def __str__(self): return str(self.table_id) class analysis(models.Model): analysis_id = models.AutoField('Analysis ID', primary_key=True) table_id = models.ForeignKey(table, on_delete=models.CASCADE) def __str__(self): return str(self.analysis_id) class subtable(models.Model): subtable_id = models.AutoField('Subtable ID', primary_key=True) table_id = models.ForeignKey(table, … -
# error:unused variable username and password
I want to create a user authentication in django there is an error in username and password def login(request): if request.method=="POST": #here got and error username=request.POST.get('Username') #here got an error password=request.POST.get('password') user = authenticate(username='username', password='password') if user is not None: return redirect("/") else: return render(request,'login.html') return render(request,'login.html') Thanks in advance! -
phpMyAdmin login is not working after changing port number
I have deployed django project on ubuntu server using nginx and gunicorn. Django tries to route /phpmyadmin within django project which blocks access to phpmyadmin. So, I changed to different port number and allowed it though vestacp firewall as well as added Listen 99 to /etc/apache2/ports.conf file. Now phpMyAdmin loads to new port but login with correct username and password doesn't work. Though returns token with correct credentials without error redirects to login page again. And returns error message with wrong credentials. Change phpMyAdmin port from 80 to another number -
How to validate POST request using OAuth1.0a or HMAC-SHA1 in Django
I'm using Django 3.0.7 and i need to validate the incoming POST request from my partner server by HMAC-SHA1 or OAuth1.0a and if it validated send response {"OK":"200"}. My views.py looks like this: def api_create_blog_view(request): blog_post = BlogPost(author=request.user) if request.method == 'POST': serializer = BlogPostSerializer(blog_post, data=request.data) data = {} if serializer.is_valid(): serializer.save() return Response({"response_code":"OK"}) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I tried to made somehow like in this and this topic, but it seems that i don't clearly understand how should it work. -
modified decorator doesn't work in django/python
I'm writing a decorator that works approximately to the api version a user uses. So thus, I want to have something like, but then that the response serializer depends on the api version the user uses: # noinspection PyMethodMayBeStatic @swagger_auto_schema( responses={ 200: openapi.Response( _( "Successfully fetched the array of all sites where the user belongs to." ), response_serializer, ) }, ) def list(self, request, *args, **kwargs): """ Return all sites where the user is part of. """ My view and decorator function: class SiteView(viewsets.ModelViewSet): """ API endpoint that allows sites to be viewed or edited """ pagination_class = StandardPagination queryset = Site.objects.all() def swagger_auto_schema(f): def wrap(self, *args, **kwargs): serializer = self.get_response_serializer() responses = ( { 200: openapi.Response( _( "Successfully fetched the array of all sites where the user belongs to." ), serializer, ) }, ) ret = responses return ret return wrap def get_response_serializer(self): if self.request.version == "v2": return AdminSiteSerializer else: return SiteSerializer def get_permissions(self): return (IsAuthenticated(),) def get_serializer_class(self): if self.request and self.request.method == "POST": return SiteCreationSerializer return SiteSerializer # noinspection PyMethodMayBeStatic @swagger_auto_schema def list(self, request, *args, **kwargs): """ Return all sites where the user is part of. """ I don't get any errors. But it does just not work, … -
How to add extra actions for endpoint routing in django rest frameworks
I'm new to django rest framework, and I'm trying to learn drf. I didn't know how to achieve this features. I want some things like(Extra Actions) as shown in screenshot to navigate all the endpoint. -
PostgreSQL and cross-site cookie warnings
I'm using python 3.7.4, django 3.0.6, javascript, Postgres 12.3.1. When my page loads on the console there are these warnings: Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/lists/list-name/” because the scheme does not match. list-name Cookie “PGADMIN_LANGUAGE” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/lists/list-name/” because the scheme does not match. list-name Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/lists/list-name/” because the scheme does not match. list-name Cookie “PGADMIN_LANGUAGE” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/lists/list-name/” because the scheme does not match. list-name Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/static/lists/js/lists.js” because the scheme does not match. lists.js Cookie “PGADMIN_LANGUAGE” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/static/lists/js/lists.js” because the scheme does not match. lists.js Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/jsi18n/” because the scheme does not match. jsi18n Cookie “PGADMIN_LANGUAGE” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/jsi18n/” because the scheme does not match. jsi18n Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/static/js/common.js” because the scheme does not match. common.js Cookie “PGADMIN_LANGUAGE” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/static/js/common.js” because the scheme does not match. common.js … -
unexpected keyword argument 'request_body' when using self in decorator
I'm trying to use 'self' in decorator swagger_auto_schema to handle the response depending on api version. When I try to use self in decorator I get this error: TypeError: swagger_auto_schema() got an unexpected keyword argument 'request_body' this is my view: class SiteView(viewsets.ModelViewSet): """ API endpoint that allows sites to be viewed or edited """ pagination_class = StandardPagination queryset = Site.objects.all() def swagger_auto_schema(f): @functools.wraps(f) def wrapper(self, *args, **kwargs): ret = f(self, *args, **kwargs) serializer = self.get_response_serializer() responses = ( { 200: openapi.Response( _( "Successfully fetched the array of all sites where the user belongs to." ), serializer, ) }, ) return ret return wrapper def get_response_serializer(self): if self.request.version == "v2": return AdminSiteSerializer else: return SiteSerializer def get_permissions(self): return (IsAuthenticated(),) def get_serializer_class(self): if self.request and self.request.method == "POST": return SiteCreationSerializer return SiteSerializer # noinspection PyMethodMayBeStatic @swagger_auto_schema def list(self, request, *args, **kwargs): """ Return all sites where the user is part of. """ -
How to access cms plugins created inside a Placeholder field
I have a Placeholder field in a model, defined like this: content = PlaceholderField(product_section_content_slotname) I created a custom view to export this model instances in a Json file, how can I access the many CMSPlugins created inside this content Placeholder field? Is there a way to access them directly from the model? -
How do I structure and save data from external API in Django?
I'm currently working on a Django web-app that essentially consumes an external API displays the data in a template while simultaneously storing the retrieved data in the database. The JSON returned from the API holds multiple JSON objects nested in arrays, e.g.: ..., "organization": { "primaryName": "Some company name", "tradeStyleNames": [ { "name": "Some alternative name", "priority": 2 }, { "name": "Some other alternative company name", "priority": 1 }, { "name": "A completely different company name", "priority": 3 }, ..., ], "industryCodes": [ { "code": "518210", "description": "Data Processing, Hosting, and Related Services", "typeDescription": "North American Industry Classification System 2017", "priority": 2 }, { "code": "73790200", "description": "Computer related consulting services", "typeDescription": "North American Industry Classification System 2017", "priority": 3 }, { "code": "561440", "description": "Collection Agencies", "typeDescription": "North American Industry Classification System 2017", "priority": 1 }, ..., ], ..., }, ..., In the example, organization logically has a one-to-many relationship with tradeStyleNames and a many-to-many relationship with industryCodes. My problem is that I only know that tradeStyleNames contains zero or more objects and that industryCodes contains one or more objects, which leads the the following questions: How do I structure my models to reflect the relationships? How do I … -
User is not authenticating
I am trying to create a simple login page. But user is always returned as none. Here's my login.html <form method = 'POST'> {% csrf_token %} <div class="body"></div> <div class="name"> <div>Chili<span>Pili</span></div> </div> <br> <div class="login"> <input type="text" placeholder="Username" name="username"><br> <input type="password" placeholder="Password" name="password"><br> <input type="submit" value="Login"> </div> </form> my login function in view.py def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username = username, password = password) if user is not None: login(user) print (user) messages.success(request, "You have successfully Logged In.") return redirect('index') else: messages.error(request, "You have entered invalid credentials. Please try again") return redirect('login') else: return render(request, 'main/login.html') The keeps returning as none and only else statement gets executed. I am not able to understand what is going wrong here -
How to validate POST request using OAuth1.0a or HMAC-SHA1 in Django
I'm using Django 3.0.7 and i need to validate the incoming POST request from my partner server by HMAC-SHA1 or OAuth1.0a and if it validated send response {"OK":"200"}. My views.py looks like this: def api_create_blog_view(request): blog_post = BlogPost(author=request.user) if request.method == 'POST': serializer = BlogPostSerializer(blog_post, data=request.data) data = {} if serializer.is_valid(): serializer.save() return Response({"response_code":"OK"}) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i have Consumer Key and Consumer Secret the example of header request looks loke this: Method: POST URL: http://api.example.com/event?foo=bar Authorization header value: OAuth realm="",oauth_consumer_key="123",oauth_nonce="abc",oauth_signature="1234",oauth_signature_method="HMAC-SHA1",oauth_timestamp="123",oauth_version="1.0" I tried to made somehow like in this topic, but it seems that i don't clearly understand how should it work. -
How to serialize File field using django rest marshmallow?
I've started using Django rest marshmallow serializers instead of the native django rest serializers because of a various advantages. Only until recently, I realized that there is no way to serialize uploaded files using marshmallow. Is there any way to serialize file field or the image field using django rest marshmallow? -
How to get origin model's name in django queryset ?
I'm using django restframework and get a complete queryset at start in every view. models.py class MAccount(BasicModel): account_id = models.CharField(max_length=45, verbose_name='ID', null=False) ... class Meta: db_table = 'account' unique_together = ('account_id', 'medium',) ordering = ['-updated_time', '-created_time', '-id'] app_label = 'account' def __str__(self): return "account" CustomModelViewSet general viewset that I want to make different work by different model name in dispatch method. class CustomModelViewSet(viewsets.ModelViewSet): parser_classes = [JSONParser, ] pagination_class = Pagination # permission_classes = [IsAuthenticated, BaseDataPermission] def dispatch(self, request, *args, **kwargs): query_model = self.queryset.model print(str(query_model)) # how can I get model's name as account here ? VSAccount specified view for actual work class VSAccount(CustomModelViewSet): queryset = MAccount.objects.all().filter(active=True) My question is how can I get the name of MAccount in dispatch method in CustomModelViewSet? -
Django form multiple select | select a valid choice
In my django project I use forms with multiple selection choices. It return the error Select a valid choice. That choice is not one of the available choices. My forms.py: class ModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): # some return code # if none of ours return default value return super().label_from_instance(obj) class ProjectForm(forms.Form): # [...] users = ModelChoiceField(widget=forms.SelectMultiple, queryset=User.objects.all(), initial=0, to_field_name='username') My user models class: class User(models.Model): username = models.CharField(primary_key=True, null=False, max_length=50, db_column='username') # [...] I don't do anything special in the views with the form. I show it via: {{ project_form.as_p }} Does anybody know how I can fix the error? Do you need more informations? EDIT: Yes the returned value in request.POST is an actual user. -
How to use self in swagger_auto_schema
I want to use self to get the api version number to modify the response serializer. What's the best way to do this? code snippet: @staticmethod def get_request_serializer(version): if version == "v2": return AdminSiteSerializer else: return SiteSerializer # noinspection PyMethodMayBeStatic @swagger_auto_schema( responses={ 200: openapi.Response( _( "Successfully fetched the array of all sites where the user belongs to." ), get_request_serializer(self.request.version), ) }, ) def list(self, request, *args, **kwargs): -
Django function include multiple functions with return
I just want to know what is the best practice to do multiple insert into different models lets say that I'm collecting a customer data including personal information address information payment information I collect all these info from one form one view and I want to do multiple inserts into multiple models (CustomerInfo,CustomerAddress,CustomerPayment) as below def insertNewCustomer(): InsertPersonalInfo() InsertAddressInfo() InsertPaymentInfo() return render() def InsertPersonalInfo(request): if request.moethod == 'POST' if form.is_valid(): form.save() return ??? def InsertAddressInfo(request): if request.moethod == 'POST' if form.is_valid(): form.save() return ??? def InsertPaymentInfo(request): if request.moethod == 'POST' if form.is_valid(): form.save() return ??? the problem is what should I return after I do the insert process in the first function which is InsertPersonalInfo() to go back again to insertNewCustomer and continue from the next function which is InsertAddressInfo I hope my question is clear :D what should I return from the nested function to return to the main function and continue from where it been called. -
django project deploy success but Server Error (500)
i assemble all file that is nessasory like setting.py , project path ,profile etc. i tried many times to solve this error but I did not get single success. and also suggest me how to set template path dir in setting.py for my project path. 1.setting.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'e(7zwftg_z4)okxle6kemn-!i30^6*y%0npb*@^)a$os&rf6wn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['ravirajsavaliya.herokuapp.com'] # Application definition INSTALLED_APPS = [ #'content' 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'contents.apps.ContentsConfig' ] 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', ] ROOT_URLCONF = 'portfolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'portfolio.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] … -
Frontend Web development with Django and ReactJS
I am working on an internship project to develop a dashboard online. This dashboard shows the performance of sales closed over a period of time (monthly, yearly etc). There is a database which already has the sales data so my task is to pull the data, do some processing and data visualizations, and display the data on the web dashboard. I read somewhere that to achieve above, I need to do server programming (with Django) and client programming (reactJS). Can someone give me pointers on how do I get started? What libraries/ frameworks should i use? Thanks in advance. -
Django: Two views for creating new user
I am scratching my head for last two days for getting completely different forms to create a user in django admin. Following are two views and I cannot understand why? First is directly running using "python manage.py runserver" and another is running webserver using nginx and docker. URL: http://127.0.0.1:8000/auth/user/add/ and I believe this is the default one. URL: http://127.0.0.1:1337/auth/user/add/ and this is weird to me. To me, this is an update/change form not create form. So what is causing this difference? Any advice is really appreciated and let me know if I need to add any thing else. Thank you -
Django sending emails problems, have tried everything on my mind
i am working on a personal portfolio website, and i want a contact form so people can get in touch with me. My problem is that the form does not send the email when someone click the submit button. The form has worked before, but then i moved the form into a and then it stopped working somehow. I have tried with the django send_mail() function, and the EmailMessage function, but nothing seems to work. I also have allowed unsecure emails on my google account. Can someone help me solve this annoying problem? HTML <div class="MainContent"> <div class="ContactForm"> <form method="POST" action="{% url 'home' %}"> {% csrf_token %} <input class="FormElement email" name="client_email" type="email" placeholder="Your email..." required> <input class="FormElement subject" name="subject" type="text" placeholder="Subject..." required> <textarea class="FormElement message" name="message" placeholder="Your message..." required> </textarea> <input class="FormElement submit" name="submit" type="submit" value="Send message"> </form> </div> </div> Settings EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my_mail@gmail.com' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' View def contact(request): if request.method == 'POST': send_mail( subject = request.POST['subject'], message = request.POST['message'], from_email = request.POST['client_email'], recipient_list = ['settings.EMAIL_HOST_USER', ], fail_silently = False, ) return render(request, 'website/contact.html') -
Docker django build fail: Couldn't import Django
Docker build failed and getting error: "Couldn't import Django. Are you sure it's installed and " web_1 | ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Dockerfile FROM debian:10.3-slim as base_image ENV PYTHONUNBUFFERED 1 RUN apt-get update \ && apt-get install -y --no-install-recommends \ ca-certificates \ exiftool \ fonts-arphic-uming \ fonts-arphic-ukai \ fonts-unfonts-core \ ghostscript \ git-core \ gpgv \ gnupg1 \ graphviz \ libfuse2 \ libmagic1 \ libmariadb3 \ libpq5 \ libreoffice \ poppler-utils \ python3-distutils \ sane-utils \ sudo \ supervisor \ tesseract-ocr \ && apt-get remove make libproxy-tools libreoffice-avmedia-backend-vlc libvlc-bin libvlc5 libvlccore9 adwaita-icon-theme gsettings-desktop-schemas libgstreamer-plugins-base1.0-0 -y \ && apt-get autoremove -y --purge RUN apt-get install -y --no-install-recommends \ default-libmysqlclient-dev \ libffi-dev \ libjpeg-dev \ libpng-dev \ libpq-dev \ libtiff-dev \ zlib1g-dev \ libssl-dev \ g++ \ gcc \ python3-dev \ python3-venv \ python3-pip \ python3-setuptools RUN pip3 install virtualenv RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN virtualenv -p /usr/bin/python3 env1 && . env1/bin/activate && pip3 install -r requirements.txt COPY . /code docker-composefile.yml version: '3' services: web: build: . depends_on: - db command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code …