Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Nested Serializers won't work independently- Key Error /dashboard/api/institution/editor/ 'id'
I'm trying to create an app using JQuery Datatables Editor and a Django REST framework API. Whenever I try to create an entry, I am returned the above key error. I believe the problem is traced back to the to_internal_value function within the InstitutionDatatableSerializer. However, I cannot delete this function as it is necessary for me to create a new entry for the InvestigatorDatatableSerializer. How can I fix the serializer? serializers.py class InstitutionDatatableSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) def to_internal_value(self, data): return get_object_or_404(Institution, pk=data['id']) class Meta: model = Institution fields = ('__all__') datatables_always_serialize = ('id',) class InvestigatorDatatableSerializer(serializers.ModelSerializer): institution_name = serializers.ReadOnlyField(source='institution.name') institution = InstitutionSerializer() class Meta: model = Investigator fields = ('id', 'last_name', 'first_name', 'email', 'institution_name', 'institution', ) datatables_always_serialize = ('id',) models.py class Institution(models.Model): id = models.AutoField(unique=True, primary_key=True) name = models.CharField(max_length=50) dept = models.CharField(max_length=50) class Meta: managed = True db_table = 'institution' def __str__(self): return str(self.name) class Investigator(models.Model): id = models.AutoField(unique=True, primary_key=True) last_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) email = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) institution = models.ForeignKey(Institution, models.DO_NOTHING, related_name='institution_id', ) class Meta: managed = True db_table = 'investigator' def __str__(self): return str(self.last_name) -
How to open and edit the pdf file uploaded by form
I have ModelViewSet class which accepts the uploaded file. using pymupdf( pdf handling library) import fitz class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer def list(self, request): serializer = s.DrawingSerializer(queryset, many=True) return Response(serializer.data) def create(self, request, *args, **kwargs): #file is uploaded as 'drawing' doc = fitz.open(request.data['drawing']) class Drawing(models.Model): drawing = models.FileField(upload_to='uploads/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) When I uploaded the file, there comes the error like this. fitz.fitz.FileNotFoundError: no such file: 'mypdf.pdf' -
AttributeError at /users/register/ Manager isn't available; 'auth.User' has been swapped for 'userty.MyUser'
I get this error whenver I try to register a new user from my website. I have two types of users (Athlete and Host). Ive created their models as follows from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from COMBAT_CON_F import settings class MyUserManager(BaseUserManager): def normalize_email(self, email): email_parts = email.split('@') domain = email_parts[-1].lower() username = '@'.join(email_parts[:-1]) return f'{username}@{domain}' def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class MyUser(AbstractUser): #objects = MyUserManager() is_athlete = models.BooleanField(default=True) is_host = models.BooleanField(default=False) class Athlete(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) WEIGHT_CATEGORY_CHOICES = ( ('Straw Weight', 'Straw Weight'), ('Fly Weight', 'Fly Weight'), ('Bantam Weight', 'Bantam Weight'), ) user = models.OneToOneField('userty.MyUser', on_delete=models.CASCADE) email = models.EmailField(null=True, default='example@example.com') name = models.CharField(max_length=100, null=True) profile_picture = models.ImageField(upload_to='athlete_pics/', null=True, blank=True) contact_number = models.CharField(max_length=20) date_of_birth = models.DateField() age = models.IntegerField() gender = models.CharField(max_length=1, choices=GENDER_CHOICES) height = models.DecimalField(max_digits=4, decimal_places=2) weight = models.DecimalField(max_digits=4, decimal_places=2) weight_category = models.CharField(max_length=20, choices=WEIGHT_CATEGORY_CHOICES) fighting_style = models.CharField(max_length=100) club_name = models.CharField(max_length=100) coach_name = models.CharField(max_length=100) record = models.CharField(max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = () def __str__(self): return self.user.username class … -
Telegram, Python-telegram-bot==13.13, webhook
help me figure out what the error is. I redesigned the bot to work from a webhook I will receive a reply from a telegram POST /webhook/ 200 OK but the bot stopped responding to commands when I press /start the bot is silent. Tell me where I went wrong? thanks in advance I start everything on django for port 8050 from telegram import * from telegram.ext import * from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from decouple import config import json TOKEN = config('TELEGRAM_TOKEN') bot = Bot(token=TOKEN) updater = Updater(token=TOKEN) dp = updater.dispatcher @csrf_exempt def webhook(request): print('this is webhook') if request.method == 'POST': update = Update.de_json(json.loads(request.body), bot) dp.process_update(update) return HttpResponse('ok') def start(update: Update, context: CallbackContext) -> None: print('this is start') update.message.reply_text('Hello World!') def echo(update: Update, context: CallbackContext) -> None: print('this is echo') update.message.reply_text(update.message.text) if __name__ == '__main__': print('this is main') dp.add_handler(CommandHandler('start', start)) dp.add_handler(MessageHandler(Filters.text, echo)) updater.start_webhook( listen="0.0.0.0", port=8050, ) updater.idle() -
How to configure nginx to serve Django at a different endpoint?
I separated my frontend (NextJS) and my backend (Django). I want to serve my Django app at /api using Nginx. events {} http { server { listen 80; gzip on; server_name $HOST; location /api/ { proxy_pass http://backend:8000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location / { proxy_pass http://frontend:3000/; } } } where backend and frontend are corresponding docker-compose services. Django is not recognizing my configuration and is having a lot of issues. For example when I access /api/admin it redirects to /admin and causes troubles. I searched around but can't find any answers. How can I solve this? -
Making a file available at url using uWSGI, Django and nginx
I'm attempting to have Django/nginx serve a specific file under a specific URL, unrelated to the Django app itself. I have a .php file I'd like to serve and be displayed as a normal PHP. The PHP file I'm using: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP - Hello, World!</title> </head> <body> <h1><?php echo 'Hello, World!'; ?></h1> </body> </html> I tried adding this to my nginx configuration to achieve it: location /deploy { alias /var/www/deploy.php } When I then attempted to run my uWSGI app, going to that URL (example.com/deploy) does indeed redirect to deploy.php, but I get a pop-up to save the file on my PC (download) instead of it being displayed as a webpage. I'm not sure how to configure it to behave correctly, I'm working with nginx for the first time. -
Django GeometryDistance usage with postgis database
I am having some issues using GeometryDistance where I have a node point object and am trying to find the closest node in another table in the database. GeometryDistance(start_node.geom, vertex.objects.all()) This is the truncated output. GeometryDistance(Value(<Point object at 0x7f3afe8e4d90>) <-> <QuerySet [<WaysVerticesPgr: WaysVerticesPgr object (1)>, <WaysVerticesPgr: WaysVerticesPgr object (2)>, <WaysVerticesPgr: WaysVerticesPgr object (3)>, and the only reference info I can find is this from Django. I know the issue is with the WaysVerticesPgr queryset in the second position but don't know how to only get the geometry from the table. I would like to return the closest nodes in the vertex table to the start_node. the vertex table has the geometry in column 'the_geom'. vertex.objects.order_by(GeometryDistance(start_node.geom, vertex.objects.all().the_geom)) Here, the queryset doesn't have the_geom attribute. I remember reading that django doesn't evaluate querysets until it has to either through iteration or other methods but I don't know exactly how I should go about this query. Any help is appreciated. -
Django: Model attribute looks for field works in view, but not in template
Say I have a model: from django.db import models class Foo(models.Model) fav_color = models.CharField(max_length=250, help_text="What's your fav color?") print(Foo.fav_color.field.help_text) # prints: What's your fav color? Say I have a view with context: { 'Foo': Foo } And in a template {{ Foo.fav_color.field.help_text }}, the result will be blank. However {{ Foo }} will print the string representation of the model, so I know the models is getting passed into the template. Why are the attributes look ups to get the help_text failing in the template, why is the help_text empty in the template? -
facing duplicate attributes in django login page
so i am trying to create a login,registration and logout access using forms in django. i have created my custom user model where user will access this with their phone numbers. but when i run the function, phone number comes twice and password. if i want to access the account, i need to fill both main and duplicate phone number to log in. Can anyone tell me how can i resolve this problem? Forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from phonenumber_field.formfields import PhoneNumberField from .models import * class CustomUserCreationForm(UserCreationForm): class Meta: model = MyUser fields = ('first_name', 'last_name', 'email', 'phone_number') class CustomAuthenticationForm(AuthenticationForm): phone_number = PhoneNumberField(label='Phone number') password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = MyUser fields = ('phone_number', 'password') Views.py from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from .forms import CustomUserCreationForm, CustomAuthenticationForm from .models import * def login_view(request): if request.method == 'POST': form = CustomAuthenticationForm(request, request.POST) if form.is_valid(): phone_number = form.cleaned_data['phone_number'] password = form.cleaned_data['password'] user = authenticate(request, phone_number=phone_number, password=password) if user is not None: login(request, user) return redirect('home') else: form.add_error(None, 'Invalid phone number or password') else: form = CustomAuthenticationForm() return render(request, 'core/login.html', {'form': form}) def logout_view(request): logout(request) return redirect('login') def register(request): if … -
How to check the given mobile number have whatsapp or not'?"
Initially, we want to read an Excel file, and then check all the rows to see if they have WhatsApp accounts. If a row has a WhatsApp account, we will add a field named 'valid' and set its value to 'true' to indicate validity. If the row does not have a WhatsApp account, we will set the value of the 'valid' field to 'false'. I tried for a API to check the mobile number -
I have made a real-time chat application and the front is implmented in react .i need to show the updated data when i manually add data into database
I have implemented a realtime chat application using django and react. When i send message it stores in db and displays on the frontend but when i mually add data into database it doesnot show untill i resfresh the pagei have tried websockets but dont know how to handle it. Here is my code Consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = "chat_%s" % self.room_name print("group name",self.room_group_name ) # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] print("textttttttttttttttttttttttttttttt is ",message) # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "chat_message", "message": message} ) # Receive message from room group def chat_message(self, event): message = event["message"] # Send message to WebSocket self.send(text_data=json.dumps({"message": message})) async def notify_response(self, event): print("event is",event["content"]) await self.send_json(event["content"]) In signals.py i am sending a response on post request to again call the websockets so that i could get data signals.py def report_communication_to_frontend(instance): if instance.id: log.info(f"Signal Triggered Successfully {instance}") try: channel_layer = get_channel_layer() content = serializers.serialize("json", [instance]) content = json.loads(content) content = … -
Django auth error on azure sql server, can't find object (table)
I'm currently building a custom api auth path on django rest framework, the application is connected to azure sql-server. the connexion to the database works perfectly, the table and migrations have been applied to the database, the necessary table have been filled with the necessary column and data, Django Admin tables such as auth_user, auth_user_groups, auth_group, auth_permission etc... A python3 startapp users was launched to customize my login class. users/models.py : from django.conf import settings from django.dispatch import receiver from django.db.models.signals import post_save from rest_framework.authtoken.models import Token from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): def __str__(self): return self.username @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) The user model is serialized users/serializers.py : from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','username','first_name','last_name','email') users/views.py : from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response from .models import User from .serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [] class UserLogIn(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data = request.data, context = {'request':request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token = Token.objects.get(user=user) return … -
error when importing Django module in visual studio
I am un able to solve this error as I am trying to run it on a django server it keeps throwing these errors -
How to restrcit users to their Site in Django?
I'm getting to know the Sites framework in Django. One thing I cannot find in the documentation is how to restrict users to "their" sites. Lets say I have example.com and sexyblog.com. Both sites run of the same code base and share the same db using Sites. How to make sure that the sexyblog-users can't log in to example.com? Thank you for your help. -
Django/Wagtail SnippetChooser template
1.How i can change/override SnippetChooser template ? 2.How i can add custom filters,queryset manipulations ? I can't find any info about this in documentation of wagtail -
How to group filtering elements into categories in Django?
I need to implement dynamic product filtering. I'm facing an issue of how to group filtering options by categories. For example, I have 3 filtering options - 8GB, 16GB, and 32GB. I need to group these values into the RAM category. model class CategoryCharacteristic(models.Model): category = models.ForeignKey("mainapp.Category", verbose_name='category', on_delete=models.CASCADE) feature_filter_name = models.CharField(verbose_name='name_of_filter', max_length=50) unit = models.CharField(max_length=50, verbose_name='unit_of_measurement', null=True, blank=True) class Meta: unique_together = ('category', 'feature_filter_name') ordering = ('id',) def __str__(self): return f"{self.category.title}-{self.feature_filter_name}-{self.unit}" class ProductCharacteristic(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='characteristics') feature = models.ForeignKey(CategoryCharacteristic,verbose_name='name_of_filter', on_delete=models.CASCADE) value = models.CharField(max_length=100) def __str__(self): return f'{self.feature.feature_filter_name} {self.value}' forms class ProductFilterForm(forms.Form): min_price = forms.DecimalField(required=False) max_price = forms.DecimalField(required=False) characteristics = forms.ModelMultipleChoiceField( queryset=ProductCharacteristic.objects.all(), widget=forms.CheckboxSelectMultiple, required=False ) def filter_queryset(self, queryset): min_price = self.cleaned_data.get('min_price') max_price = self.cleaned_data.get('max_price') characteristics = self.cleaned_data.get('characteristics') if min_price: queryset = queryset.filter(price__gte=min_price) if max_price: queryset = queryset.filter(price__lte=max_price) if characteristics: characteristic_query = Q() for characteristic in characteristics: characteristic_query |= Q(characteristics=characteristic) queryset = queryset.filter(characteristic_query) return queryset view class ProductListView(ListView): model = Product template_name = 'mainapp/product_list.html' def get_queryset(self): self.category = get_object_or_404(Category, slug=self.kwargs['category_slug']) queryset = super().get_queryset().filter(category=self.category) filter_form = ProductFilterForm(self.request.GET) if filter_form.is_valid(): queryset = filter_form.filter_queryset(queryset) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter_form'] = ProductFilterForm(self.request.GET) context['product'] = self.get_queryset() return context In the end, I want to get something like this. enter image … -
How to remove users from a copy of a database SQLite?
Now I am hosting my django project on github. My friend wants to move this project to his computer. I want him not to waste time populating the database, but to install a copy of mine. I do like this: python manage.py dumpdata > datadump.json Does this json store usernames and passwords? If yes, how to remove them? I want my friend to create his own superuser on his computer, and take only test data from the SQLite database copy. -
Integrating Jupyter Notebook to Django, Vue and React
I have created my recommendation algorithm with jupyter notebook and I have the dataset both locally. I just need help on how I can integrate the jupyter notebook to Django and Vue, React for both backend and frontend to create a recommendation web app? I have no resources for it since everything I searched are using Flask instead. -
problem in initialising keyczar in import errors No module named 'errors'
I am working with django python 3.10 and I installed encrypted_fields succsesfully which is depends on keyczar its already installed but it shows error in import statement ModuleNotFoundError: No module named 'errors' I tryied to install python3-keyczar but the problem still the same -
config file that shared between the frontend and backend
i need to write a config file to share with the frontend developer for common things like parameters name in requests. for example in my view file, i have something like this: class View(ApiView): def get(self,request): username = request.GET.get('phone') i want to use a config file instead of hard coding phone. and i want frontend(React) developer use this config too.(when they sending phone) in other words, i want to extract the parameters name from a config file in the frontend and backend. in other words, i want to extract the parameters name from a config file in the frontend and backend. -
django: NoReverseMatch at /
When i'm trying to get into main dashboard it shows me this error: NoReverseMatch at / Reverse for 'customer' not found. 'customer' is not a valid view function or pattern name. customer was a class copied from previous project main.html </head> <body> {% include 'zatrudnienie/navbar.html' %} {% block content %} {% endblock %} <hr> dashboard.html div class="row"> <div class="col-md-5"> <h5> ZAKŁAD PRACY: <!--{{total_customers}}--></h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="{% url 'create_zatrudnienie' %}">Create Zatrudnienie</a> <table class="table table-sm"> <tr> <th></th> <th>Zatrudnienie</th> <th>Orders</th> </tr> <!-- {{% for zatrudniony in zatrudnienie %} <tr> <td><a href="{% url 'customer' customer.id %}" class="btn btn-sm btn-info">View</a></td> --> <!-- <td>{{zatrudniony.nazwisko}}</td> <td>{{zatrudniony.stanowisko_pracy}}</td> </tr> {% endfor %} --> </table> </div> </div> models.py class Zatrudnienie(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) stanowisko_pracy = models.ForeignKey(StanowiskoPracy, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) imie = models.CharField(max_length=200, null=True) nazwisko = models.CharField(max_length=200, null=True) nrpaszportu = models.CharField(max_length=200, null=True) nrtelefonu = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) uwagi = models.CharField(max_length=200, null=True) adres1 = models.CharField(max_length=200, null=True) adres2 = models.CharField(max_length=200, null=True) def __str__(self): return self.stanowisko_pracy.name views.py def home(request): zatrudnienie = Zatrudnienie.objects.all() context = {'zatrudnienie': zatrudnienie,} return render(request, 'zatrudnienie/dashboard.html', context) Urls.py path('', views.home, name="home"), path('create_zatrudnienie/', … -
drf-spectacular how to have sub tags
By using the extend_schema I can create tags for each view @extend_schema(tags=['mytag']) def list(self, request): ... But is this possible to have one tag under another tag? -
PDF creation django base on a form but values of fields' db not shown
I have a problem with a creation of a pdf file. I'm using Django and python to create this project where once a form is filled out you can submit and the data will be saved in db and a view manage the part of the creation of the pdf file taking a template in html where here I can use fields to take the data that I wanto to show (I don't know how it s called I'll make an example: {{ name }}) but the fields don't show their values, it seems like it can't reach them. when creating the pdf, only there cause when I test it in local where I can reach the url where I can find my template I can see all of the values. Here is the code in my "views.py": def form_view(request): try: if request.method == 'POST': print('POST') form = PreventivoClienteForm(request.POST) if form.is_valid(): form.save() # genera file pdf da template HTML template = get_template('template_mail_pdf.html') html = template.render({'form': form.cleaned_data}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="preventivo.pdf"' # crea file pdf pisa_status = pisa.CreatePDF(html, dest=response) text_html = 'Buongiorno, <br><br> in allegato il documento in oggetto. <br> Cordialmente, <br> Roberta <br>' # verifica se la … -
'EntryPoints' object has no attribute 'get' during running pre-commit
I am getting an error from importlib_metadata AttributeError: 'EntryPoints' object has no attribute 'get' during pre-commit install even though I have already installed importlib_metadata==4.13.0 as suggested by below StackOverflow answer. What I am doing wrong here? This is my pre-commit config yaml file that I am using - exclude: 'settings.py' fail_fast: true repos: - repo: https://github.com/pre-commit/pre-commit-hooks.git rev: v4.0.1 hooks: - id: trailing-whitespace - id: check-yaml - id: check-json - id: check-docstring-first - id: requirements-txt-fixer - id: debug-statements - id: check-toml - id: pretty-format-json args: [--autofix] - id: no-commit-to-branch args: [--branch, develop, --branch, master] - repo: https://github.com/pycqa/isort rev: 5.11.5 hooks: - id: isort name: isort exclude: ^site-pacakges/ - repo: https://github.com/asottile/pyupgrade rev: v2.26.0 hooks: - id: pyupgrade exclude: ^site-pacakges/ args: ["--py37-plus"] - repo: https://github.com/psf/black rev: 23.1.0 hooks: - id: black exclude: ^site-pacakges/ language_version: python3.7 - repo: https://github.com/PyCQA/flake8 rev: 3.9.2 hooks: - id: flake8 additional_dependencies: [flake8-typing-imports==1.10.0] exclude: ^site-pacakges/ - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.910 hooks: - id: mypy name: Mypy typing checks args: ["--config-file=pyproject.toml"] exclude: ^site-pacakges/ - repo: local hooks: - id: tests name: run tests entry: pytest pass_filenames: false language: system Possible duplicate - 'EntryPoints' object has no attribute 'get' -
How to salve this error SMTPAuthenticationError at /auth/users/
I am trying to send email from backend to other but I face to this error (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor f25-20020a05651c03d900b00295a5aa9d05sm1136834ljp.120 - gsmtp')