Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
not triggering the post_delete_signal when it's coming from a CASCADE delete
Hello I have two django models linked by a foreign key and it looks like this class Author(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, null=False, db_index=True) number_of_books=models.IntegerField() #other fields class Book(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE, related_name='books') name = models.CharField(max_length=255, null=False, db_index=True) #other fields The Book model has a post_delete_signal that triggers some computations for te author instance def book_post_delete(sender, instance, **kwargs): # Re save max exposure author = instance.author author.number_of_books = author.books.count() author.save() trigger_computation(author) My problem is that if I delete an author for example, then his books are also deleted because of the on_delete=models.CASCADE, the book_post_delete function is then called and the trigger_computation(author) is called, which takes a lot of time for me and is also useless because the author is being deleted. Is there a way to get around not triggering the computation when the instance that is being deleted is an author? -
Django Title Block Showing on Page Content
example of issue: https://imgur.com/a/dtZsdjr Code views.py def home_view(request, *args, **kwargs): context = { "title" : "PortfolioLog - Home", } return render(request, "base.html", context) base.html <html lang = "en"> <head> <meta charset="utf-8"> <title>{{title}}</title> <meta name="description" content="Home page"> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> <script type="text/javascript" src="{% static 'scripts.js' %}"></script> </head> </html> -
How to create group of users in django
I want to create group where members of the group can see the documents, announcements and also list of members of the group. How do I code that in django models? Do I create custom group? Users can be member of many groups, and group can have a lot of members. So, it should be a many-to-many relationship(?) Do I put users under group models or the other way around? And how do I store announcements and documents of the group? Do I keep it under group models too? Or put group under the announcements and documents model, like how category is put under the post models like this: class Category(models.Model): name = models.CharField(max_length=100) class Post(models.Model): category = models.ForeignKey( Category, on_delete=models.PROTECT, default=1) title = models.CharField(max_length=250) content = models.TextField() -
Redering a list of objects with date and drop down
I am on the path of learning django. My personal project aims to create a clickable date based on available dates for different destinations. I have some data that is directly scraped from scrapy in the following format: departureDate = [{'departureDate': '2022-07-29', 'id': 'The Bahamas'}, {'departureDate': '2022-11-11', 'id': 'The Bahamas'}, {'departureDate': '2022-11-18', 'id': 'The Bahamas'}, {'departureDate': '2022-12-02', 'id': 'The Bahamas'}, {'departureDate': '2023-01-13', 'id': 'The Baltic Sea'}, {'departureDate': '2023-02-03', 'id': 'The Baltic Sea'}, {'departureDate': '2023-02-17', 'id': 'The Baltic Sea'}, {'departureDate': '2023-03-03', 'id': 'The Baltic Sea'}, {'departureDate': '2023-03-24', 'id': 'The Baltic Sea'}, {'departureDate': '2023-04-07', 'id': 'The Western Mediterranean'}, {'departureDate': '2023-04-14', 'id': 'The Western Mediterranean'}, {'departureDate': '2023-04-28', 'id': 'The Western Mediterranean'}, {'departureDate': '2023-12-21', 'id': 'The Western Mediterranean'}, {'departureDate': '2023-12-28', 'id': 'The Western Mediterranean'}], I want to then be able to load this into my model: Here's my model.py: from django.db import models class Cruises(models.Model): departureDate = models.DateTimeField('Departure Date') id = models.CharField('Destination', max_length=200) Then my views: from django.shortcuts import render from .models import Cruises def basic(request): departure_list = Cruises.objects.values('departureDate', 'id') return render(request, cruise_control/basic.html, context={'departure_list':departure_list}) basic.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Cruises</title> </head> <body> <h1> Cruise Control </h1> {% for dep_l in departure_list %} <form action="/action_page.php"> <label for='destination'>Destination</label> <input type="text" list="destination" /> <datalist id="destination"> … -
TypeError: connect() argument 4 must be str, not WindowsPath
Problem in connecting mysql to django Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 53, in init self.build_graph() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 235, in cursor self.ensure_connection() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\MySQLdb_init.py", line 123, in Connect return Connection(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\MySQLdb\connections.py", line 185, in init super().init(*args, **kwargs2) TypeError: connect() argument 4 must be str, not WindowsPath DATABASES = { 'default': { … -
Unable to save my form field getting error again and again
I built a simple signup form that will take data as the user will click submit it and will save it in the database. But for some reason, I am able to validate it. I removed all the validations and added them again too. Not sure where I am missing? it is not saving and giving the error Error Processing Your Request. which is in the else block of the code Forms.py: class RegisterForm(UserCreationForm): email = forms.EmailField(max_length=100,help_text='Enter Email Address', required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email'})) first_name = forms.CharField(max_length=100,help_text='Enter First Name', required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'})) last_name = forms.CharField(max_length=100,help_text='Enter Last Name', required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'})) username = forms.CharField(max_length=100,help_text='Enter Username', required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'})) password = forms.CharField(max_length=200,help_text='Enter Password', required=True,widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})) password2 = forms.CharField(max_length=200,help_text='Enter your Password again', required=True,widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})) #check = forms.BooleanField(required = True) class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'password', 'password2' #, 'check' ] Views.py: def register(request): if request.method == 'GET': #when you request a form it is in a get request form = RegisterForm() context = {'form' : form} #this creates a object which you want to send to the front end return render(request, 'signup-login.html', context) # here we pushing that form … -
Django rest_framework, logout redirect doesnt work
I am trying to redirect to the home page after clicking on Logout urls.py urlpatterns = [ . . path("api-auth/", include("rest_framework.urls")), ] settigs.py . . LOGOUT_REDIRECT_URL = "/" ACCOUNT_LOGOUT_REDIRECT_URL = "/" The problem is it still redirect to /api-auth/logout/?next=/current-page. This will cause an error because this "current page" needs authentication (requires a login) unlike the home page which doesn't require a login I also tried path("api-auth/logout", RedirectView.as_view(url="/", permanent=True)) but this again didn't work(still redirected to the "current page"). How can I redirect to the home page? -
Telethon TelegramClient.sign_in deadlock
I'm trying to separate my account access logic with Telethon. Thus, first a user enters his phone number, password, and then, when he receives an SMS with a code, he enters it too, and I can work with TelegramClient. Here's my code inside a Django project (the code is incredibly awful since I'm writing it in haste and for myself): urls.py from django.urls import path from .views import main_page, verify urlpatterns = [ path("authenticate/", main_page), path("verification/", verify, name="verify") ] view.py from django.shortcuts import render, redirect from django.urls import reverse from telethon import TelegramClient global phone, password, hash_, client phone = None password = None hash_ = None client = TelegramClient( "Telegram Client", 0, "" ) async def main_page(request): global phone, password, client, hash_ if request.POST: phone = request.POST['phone'] password = request.POST['password'] print("Connecting to the client") await client.connect() print("Sending an SMS with the code") hash_ = await client.send_code_request(phone) return redirect(reverse("verify")) return render(request, "credentials.html") async def verify(request): global phone, password, client, hash_ if request.POST: print("Connecting to the client") await client.connect() print( "Data before signing in: " "phone {}, password {}".format(phone, password) ) # Here is a deadlock. client = await client.sign_in( phone, request.POST["code"], password=password, phone_code_hash=hash_.phone_code_hash ) print( "Check after signing in", await … -
Django. Updating the model instance
Let's say I have a model: class PurchaseOrder(models.Model): supplier = models.ForeignKey('Supplier', on_delete=models.DO_NOTHING) employee = models.ForeignKey('employees.Employee', on_delete=models.DO_NOTHING) total_price = models.FloatField(null=True, blank=True) creation_date = models.DateTimeField(auto_now_add=True) posted = models.BooleanField(default=False) required_shipment_date = models.DateField(null=True, blank=True) date_shipped = models.DateField(null=True, blank=True) date_of_receiving = models.DateField(null=True, blank=True) shipment_address = models.CharField(max_length=255) order_status = models.CharField(max_length=255, choices=OrderStatus.ORDER_STATUS_CHOICES, default='ACCEPTED') def __str__(self): return f"Purchase order {self.supplier} № {self.pk}" def get_absolute_url(self): return reverse('purchases:purchase-order-details', kwargs={'pk': self.pk}) def compute_total_price(self): total_price = PurchaseOrder.objects.annotate( value=models.Sum(models.F('purchaseorderitem__quantity') * models.F('purchaseorderitem__price_per_unit')) ) print("total price") self.total_price = total_price[0].value In my model I have a method "compute_total_price" which gets all order items and multiplies quantity and price for every item and then sum it. The issue is I don't know how to save value to my model's field "total_price". I thought accessing self will do that, but it doesn't. The method computes the value however field isn't updated. -
django.db.utils.IntegrityError: NOT NULL constraint failed: Eid_Post_name.massenger_name
i have this issue "django.db.utils.IntegrityError: NOT NULL constraint failed: Eid_Post_name.massenger_name " and these my codes views.py from .models import Name # Create your views here. def Home(request): name_input = request.POST.get('user_name') name_in_model = Name(massenger_name=name_input,) name_in_model.save() return render(request , 'index.html') and this models.py from datetime import datetime # Create your models here. class Name(models.Model): massenger_name = models.CharField(max_length=50) action_time = models.DateTimeField(default=datetime.now) def __str__(self): return self.massenger_name and this index.html <!DOCTYPE html> <html lang="en" dir="rtl"> <head> <meta charset="utf-8"> <title></title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" href="{% static 'CSS/style.css' %}"> </head> <body> <div id="form"> <form class="row" method="POST"> <div class=""> <input type="textarea" class="form-control" placeholder="أكتب أسمك (مثلا/أخوكم عبدالله العتيبي)" id="text_name" name="user_name"> </div> <div class="col-auto"> <button type="submit" class="btn btn-primary mb-3" id="button">حمل الصورة</button> </div> </form> </div> </body> </html> -
Best way to use "context" on Django templates for many variables / dictionaries
I want to send a lot of data to 1 Django template (to show it on 1 specific page). The data comes from 2 sources: At least 1 list, with many dictionaries inside (I can't change any of this, it comes from Google Ads API). Many variables (I can change them, for example, to turn them into dictionaries or tuples if necessary). The variables are very simple, something like "variable = other_variable / 100" (just 1 value, no need for a key), so I don't need the variables to be turned into a dictionary. But I've understood (maybe wrong) that the "context" from Django's render needs dictionaries. The variables' data comes from the list (I do some calculations using some of the list values), but maybe this is not relevant for my question. Right now I'm doing something like this in my views.py: campaign_data = [] CODE TO FILL THAT LIST WITH API DATA (MANY DICTIONARIES INSIDE) clicks = sum(data['campaign_clicks'] for data in campaign_data) sum_clicks = {"sum_clicks" : clicks} context = { 'campaign_data' : campaign_data, 'sum_clicks' : sum_clicks } return render(request, 'testing.html', context) And then on the Django template I use the data from views.py like this: {% for element … -
Wierd behaviour in django
I am using SQLite in my Django project, I am gathering the data into the database manually with python. everything worked fine in that phase, now when I am trying to reach them in the templates file, something weird is happening, Django keeps giving me a NoReverseMatch match (because I am having a link that is referring to a view for some calculations, this view needs a URL which I have in my template), the weird thing is, when I open my 127.0.0.1:8000/admin and opening the data I've gathered and saved them, Django won't give me an error! it seems I have to do something like migrating my new data manually to project too, its very confusing -
Confirmation email works in localhost but not with ngrok django
I have this code. When I use it in localhost it works but when I use it with ngrok it shows a 400 error. It is strange because if I reload the page twice the error dissapears and it loads the url but it shows: Activation link is invalid!. In views.py: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = CustomUser.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, CustomUser.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponseRedirect(reverse("index")) else: return HttpResponse('Activation link is invalid!') mail_subject = 'Activate your account.' message = render_to_string('twc/acc_active_email.html', { 'user': user, 'domain': request.get_host(), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please confirm your email address to complete the registration') In urls.py: path('activate/<uidb64>/<token>/', views.activate, name="activate"), Finally, acc_active_email: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} -
Multiple search with django foreign key (Related Field got invalid lookup: icontains)
I understand that you can't directly use icontains on a foreign key when searching but I haven't found a solution yet. Here is my search view in views.py (I have imported every model needed): def search(request): # if the user actually fills up the form if request.method == "POST": searched = request.POST['searched'] # author__icontains part is not working posts = Post.objects.filter(Q(title__icontains=searched) | Q(author__author__icontains=searched)) return render(request, 'blog/search.html', {'searched': searched, 'posts': posts}) else: return render(request, 'blog/search.html', {}) Here is my model in model.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Mainly, this is not working: posts = Post.objects.filter(Q(title__icontains=searched) | Q(author__author__icontains=searched)) The error is Related Field got invalid lookup: icontains -
unresponsive mutation on graphql
When I am injecting values on useMutation it gives me Error 400 140. The data types does match. In appointment_booking argument, I am passing the its ID as a reference on the other table. Here is my Schema class CreateVideoConsultation(graphene.Mutation): id = graphene.Int() client = graphene.String() veterinarian = graphene.String() appointment_booking = graphene.Int() class Arguments: client = graphene.String() veterinarian = graphene.String() appointment_booking = graphene.Int() def mutate(self, info, client, veterinarian, appointment_booking): client_username = Client.objects.get(username = client) veterinarian_username = Veterinarian.objects.get(username = veterinarian) appointment_booking_id = Appointment_Booking.objects.get(id = appointment_booking) video_consultation = Video_Consultation(client = client_username, veterinarian = veterinarian_username, appointment_booking = appointment_booking_id) video_consultation.save() return CreateVideoConsultation(id = video_consultation.id, client = client_username, veterinarian = veterinarian_username, appointment_booking = appointment_booking_id) class Mutation (graphene.ObjectType): create_video_consultation = CreateVideoConsultation.Field() schema = graphene.Schema(query = Query, mutation = Mutation) Here is my model class Video_Consultation(models.Model): client = models.ForeignKey('Client', on_delete = models.DO_NOTHING) veterinarian = models.ForeignKey('Veterinarian', on_delete = models.DO_NOTHING) appointment_booking = models.ForeignKey('Appointment_Booking', on_delete = models.DO_NOTHING) def __str__(self): return str(self.client) Here is my mutation in Graphiql mutation{ createVideoConsultation(client:"GGGG",veterinarian:"Peppermint",appointmentBooking:29){ id client veterinarian appointmentBooking } } { "errors": [ { "message": "int() argument must be a string, a bytes-like object or a real number, not 'Appointment_Booking'" } ], "data": { "createVideoConsultation": { "id": 7, "client": "GGGG", "veterinarian": "Peppermint", "appointmentBooking": null } … -
Custom links in django
Here's my initial code class Article(models.Model): article_author = models.CharField(max_length=12) article_name = models.CharField(max_length=60) article_body = models.TextField() article_date = models.DateTimeField(auto_now_add=True) article_tags = models.CharField(max_length=25, choices=tags_, null=True) article_link = make_link() Turns out it won't be added to the db, and I can't make migrations (prob. because it's not part of .models). (I want the link to be made automatically as the instance of article class is created, and without user) I can just make it a CharField and then replace whatever was there with the function, but that just seems like a sloppy solution, also it'll give a usless field to the default admin-panel. -
Docker web server scale for distributed cpu
version: '3.7' services: web: command: python manage.py runserver 0.0.0.0:8000 build: . volumes: - ./:/usr/src/web/ ports: - "80-83:8000" env_file: - config/.env depends_on: - db restart: always static-file-server: restart: always image: halverneus/static-file-server:latest environment: - SHOW_LISTING=false - DEBUG=false volumes: - ./static/:/web ports: - 3000-3003:8080 db: restart: always image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - config/.env volumes: postgres_data: name: docker_database external: true My docker yml file is above. I have a server so people can download images. But there will be so many request for downloading images.I want to scale my web server to 3 or more. I can add new ports for scale but there is no distribution on the CPUs. Still only one cpu value increases and it comes to 150%. The docker stats for web_server are as below. How can I share the load to other cpu's CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS 9238c8f86a2f server_web_1 137.75% 2.94GiB / 7.714GiB 38.32% 799kB / 193kB 94.3MB / 8.19kB 41 d24e07a1eb55 server_web_2 2.96% 128.8MiB / 7.714GiB 1.63% 115kB / 28.9kB 582kB / 0B 17 1e00778f5d71 server_web_3 2.95% 291.1MiB / 7.714GiB 3.68% 352MB / 7.93GB 34.8MB / 0B 17 -
'Recipe' object has no attribute 'tags'
I am creating a recipe API. Here I have created a nested serializer, i.e. TagSerializer and RecipeSerializer. I am getting a error at "recipe.tags.add(tag_obj)" at the end of for loop. It is giving error " 'Recipe' object has no attribute 'tags'" Serializer.py """ Serializers for recipe APIs """ from rest_framework import serializers from core.models import (Recipe,Tag) class TagSerializer(serializers.ModelSerializer): #moved TagSerializer above to created nested serializer """Serializer for tags.""" class Meta: model = Tag fields = ['id', 'name'] read_only_fields = ['id'] class RecipeSerializer(serializers.ModelSerializer): """Serializer for recipes.""" tags = TagSerializer(many=True, required=False) # to make tags not necessary while creating recipe class Meta: model = Recipe fields = ['id', 'title', 'time_minutes', 'price', 'link','tags'] read_only_fields = ['id'] def create(self, validated_data): #creating function because nested serializer only allows read-only cannot be modified,but we want to modify the data """Create a recipe.""" tags = validated_data.pop('tags', []) #removes tag from validated data recipe = Recipe.objects.create(**validated_data) #created recipe from validated data auth_user = self.context['request'].user #authorising user for tag in tags: tag_obj, created = Tag.objects.get_or_create( #if tag is their it gets or if not creates,helps in removing duplicates user=auth_user, **tag, ) recipe.tags.add(tag_obj) return recipe class RecipeDetailSerializer(RecipeSerializer): """Serializer for recipe detail view.""" class Meta(RecipeSerializer.Meta): #reusing recipe serializer fields fields = … -
Page not found (404) adding a Django page
So I am trying to link up a page on my blog. I have created the template, view and URL for the page but it keeps throwing a 404 error. Could someone please look over my code and help me figure out the issue? add_post.html: {% extends "base.html" %} {% block content %} <header> <div class="post-caption mt-4"> <div class="text-center-caption"> <h1 class="display-5 fw-bolder text-shadow">Add Your Post</h1> <p class="lead text-shadow fw-bold">Tell us about your favourite game</p> </div> </div> </header> {%endblock%} views.py: from django.shortcuts import render, get_object_or_404, reverse from django.views.generic import View, CreateView, ListView from django.http import HttpResponseRedirect from .models import Post from .forms import CommentForm class AddPost(CreateView): model = Post template_name = 'about.html' fields = '__all__' urls.py: from .views import AddPost, PostList, PostDetail, PostLike from django.urls import path urlpatterns = [ path('', PostList.as_view(), name='home'), path('<slug:slug>/', PostDetail.as_view(), name='post_detail'), path('like/<slug:slug>/', PostLike.as_view(), name='post_like'), path('add_post/', AddPost.as_view(), name='create_post'), ] -
Installed both Miniconda and Anaconda
After running the Conda info --envs command I can see that I have both mini- and anaconda installed. Is this a problem? if so how do I remove one? code: (base) ********-MacBook-Pro ~ % conda info --envs # conda environments: # /Users/****/miniconda3 base * /Users/****/opt/anaconda3 -
When i am trying to integrate django with react when i am run webpack got error like below
WARNING in DefinePlugin Conflicting values for 'process.env.NODE_ENV' 1 warning has detailed information that is not shown. Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it. webpack 5.73.0 compiled with 1 warning in 2053 ms -
how to add fix numbers of django channels we can add in every group?
class MySyncConsumer(SyncConsumer): def websocket_connect(self): async_to_sync( self.channel_layer.group_add)('programer',self.channel_name) self.send({ "type" : "websocket.accept" }) -
How to customize the appearance of the password fields of a Django custom registration form?
I want to change the appearance of the input fields in the registration form, but why is the decoration not being applied to the password fields? forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ['email', 'username', 'password1', 'password2'] widgets = { 'email': forms.EmailInput(attrs={ 'type': 'email', 'class': 'form-control', 'id': 'exampleInputEmail', }), 'username': forms.TextInput(attrs={ 'type': 'text', 'class': 'form-control', 'id': 'exampleInputUsername', }), 'password1': forms.PasswordInput(attrs={ 'type': 'password', 'class': 'form-control', 'id': 'exampleInputPassword1', }), 'password2': forms.PasswordInput(attrs={ 'type': 'password', 'class': 'form-control', 'id': 'exampleInputPassword2', }), } HTML <label for="exampleInputEmail" class="form-label">Email</label> {{ form.email }} <label for="exampleInputUsername" class="form-label">Username</label> {{ form.username }} <label for="exampleInputPassword1" class="form-label">Password</label> {{ form.password1 }} <label for="exampleInputPassword2" class="form-label">Confirm password</label> {{ form.password2 }} Result -
Django properly remove treebeard
I was using Django treebeard, which then i decided i no longer need it and just went a head reformed the class model that was using it and deleted my migrations and cash files, however my app keeps trying to use django treebeard and throw and error how i can tell my App to actually start fresh. P.S i dont care about the database inside, i just dont want to write the app all over again. This how it looked before : from django.db import models from vessels.models import Vessel from treebeard.mp_tree import MP_Node # Create your models here. class Component(MP_Node): name = models.CharField(max_length=255, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) parent = models.ForeignKey( 'self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') def __str__(self): return self.name this is how i want it to be : class Component(models.Model): name = models.CharField(max_length=255, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) parent = models.ForeignKey( 'self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') def __str__(self): return self.name … -
Strawberry Django specific Graphql queries other than pk not working
I am having issues making specific queries using the Strawberry library. Lets say I have two Django models: class Address(models.Model): name = models.CharField() class Person(models.Model): name = models.CharField() address = models.ForeignKey('Address', on_delete=models.CASCADE, blank=False, null=False) with my type.py file: @strawberry.django.type(models.Address) class Address: id: auto name:auto @strawberry.django.input(models.Address) class AddressInput: id: auto name:auto @strawberry.django.type(models.Person) class Person: id: auto name: auto address:'Address' @strawberry.django.input(models.Person) class Person: id: auto name: auto address:'AddressInput' and schema.py: @strawberry.type class Query: address: Address = strawberry.django.field() addresses: List[Address] = strawberry.django.field() person: Person = strawberry.django.field() persons: List[Person] = strawberry.django.field() schema = strawberry.Schema(query=Query) In the graphiql terminal if I wanted id for Person it works fine: #Query query MyQuery { person(pk: "1") { address { id name } id name } } #Return value { "data": { "person": { "address": { "id": "1", "name": "Compound" }, "id": "1", "name": "William" } } } But if I try searching by address id or person name it does not work. All of these query following do not work query MyQuery { person(name: "William") { address { id name } id name } } query MyQuery { person(data: {name: "William"}) { address { id name } id name } } query MyQuery { person(address: {id: "1"}) …