Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent multiple user login in django(note: When first user is login , prevent second user to login )
I am developing an Django application using django auth module and would like to prevent multiple login using the same user name and password. It should prevent multiple logins on different machines using the same user name and password. When the second user tries to login in same account, the second shouldn't get access unless the first logout . -
Calling Javascript function and django view function at the same time
I am a django beginner, I was trying to call django view function and Javascript function at the same time through submit button in django form but django view is not calling. Is there any way that I can call both functions at the same time? -
display data from db in django
I am trying retrive data from db and display in view but output is empty. Here is my function from django.shortcuts import render from django.http import HttpResponse from pages.models import Contact # from django.views import View # Create your views here. def home(request): return render(request, 'index.html', {'title':'Home Page'}) def contact(request): if(request.method == 'POST'): data = Contact( name = request.POST['name'], email = request.POST['email'], address = request.POST['address'], city = request.POST['city'], zipcode = request.POST['zipcode'], ) data.save() dbdata = Contact.objects.all() return render(request, 'contact.html', {'title':'Contact Page','row':dbdata}) Here is my template and display data in this table <tbody> {% for row in rows %} <tr> <th>{{row.name}}</th> <th>{{row.emai}}</th> <th>{{row.address}}</th> <th>{{row.city}}</th> <th>{{row.zipcode}}</th> </tr> {%endfor%} </tbody> . I am beginner in django.and also please tell me how to debug code in django. -
I am not able to install mysqlclient in pycharm for a django project. Is there any other alternative or any other way to install mysqlclient?
(venv) C:\Users\srijan\PycharmProjects\webapp>pip install mysqlclient-1.4.6-cp38-cp38-win32.whl mysqlclient-1.4.6-cp38-cp38-win32.whl is not a supported wheel on this platform. (venv) C:\Users\srijan\PycharmProjects\webapp>pip install C:\Users\srijan\Downloads\mysqlclient-1.3.13-cp35-cp35m-win32.whl mysqlclient-1.3.13-cp35-cp35m-win32.whl is not a supported wheel on this platform. (venv) C:\Users\srijan\PycharmProjects\webapp> -
Django docker django gunicorn Postgres
Trying to run the following docker compose file version: '3' services: database: image: postgres container_name: pg_container environment: POSTGRES_USER: partman POSTGRES_PASSWORD: partman POSTGRES_DB: partman app: build: . container_name: partman_container links: - database environment: - DB_NAME=partman - DB_USER=partman - DB_PASSWORD=partman - DB_HOST=database - DB_PORT=5432 - SECRET_KEY='=321t+92_)@%_4b+f-&0ym(fs2p5-0-_nz5mhb_cak9zlo!bv@' depends_on: - database expose: - "8000" - "8020" ports: - "127.0.0.1:8020:8020" volumes: pgdata: {} when running docker-compose up-build with the following docker file # Dockerfile # FROM directive instructing base image to build upon FROM python:3.7-buster RUN apt-get update && apt-get install nginx vim -y --no-install-recommends COPY nginx.default /etc/nginx/sites-available/default RUN ln -sf /dev/stdout /var/log/nginx/access.log \ && ln -sf /dev/stderr /var/log/nginx/error.log RUN mkdir .pip_cache \ mkdir -p /opt/app \ mkdir -p /opt/app/pip_cache \ mkdir -p /opt/app/py-partman COPY start-server.sh /opt/app/ COPY requirements.txt start-server.sh /opt/app/ COPY .pip_cache /opt/app/pip_cache/ COPY partman /opt/app/py-partman/ WORKDIR /opt/app RUN pip install -r requirements.txt --cache-dir /opt/app/pip_cache RUN chown -R www-data:www-data /opt/app RUN /bin/bash -c 'ls -la; chmod +x /opt/app/start-server.sh; ls -la' EXPOSE 8020 STOPSIGNAL SIGTERM CMD ["/opt/app/start-server.sh"] /opt/app/start-server.sh : #!/usr/bin/env bash # start-server.sh ls pwd cd py-partman ls pwd python manage.py createsuperuser --no-input python manage.py makemigrations python manage.py migrate python manage.py initialize_entities the database image keeps on running, i want to stop it because otherwise … -
How to customize to_internal_value function in a RelatedField class for Django REST Framework?
In my code I need to make a custom RelatedField class for multiple ModelSerializer classes. I followed this answer, it's working great. But I need to make several RelatedField classes for every model I have. Is there any way to only make 1 RelatedField class so it can be used for all related fields in my ModelSerializer? Currently I'm doing it like this in serializers.py: class ColorRelatedField(serializers.RelatedField): def display_value(self, instance): return instance def to_representation(self, value): return str(value) def to_internal_value(self, data): return ColorParent.objects.get(name=data) class ProductCollectionRelatedField(serializers.RelatedField): def display_value(self, instance): return instance def to_representation(self, value): return str(value) def to_internal_value(self, data): return ProductCollection.objects.get(name=data) class ProductSerializer(serializers.ModelSerializer): collection = ProductCollectionRelatedField(queryset=ProductCollection.objects.all(), many=False) color = ColorRelatedField(queryset=ColorParent.objects.all(), many=False) class Meta: model = Product fields = ['id', 'product_id', 'collection', 'color', 'video', 'status'] How to make to_internal_value function returns a dynamic model depending on who calls the method: class CustomRelatedField(serializers.RelatedField, model): def display_value(self, instance): return instance def to_representation(self, value): return str(value) def to_internal_value(self, data): return model.objects.get(name=data) class ProductSerializer(serializers.ModelSerializer): collection = CustomRelatedField(model=ProductCollection, queryset=ProductCollection.objects.all(), many=False) color = CustomRelatedField(model=ColorParent, queryset=ColorParent.objects.all(), many=False) class Meta: model = Product fields = ['id', 'product_id', 'collection', 'color', 'video', 'status'] When I tried to add model parameter in the CustomRelatedField class the error message I got was: name model is … -
Using custom DRF permissions to restrict access
TL;DR How to write a custom permission class to check object-level permissions (has_object_permission) before the api-level ones (has_permission)? Definitions Suppose we are building an online annotation tool. We have Images belonging to Projects and Users working on annotating Images. Users have a role field -- Guests have read-only access, Developers may change the Image fields and Owners may change both Projects and Images. The models: class Image(models.Model): data = JSONField() project = models.ForeignKey(Project) class Project(models.Model): pass class User(AbstractUser): ROLE_GUEST, ROLE_DEVELOPER, ROLE_OWNER = range(3) ROLE_CHOICES = [(ROLE_GUEST, "Guest"), (ROLE_DEVELOPER, "Developer"), (ROLE_OWNER, "Owner")] role = models.IntegerField(default=ROLE_GUEST, choices=ROLE_CHOICES) Suppose we wish to restrict access to and within some Projects. We are adding m2m model UserProjectRole: class UserProjectRole(models.Model): user = models.ForeignKey(User) project = models.ForeignKey(Project) project_role = ... # same as in User Now we wish to set up permissions in a way that, if user requests access to API endpoints regarding some Project: if there is no UserProjectRole with this user and this project, permissions defaults to his global role if there is such UserProjectRole, the permissions are using his project_role instead of role Problem We are implementing custom permission class: # permissions.py from rest_framework import permissions class AtLeastDeveloper(permissions.BasePermission): def has_permission(self, request, view): return … -
Represent a MySQL BIT column in django model
What would be the field type to use in a Django model if I have a BIT column in a MySQL table. I tried to use: active = models.BooleanField(db_column='Active', default=True) The creation works fine but when trying to access my model in admin view, I am getting a KeyError Exception b'\x00'. I found no equivalent of BIT reading django doc. (I am using django 2.2.6) -
Django show message in every view
I want to show a message in every view in my Django project. Once a user has created an account, I send them an email asking them to verify their email and until they have verified their email address (by visiting a verify URL) I'll show the message. Now, I don't want to show the message on the verify URL view and I don't want the message to be "duplicated" i.e. show two of the same messages. Initially I tried the approach of creating a middleware that will simply add the message to every response but this has 2 downsides: The message appears in the verify view -- currently I remove all messages[1] from that view, but this isn't ideal. When I use a redirect in my view, I get more than one of the same message. Most of the redirects I use are after a POST so I could check if the request is a GET but that doesn't feel right. Here's the middleware: class VerifiedEmailMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.user.id … -
How to add placeholder inside the html links in django cms?
I want to make facebook link in my html dynamic with the help of django cms placeholder and for this I tried like this but it didn't worked. How can I do it ? <div class="footer--social"> <div class="social-wrapper mr-3"> {% static_placeholder 'Add facebook link' %} <a href=""> <img src="{% static 'assets/images/facebook.svg' %}" alt=""> </a> </div> <div> -
How to save and delete data automatically in Django database?
I am trying to build a website using Django, but I would like to update my database for every 15 mins with new scraped data. Also, I would like to delete the old data that has been saved for longer than one week. I was able to do it manually by using Django manage.py shell, but how can I make it automatically? Is there any library for automatic database management that is compatible with Django? Thank you in advance! -
How to I Change my SQL to Django ORM Left on and condition?
SELECT website.id, website.title,article.looks FROM website LEFT OUTER JOIN article ON (website.id = article.website_id) AND article.id =(SELECT MAX(id) FROM article s WHERE s.website_id = website.id) ORDER BY article.looks ASC I try too many to change this SQL to Django ORM -
Django rest framework and vuejs modification without reloading the page
I'm working on a project with VueJs and Django REST. The goal is to communicate with Django REST (change values in a table and see the update without reloading the page). The problem is that I have to reload the page to see the update. Do you know what's wrong with my code and how to fix it. Thank you for your help. Here I define all the routes for my different components. Index.js Vue.use(VueRouter); const routes = [ { path: '/prescripteurs/', name: 'prescripteurs', component: PrescripteurListe }, { path: '/prescripteur/:id/', name: 'prescripteur', component: PrescripteurDetail }, { path: '/nouveau/prescripteur', name: 'prescripteurNew', component: PrescripteurCreation } ]; Here, I launch a function that allows me to retrieve all the data from my api. PrescripteursListe.vue <script> // Import du service servant à communiquer avec l'API import { apiService } from '@/common/api.service'; import PrescripteurFiltres from './PrescripteurFiltres'; export default { name: 'PrescripteurListe', components: { PrescripteurFiltres }, data() { return { filtres: [], prescripteurs: [] }; }, mounted() { // Appel cette fonction au moment de la création du DOM this.getPrescripteurs(); }, methods: { // Fonction qui récupère les data de tous les prescripteurs et les injecte dans un tableau getPrescripteurs() { let endpoint = '/api/prescripteurs/'; apiService(endpoint).then(data … -
Is it possible to fix the port number for graphql altair?
I'm using Django as backend providing a GraphQL API. I'm using Django's builtin suport and django-cors-headers to use the CORS mechanism. To debug the API I'm using Altair. Can I define a fixed port number for altair that I can consider altair as trusted origin in the Django settings.py file (CSRF_TRUSTED_ORIGINS). -
Django security: how to log and block anything related to Wordpress targeting bots
I was just looking for some general advise on Django security - especially around Wordpress related bots targeting the site, i.e., if anythings does a look up on wp-admin or wp-login or wp-content etc etc they'll be immediately blocked ... it's possibly more on the server access lebel ... maybe within nginx.conf? -
how to check where is url from? in views.py [Django]
this is my views.py I need to check where is the url from? to redirect to the correct url. I try to use request.path and request.get_full_path but it's not working. my views.py def deletemovie(request,id): user=request.user.id movie = get_object_or_404(Reviewmovie,id=id) movie.delete() if request.path == 'report:report': return redirect('report:report') else: return redirect('movie:dashboard',user) -
AWX Ansible debugging via PyCharm
I have issue. I need to have ability to run and debug application django web application that runs in docker container. There is link on it: https://github.com/ansible/awx I tryed to stop awx_web application from container and run start it from PyCharm IDE. Application starts, but I have default message: AWX is upgrading and after that I don't get login to account page. Can you help me how can I solve mey issue? Thanks for any answers. -
how to remove syntax error while using range(len(data)) in an html page in django?
I am sending my data to Html page in tuple format and want to display using range(len(data)) in Html page in Django but it is showing this error " Could not parse the remainder: '(len(data))' from 'range(len(data))' ". please help. -
How to retrive data from mysql and display in view using django
Here is my model where migrations from django.db import models # Create your models here. class Contact(models.Model): name = models.CharField(max_length=125, null=True) email = models.EmailField() address = models.CharField(max_length=255) city = models.CharField(max_length=150) zipcode = models.CharField(max_length=15) i am trying display data in view <div class="row d-block"> <table class="table table-responsive"> <thead> <tr> <th>Name:</th> <th>Email:</th> <th>Address:</th> <th>City:</th> <th>Zipcode:</th> </tr> </thead> <tbody> {% for row in rows%} <tr> <th>{{rows.name}}</th> <th>{{rows.emai}}</th> <th>{{rows.address}}</th> <th>{{rows.city}}</th> <th>{{rows.zipcode}}</th> </tr> {%endfor%} </tbody> </table> Here is my function where i send data in db. my next step is retrive data from db and dispaly in html from django.shortcuts import render from django.http import HttpResponse from pages.models import Contact # from django.views import View # Create your views here. def home(request): return render(request, 'index.html', {'title':'Home Page'}) def contact(request): if(request.method == 'POST'): data = Contact( name = request.POST['name'], email = request.POST['email'], address = request.POST['address'], city = request.POST['city'], zipcode = request.POST['zipcode'], ) data.save() dbdata = Contact.objects.all() print(dbdata) return render(request, 'contact.html', {'title':'Contact Page','row':dbdata}) When i trying retrive data from db error will come UnboundLocalError at /pages/contact/ local variable 'dbdata' referenced before assignment How i can retrive and display data?? -
socket.gaierror: [Errno -2] Name or service not known when I run unittest in Django
I have following code. When I run unittest for send_user_notification I get error socket.gaierror: [Errno -2] Name or service not known. How to fix it? Thnx. def send_event(channel='', message=''): channel_layer = get_channel_layer() asyncio.run(channel_layer.group_send( channel, { "type": 'send_data', "message": message } )) @receiver(post_save, sender=User) def send_user_notification(sender, **kwargs): instance = kwargs['instance'] if kwargs['created']: send_event(f'user_{instance.id}', {'message': "Welcome!"}) -
CRUD template with using bootstrap in django
How to create CRUD template using bootstrap in Django. without using django forms -
Nested dictionary from Django QuerySet
I am stuck in creating nested dictionary from Django QuerySet My code is qr_dict = [{'id':i.pop('ID'), 'data':[{i['ACCOUNT_NAME']}] } for i in query_result] i got the result from code listed above: [{'id': 123, 'data': [{'MUHAMMAD ADNAN'}]}, {'id': 123, 'data': [{'NAVEED AHMED SUNNY'}]}] i need the result like following dictionary list: [{'id': 123, 'data': [{'MUHAMMAD ADNAN'},{'NAVEED AHMED SUNNY'}]}] what is wrong i am doing please help thanks in advance. -
Using many-to-many items before save()
I am using models which has many-to-many fields What I want to do is like this. Fetch items from web and store in memory Filter items. remove or add many-to-many field. Save in database. my model class Tweet(models.Model): text = models.TextField(null=True) genre = models.ManyToManyField(genre) filter tweets = fetchfromweb() filtered = [] for tweet in tweets: if tweet.text == x : tweet.genre.add(genreObj) filtered.append(tweet) else: pass for i in filtered: // write in db i.save() However it shows error where tweet.genre.add(genreObj). Without save(), I couldn't access many-to-many fields. so for now my solution is like this. tweets = fetchfromweb() filtered = [] for tweet in tweets: tweet.save() ## save and create manytomanyfield if tweet.text == x : tweet.genre.add(genreObj) tweet.save() else: tweet.remove() However it require many db insert and remove, is it good practice??? Or is there any good ideas ??? -
Does Django have method to 'validate' form fields BEFORE form submission?
I have read Django documentation and found almost 2 ways to validate fields forms (clean_data, validators) but I am looking for a method to test fields before form submission i can do it with JS but I wonder if there is a way to do it with Django -
Is there any way to create dynamic tables without affect migration in django?
Is there any way to create dynamic tables without affect migration in django?