Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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') -
Why pytest (pytest-django) doesn't have access to .env variables through decouple which regular django files access as normal?
I have a django project and I'm setting up my testing environment with pytest and pytest-django. Previously, I have set up my environment variables like DB_HOST using decouple module. These variables work fine when they are used by regular django Python files. However, when I run pytest on tests which use the same files, these variables are not found. decouple.UndefinedValueError: DB_HOST not found. Declare it as envvar or define a default value. My pytest.ini file: [pytest] DJANGO_SETTINGS_MODULE = bapi_django.settings The error suggests to declare these variables, but it seems anti-DRY to me. Is there anyway I can use my django project level env variables or do I have to redefine them from scratch? -
How should I give a id to the button which displays each button in a for loop
I'm creating a quiz application in Python Django where in the template I'm iterating through a list of questions and then iteration through a list of answers for the current question and displaying those. I have a button for each answer. When I click a answer button an ajax call is triggered which calls my view to check if the answer is correct and returns the response. As I'm iterating through the answers for-loop and displaying a button for each answer of a question how should I make the clicked answer button red or green depending on the answer I got from my view response telling me if it is right or wrong? I'm confused how to determine unique id for each button and then change the color of that button. Below is the code <div class="row"> {% for question in questions %} <div class="col-md-4" > <div class="card mb-2" id="question_counter" value="{{forloop.counter}}"> <div class="card-body" > <p>{{forloop.counter}}{{"."}}{{ question.question|safe }}</p> <br> <div class="card-body" > {% for answer in question.answers %} <li><button type="button" class="btn btn-primary display: inline-block width: auto;" name="answer" id="submit" value="{{answer}}">{{ answer|safe }}</button></li> </br> {% endfor %} </div> </p> </div> </div> </div> {% endfor %} Also I have attached a sample showing how … -
model doesn't display title Django
In the admin the content of my model doesn't show a title, now I now that I can make a field called title but then I need it to be an incrementing int, but if I do that Django tells me that that can't happen because it will get rid of the ID, is there anyway I can fix this? model: class ReviewRating(models.Model): album = models.ForeignKey(albums, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=100, blank=True) review = models.TextField(max_length=500, blank=True) rating = models.FloatField() ip = models.CharField(max_length=20, blank=True) status = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject how the admin looks if there is any information missing please let me know -
How to add value to django form template in html
I created a django form and use it in html in user profile page. {{profile_form.first_name}} how can I add form value for this column of the form I tried to add value from form widget but I need to add user data but I can only do it in html like user.first_name -
DJANGO, NGINX and WINDOWS SERVER
I have deployed a django application using nginx. These are the nginx configurations I configured. **c:/nginx/sites-available/project_nginx.conf & c:/nginx/sites-enabled/project_nginx.conf ** server { listen 80; server_name 192.168.xxx.xx; location /static { alias D:/project/apps/media; } location /media/ { alias D:/project/apps/media; } location / { proxy_pass http://localhost:8000; } } **c:/nginx/conf/nginx.conf ** events { worker_connections 1024; } http { include. mime.types; default_type application/octet-stream; include C:/nginx/conf/sites-enabled/project_nginx.conf ... I have successfully deployed it and it is running without any problem on the server but, NB: The server is a windows server the problem is that, I cannot access the software on other PCs which are on the same network. What is a possible solution to this problem? I need the application to be accessible with other PCs on the intranet. -
Using pandas in django, how to release memory?
In a django project that focuses on data analysis, I use pandas to transform the data to a required format. The process is nice and easy, but the project quickly starts using 1GB of RAM. I know that Python doesn't really free up memory in this case (https://stackoverflow.com/a/39377643/2115409) and that pandas might have an issue (https://github.com/pandas-dev/pandas/issues/2659). How do I use pandas in a django project without exploding memory? -
How to hook up two viewsets to a single django url
I hava a standard DRF viewset for a model which I hook up in my urls.py as such: router = routers.SimpleRouter() router.register("", ResourceViewSet, basename="resource") urlpatterns = [ path( "", include(router.urls), name="basic-resource-crud", ), ] Resource is the only model in the app so it is hooked up to the root. Additionally I would like to hook up the PATCH method on the root url to a bulk update view: router = routers.SimpleRouter() router.register("", ResourceViewSet, basename="notifications") urlpatterns = [ path( "", BulkResourceUpdateViewSet.as_view(), name="bulk-resource-update", ), path( "", include(router.urls), name="basic-resource-crud", ), ] The BulkResourceUpdateViewSet class only defines a patch method. However with the setup above only the first route in the urlpatterns array is taken into considereation by Django and the other is ignored. How can I achive the url structure I am looking for: GET / : ResourceViewSet PATCH / : BulkResourceUpdateViewSet.patch GET /<pk>/ : ResourceViewSet POST /<pk>/ : ResourceViewSet PATCH /<pk>/ : ResourceViewSet PUT /<pk>/ : ResourceViewSet