Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How I save data on database table from django?
I made a django website where doctor and patient both can signup. Patient mark their problem and it will send to those doctor whom he/she want, like question asking on Quora. And I also want to save data in db But my webpage when patient insert data it does not save in database. Models.py class patients(models.Model): Fever=models.BooleanField() others=models.TextField() Views.py from django.shortcuts import render, redirect from .models import patients def patient(request): if request.method == 'POST': fever=request.POST['Fever'] others=request.POST['others'] patient_details=patients(Fever= fever,others = others) patient_details.save() return render(request, "patient") else: return render(request, "patient.html") Patient.html <form action="patient"> <label for="exampleFormControlTextarea1"><u>Mark Your Problems</u></label><br> <!-- FEVER --> <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1"> <label class="form-check-label" name="fever" for="inlineCheckbox1">Fever </label> </div> <!--Others--> <h6 style="text-align:left;"><u>Others</u></h5> <div class="form-group"> <textarea class="form-control" id="exampleFormControlTextarea1" rows="1"></textarea> </div> <button class="btn btn-lg btn-primary btn-block" type="submit"> SUBMIT </button> </h6> </form> How I store these data on database ? -
Django - list of objects not visible in DetailView
I have list of posts on my homepage, which are links to post DetailView. Links works correctly, but when i go to DetailView, list is no more visible - i have to go back to home page to choose other post. Element which is showing posts list is located on base.html, correctly passes objects list to home.html, and in post_detail.html list is empty. Homepage looks like this Post DetailView looks like this - posts list is no more visible Inspect view on homepage Inepect view on DetailView - ul element is empty base.html <body> <div> <ul> <li> <a href="{% url 'blog-home' %}"> home</a> </li> <li> <a> items</a> <ul> {% for post in posts %} <li> <a href="{% url 'post-detail' post.id %}"> {{ post.title }}</a> </li> {% endfor %} </ul> </li> </ul> </div> <di> {% block content %} {% endblock content %} </div> </body> home.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <div> <a href="#">{{post.title}}</a> <p>{{post.content}}</p> <p>{{post.date_posted}}</p> </div> {% endfor %} {% endblock content %} post_detail.html {% extends "blog/base.html" %} {% block content %} <div> <a href="#">{{object.title}}</a> <p>{{object.content}}</p> </div> {% endblock content %} urls.py from django.urls import path from .views import PostListView, PostDetailView from … -
Django swagger request change data description
I need to change default request description for one api_view in swagger. How to achieve this? Because request schema is based on serializer_class. For example, I have viewset class UserViewSet(viewsets.ViewSet, generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) with such view: @action(detail=False, methods=['post']) def login(self, request): data = request.data email = data['email'] email = email.lower() user = User.objects.filter(email=email).first() password_valid = user.check_password(data["password"]) if not password_valid: return Response({'error': 'wrong password'}, status=status.HTTP_401_UNAUTHORIZED) serializer = UserSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK) By default, swagger with generate schema with request fields based on UserSerializer class. So, for custom behaviour I should create new serializer class? class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() and add this as request_body in swagger_auto_schema decorator? -
Django Permission Not Appearing in Admin
First of all I have a Legacy database, we run it in MYSQL WB for the time being. This difficulted the making of migrations. When i created the second app and defined the model i made fakemigrations to tell django that the tables were ok. The django-admin now shows only the permissions of the tables of the first app, the second app permission doesn´t appear and when i looked in the auth_permission table these don´t appear either. Should i insert the permission of the second app directly? I want to have crud capabilities with the model of the app and assigning group permissions between these 2 apps(More in the future), so i should follow this path or just hardcode in a permission.py file?. in order i did the following to get to this situation: 1-Updated the project with the 2 model app. 2-produced fakemigrations to tell django all is ok. 3-updated django-admin. -
Django vs .net core
I am looking for comparison between Django and .net core .In my current project I am using angular as front end and .net core as back end technology. I am trying to explore other web framework for my new project. As Django is based on python what is pros/cons of Django over .net core? How scale able and maintainable is Django? -
Running Nameko Micro service failed
I have a Nameko micro-service which I run with the below command line, but nothing happen no errors or success running message noted : nameko run service --config config.yaml Here is the config file AMQP_URI: amqp://guest:guest@localhost:8001/vhost RABBIT_CTL_URI: http://guest:guest@localhost:8001 -
Follow user on facebook and instagram using API (graph API)
In my app there is a follow button, I want on click of the button, The User clicking the follow button can follow the intended user on connected social media like Facebook and Instagram. Is there any way to achieve this? -
How to solve django.db.utils.DataError: (1406, "Data too long for column 'product_team' at row 1")
After running a function containing the below create process : client_daily.objects.create(client_id=c,title=c.title,products=product_list,categories=categories[:-2],product_team=product_team[:-2],pcategory=pcategory[:-2],date=date) I came up with the error: Traceback: File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py" in execute 112. return self.cursor.execute(query, args) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/MySQLdb/cursors.py" in execute 209. res = self._query(query) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/MySQLdb/cursors.py" in _query 315. db.query(q) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/MySQLdb/connections.py" in query 239. _mysql.connection.query(self, query) The above exception ((1406, "Data too long for column 'product_team' at row 1")) was the direct cause of the following exception: File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/www/wwwroot/geolocator/intranet/views.py" in cron_job_functions 2103. message=my_scheduled_job() File "/www/wwwroot/geolocator/intranet/views.py" in my_scheduled_job 882. client_daily.objects.create(client_id=c,title=c.title,products=product_list,categories=categories[:-2],product_team=product_team[:-2],pcategory=pcategory[:-2],date=date) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/models/query.py" in create 399. obj.save(force_insert=True, using=self.db) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/models/base.py" in save 796. force_update=force_update, update_fields=update_fields) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/models/base.py" in save_base 824. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/models/base.py" in _save_table 908. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/models/base.py" in _do_insert 947. using=using, raw=raw) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/models/query.py" in _insert 1045. return query.get_compiler(using=using).execute_sql(return_id) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 1054. cursor.execute(sql, params) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/db/backends/utils.py" in execute 79. return super(CursorDebugWrapper, … -
How to modify python script programmatically, a template so to speak?
Based on user input, I want to use different databases for serverless handler. Basically I want to add a few lines of code in two places. How is it possible to do programmatically? -
How to save data related to two models
Im learning dajngo and have I problem, I dont even know what I should search for to solve it. So maybe someone knows what i need. So far I have two models in my project 1) CustomUserModel with additional data 2) RunningTrackModel wich provides information about tracks like distance, location, etc. My goal is now to save user specific Data for each object of the RunnningTrackModel like time, date, etc. Whenever a new RunningTrackObject is created, all users should get the possibility to sign up and save data to tracks they signed up for, but whats the right way to implement this? -
post_save signal not updating data in Django
I am trying to update the has_video attribute of property model with the below mentioned code. I tried to debug, and the code executes properly on saving data in admin. But the data is not getting updated. Any idea on what I might be doing wrong here while updating the property model? def post_save_property(sender, **kwargs): property_obj = Property.objects.get(pk=kwargs['instance'].pk) try: if property_obj.pk: if 'video_youtube' in property_obj.media.values_list('image_type', flat=True): property_obj.attr.has_video = True else: property_obj.attr.has_video = False refresh_listing_in_index(property_obj, property_class_klass=PropertyClass) else: pass except: logger.error(traceback.format_exc()) What I tried? I tried to test by adding the code to save method in property model as shown below: def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) # update has_video if 'video_youtube' in self.media.values_list('image_type', flat=True): self.attr.has_video = True else: self.attr.has_video = False return super().save(*args, **kwargs) This saves the data in database. But the problem is: self.media value is updated only after save and thus, has_video attribute is updated only if I save my model for one more time. -
How can I know if I liked a post in board like facebook?
I am developing SNS app. In the Facebook timeline, the posts come out showing whether I liked it or not. How should these systems be designed? I have a table that contains rows that I liked, but I don't know how to effectively show whether the timeline posts I like or not. -
How to display data from given api onto a single webpage
I was given an API, and need to display the given data on a single web page. Was thinking of using django as a framework to build page but open to suggestions. I haven’t worked with APIS before, so any help would be appreciated. -
editing nginx.conf file over cloud foundry
I have an application built using django, angular and hosted using cloudfoundry. partial URL with http fails to proceed, for example http://www.example.com/home will fail but https://www.example.com/home will work fine. same way http://www.example.com will redirect to https://www.example.com but when given with half URL the redirection is failing. So i did some research on this issue, and found that nginx.conf file needs to be edited and could not find more. is it need to be uploaded with the django application to cloud foundry any guide over this will be very helpful -
Nginx 502 Bad Gateway due to gunicorn and nginx
I'm trying to deploy my Django app to Digital Ocean. I set it up with gunicorn, nginx and supervisor but I get 502 Bad Gateway error. There is a problem with connecting to gunicorn.sock. Gunicorn Log [2020-05-28 11:40:44 +0000] [2439] [ERROR] Retrying in 1 second. [2020-05-28 11:40:45 +0000] [2439] [ERROR] Retrying in 1 second. [2020-05-28 11:40:46 +0000] [2439] [ERROR] Retrying in 1 second. [2020-05-28 11:40:47 +0000] [2439] [ERROR] Can't connect to /home/user/run/gunicorn.sock [2020-05-28 11:40:49 +0000] [2445] [ERROR] Retrying in 1 second. [2020-05-28 11:40:50 +0000] [2445] [ERROR] Retrying in 1 second. [2020-05-28 11:40:51 +0000] [2445] [ERROR] Retrying in 1 second. [2020-05-28 11:40:52 +0000] [2445] [ERROR] Retrying in 1 second. [2020-05-28 11:40:53 +0000] [2445] [ERROR] Retrying in 1 second. [2020-05-28 11:40:54 +0000] [2445] [ERROR] Can't connect to /home/user/run/gunicorn.sock Nginx Log 020/05/28 11:34:34 [error] 2071#2071: *8 connect() to unix:/home/user/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: (IP), server: (IP), request: "GET / HTTP/1.1", upstream: "http://unix:/home/user/run/gunicorn.sock:/" Any idea why this is happening? -
how to get ids of ManyToMany through a models foreignKey django
how to access all ids of Languages through Programmer class Language(models.Model): name = models.CharField(max_length=20) class Programmer(models.Model): name = models.CharField(max_length=30) langs = models.ManyToManyField(Language,through='Level') class Level(models.Model): language = models.ForeignKey(Language) programmer = models.ForeignKEy(Programmer) level = models.CharField(max_length=10) i tried this ways but no one worked in Programmer instance : instance.level_set.language_id , instance.level.all.language_id , instance.level.all.language.id and also tried this instance.level_set.language.id all said Programmer has no attribute ,language , language_id etc thanks for any advice -
Django ERR_CACHE_MISS on login page after clicking a link and back
I have a login page with a form with username and password fields and a submit buttons. In the same page there are links to other pages. I'm using the vanilla Django login view. The user can login using the correct credentials, otherwise the authentication form shows authentication error as expected. Everything works fine so far. The issue I'm having is reproducible this way: go to login page and input wrong credentials correctly validation errors appear on the form click some link on the page correctly the browser brings me on the other page following the GET request click on browser back button At this point I get this message from the browser: Confirm Form Resubmission This webpage requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed. Press the reload button to resubmit the data needed to load the page. ERR_CACHE_MISS It's weird, but even more weird is that if I check on Disable cache in Chrome DevTools Network panel, the problem disappears (ie. when I click back, I see the form precompiled with previously inserted data). So … -
Button onlick doesn't show popup-form django
I have a simple problem and I've been trying to solve it for hours it so I'm going nuts. I am trying to make a sign up button and when user clicks it, it opens a pop-up signup form but when I click it nothing happens.(I am using django btw) So there are my files: --Views.py def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): #Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) #Set the chosen password new_user.set_password(user_form.cleaned_data['password']) #Save the user object new_user.save() return redirect('home') else: user_form = UserRegistrationForm() return render(request,'account/signup.html',{'user_form':user_form}) --Forms.py class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='password',widget=forms.PasswordInput) class Meta: model = User fields = ('username','email') --Signup.html {% extends "base.html" %} {% load static %} {% block stylesheets %} <link rel="stylesheet" href="{% static 'css/signup.css' %}"> {% endblock stylesheets %} {% block content %} <!-- Modal HTML Markup --> <div class="form-popup" id="myform"> <form class="form-container" action="{% url 'signup' %}" method="post"> {% csrf_token %} <h1>Register</h1> <label for="email"><b>Email</b></label> <input type="text" name="email" placeholder="email" required> <label for="password"><b>password</b></label> <input type="password" name="password" placeholder="password" required> <label for="username"><b>username</b></label> <input type="text" name="username" placeholder="username" required> <button type="submit" name="button" class="register-btn">Sign Up</button> </form> </div> {% endblock content %} {% block scripts %} <script type="text/javascript" src="{% static 'js/signup.js' %}"></script> … -
Can't connect to MySQL server on 'db' ([Errno -2] Name does not resolve)
I am trying to connect mysql with docker using python. but this error is occurring. I am using python3. I am new in docker so I am unable to find any solution. Dockerfile: FROM python:3.8-alpine MAINTAINER Fahim Ahmed Irfan ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache jpeg-dev RUN apk --update add --no-cache --virtual .tmp-build-deps \ gcc build-base libffi-dev freetype-dev libpng-dev openblas-dev linux-headers mysql-dev zlib zlib-dev RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR ./app COPY ./app /app RUN adduser -D user User user EXPOSE 8000 Docker-compose file: version: '3' services: app: restart: always build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python check_db.py --service-name mysql --ip db --port 3306 && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=root - DB_PASS=supersecretpassword depends_on: - db db: image: mysql:8.0 environment: - MYSQL_HOST=localhost - MYSQL_PORT=3306 - MYSQL_ROOT_HOST=% - MYSQL_DATABASE=app - MYSQL_USER=root - MYSQL_PASSWORD=supersecretpassword ports: - "3306:3306" check_db.py: import socket import time import argparse """ Check if port is open, avoid docker-compose race condition """ parser = argparse.ArgumentParser(description='Check if port is open, avoid\ docker-compose race condition') parser.add_argument('--service-name', required=True) parser.add_argument('--ip', required=True) parser.add_argument('--port', required=True) args = … -
How to save a user’s image and display it
I have a user profile model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(User,default='default.jpg', upload_to='profile_pics',) #default avatar user /download avatar user avatar = models.CharField(max_length=300, null=True, blank=True) #field for storing url from a social network def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) It has two fields for the image. 1- regular default avatar (input image) it can be set by the user and after downloading it will be saved in the media / profile_pics folder. 2 field (input avatar) - to store the avatar url from outside (social network). I also have two authorizations, regular and social (python-social-auth). When authorizing a call through social networks, I use the function to get the url of the user address: def get_avatar(backend, response, user=None, *args, **kwargs): if backend.name == 'vk-oauth2': url = response.get('photo', ) if url: user.profile.avatar = url user.profile.save() I get a link of this kind (url variable): https://sun9-12.userapi.com/c852132/v852132234/118b6c/aB0GoDEWzaw.jpg and save this url user.profile.avatar. In the template, I output: <img src="{{user.profile.image.url }}"> - #default avatar user/download avatar user <img src="{{user.profile.avatar}}"> - #social avatar (url) user How do I make sure that when authorizing through social … -
Django not printing post request
I'm learning Django and creating my website... Created and basic HTML contact form and to check if it is working I've added an print option on form submission(method==post) but after I submit the form, on terminal prints nothing below are my codes Thank you For your time views.py def contact(request): if request.method == 'POST': print ("we are done") return render(request,"news/Home/Homepage.html") _____models.py_______ class Contact(models.Model): name=models.CharField(max_length=100) email=models.CharField(max_length=150) msg=models.TextField() ____my html contact form__________ <form class="grid-form" method="post" action="/"> {% csrf_token %} <div class="form-control narrow"> <label for="name">Name</label> <input name="name" id="name" type="text"> </div> <div class="form-control narrow"> <label for="email">Email</label> <input name="email" id="email" type="email"> </div> <div class="form-control"> <label for="message">Message</label> <textarea name="message" id="message" rows="4"></textarea> </div> <ul class="actions"> <li><input value="Send Message" type="submit"></li> </ul> </form> -
Boostrap datetimepicker wrong visualization
I have the following html's boostrap code: <div class="input-group date col-2" id="datetimepicker1" data-target-input="nearest"> {{form.data_contabile|as_crispy_field}} <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="far fa-clock"></i></div> </div> </div> <script> $(function () { $("#datetimepicker1").datetimepicker({ format: 'DD/MM/YYYY', }); }); </script> And in my form the following code: class MaterialeForm(forms.ModelForm): data_contabile = forms.DateTimeField(input_formats=['%d/%m/%Y'], widget=forms.DateTimeInput(attrs={ 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker1'})) But the layout are the following: Where is the error? -
Get "code" when using Azure AD Graph API from the response
This question is related to this other post: how to get 'code' for getting access_token when using Azure AD Graph API. Let me open a new thread as I cannot write a comment. I will try to explain my problem as best as possible: Context My app is a web server written in Django with several REST APIs used by the frontend. I had an API for the users to register, which used to use Microsoft login api perfectly. Everything was fine until we found out some clients had MFA and we could not use the api anymore. Possible solution I followed the instructions in https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow for getting the token, and I can do it correctly manually. That is: Step 1: I write this url on the browser and login // Line breaks for legibility only "https://login.microsoftonline.com/<tenant>/oauth2/v2.0/authorize? client_id=<client_id> &response_type=code &redirect_uri=<redirect_uri> &response_mode=query &scope=https://graph.microsoft.com/.default" Step 2: The response I get in the browser address bar contains the code. I extract it manually, using the console. <redirect_uri>/?code=?code=<authorization_code>&session_state=<session_state> Step 3: With this code I can ask for a token to the api: // Line breaks for legibility only POST /{tenant}/oauth2/v2.0/token HTTP/1.1 Host: https://login.microsoftonline.com Content-Type: application/x-www-form-urlencoded client_id=<client_id> &scope=https://graph.microsoft.com/.default &code=<authorization_code> &redirect_uri=<redirect_url> &grant_type=authorization_code &client_secret=<client_secret> Problem Ok, so … -
How to order a django qset by two fields and then annotate it with a rank
I am using Django 3 with PostgreSQL. I would like to annotate my queryset with a rank, based on ordering by two fields. My simplified Model looks like this class Player(model.Models): name = models.CharField() primary_score = models.IntegerField() secondary_score = models.IntegerField() The queryset should order by primary_score first and then for players with the same primary_score it should rank by secondary_score. The variable rank should then be annotated with the position of the player in the ordered queryset. I can do this for one field, but do not know how to do it for both: queryset = Player.objects.order_by('primary_score', 'secondary_score').annotate(rank=Window(expression=Rank(), order_by=F('primary_score').desc())) Also, this might cause the ordering operation to happen twice. Any ideas will be appreciated. -
Get date range of week from a given date range
I've been trying to break a given date range into date range each week, but couldn't find any effective way to do it. Let's say I have input: 05/05/2020 (Tues) - 04/06/2020, and the out put would be like ('05/05/2020', '10/05/2020'), ('11/05/2020', '17/05/2020'), .... Any help would be appreciated, thank you so much^