Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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"}) … -
how to get price range with django?
i have price model class Product(models.Model): price = models.IntegerField membership_discount = models.DecimalField if i get price parameter, (ex. min_price = 100000, max_price = 500000) I want to get the products multiplied by the price fields and membership_discount fields. not this Product.objects.filter(price__range = (min_price, max_price)) i want Product.objects.filter(price * (1+membership_discount)__range = (min_price, max_price)) -
How to combine two different models on the basis of user and send a single response- Django Rest Framework
I have two different models in my project. The StudentDetail model has an one-to-one connection with the student-user and the EnrollmentList has a foreign key connection with the student user. I want to combine information from both the models for that specific student-user and send them as as a single response rather than sending different responses. Below are the models and their serializers StudentDetail/models.py class StudentDetail(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True) StudentDetailSerializer class StudentDetailSerializer(serializers.ModelSerializer): class Meta: model = StudentDetail fields = "__all__" Enrollment/models.py class EnrollmentList(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) student = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='student') EnrollSerializer class AllReqs(serializers.ModelSerializer): class Meta: model = EnrollmentList fields = ['id','student_name', 'student_parent_name', 'standard', 'applying_for_standard', "board", 'home_tuition', 'address'] Now suppose a request is made, I want to combine the information from the StudentDetail and EnrollmentList for that specific student user to get a serialized data which may look like below example and send this as a single response { "student_name": name, #from StudentDetail "home_tuition": home_tuition #from EnrollmentList } Please suggest to me the correct way to do it -
Delivery management in Python
I want to develop an open source delivery management, python web-based (Django) software to have multi-point pick up and multi-point drop. Is this an already developed opensource free project? If not, how do I start? -
Django django.db.utils.IntegrityError
We've a table with thousands of rows. Now we are in need to make 1 existing field to be Foreign Key from another table. Table 'list' got all the names and their details. Table 'State' is a new table included later and used to link it to the existing 'List' table. Model is as below, class List(models.Model): Lid = models.AutoField(primary_key=True) Name = models.CharField(max_length=100) addr1 = models.CharField(max_length=100) addr2 = models.CharField(max_length=100) City = models.CharField(max_length=40) State = models.ForeignKey(State,blank=True, on_delete=models.DO_NOTHING, default=None,to_field="state",db_column="State") #,to_field="state",db_column="State" Below is the error appears when tried to migrate, IntegrityError( django.db.utils.IntegrityError: The row in table 'list' with primary key '1' has an invalid foreign key: list.State contains a value '' that does not have a corresponding value in State.state. How to fix this issue? I did add those 'blank=True' and on_delete=models.DO_NOTHING after searching for a solution in google, still no luck. -
Is there any way to perform operation on django model on read
I am using a model something like this class MyModel(models.Model): text=models.CharField(max_length=200) viewed=models.BooleanField(default=False,editable=False) I want to set viewed=True when user gets the text. I tried to do it in views.py. But the problem is I need to write the same logic twice for admin site. Is there any way I can perform this in model. Thank you. -
Django and waypoints Infinite scroll not working
I have tried all the answers on stack and the infinite scroll is still not working. My home.html is still displaying the pagination. I suspect the problem is with jquery or the js files or with how the static file is loaded? Here is my home.html: {% block content %} {% load static %} <div class="infinite-container"> {% for post in posts %} <div class="infinite-item"> <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> </div> {% endfor %} </div> <div class="d-flex d-none position-fixed" style="top:35vh;left:46vw"> <button class="btn btn-primary loading"> <span class="spinner-border spinner-border-sm"></span> Please wait... </button> </div> <!--pagination logic --> <div class="col-12"> {% if page_obj.has_next %} <a class="infinite-more-link" href="?page={{ page_obj.next_page_number }}">next</a> {% endif %} </div> <script src="/static/js/jquery.waypoints.min.js"></script> <script src="/static/js/infinite.min.js"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], offset: 'bottom-in-view', onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function () { $('.loading').hide(); } }); </script> {% endblock content %} In my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [Path(BASE_DIR, 'static'),] The directory of my js files. I have added the following … -
Django display each categories url on base.html
I am a beginner in Django and create video streaming apps, the functions are basically to add videos and display those on different pages by categories. I am struggling to obtain URL for each category to display limited videos on each page. I could display categories and the link in one page by using for loop. However, I want to have those URLs on the Nav bar on base.html. videos/models.py from tabnanny import verbose from unicodedata import category import uuid from django.contrib.auth import get_user_model from django.db import models from django.conf import settings class VideoCategory(models.Model): name = models.CharField(choices=settings.CATEGORIES, max_length=45) def __str__(self): return self.name class Meta: verbose_name = 'カテゴリー' verbose_name_plural = 'カテゴリー' # Create your models here. class VideoContent(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True, ) title = models.CharField('タイトル', max_length=50) comment = models.CharField('内容',max_length=500) url = models.URLField('URL', max_length=200) published_date = models.DateTimeField('投稿日', auto_now_add=True) category = models.ForeignKey( VideoCategory, verbose_name = 'カテゴリー', on_delete=models.PROTECT, null=True, blank=True ) def __str__(self): return self.title class Meta: verbose_name = '動画投稿' verbose_name_plural = '動画投稿' video/views.py from django.contrib.auth.mixins import LoginRequiredMixin from unicodedata import category from django.shortcuts import render, get_object_or_404 from .models import VideoCategory, VideoContent from django.urls import reverse_lazy, reverse from django.shortcuts import render from django.views.generic import ( ListView, CreateView, UpdateView, DeleteView, ) … -
Define an aggregated check constraint using Django ORM
Think of two models like below: class Storage(Model): capacity = IntegerField() ... class FillStorage(Model): storage = ForeignKey(Storage, ...) amount = IntegerField() ... I need to have a check constraint on FillStorage model, preventing Sum of amounts of a single storage exceed its capacity; or be less than 0. What is the best solution? -
python django project hosting error on pythonanywhere.com
2022-07-03 04:54:11,060: Error running WSGI application 2022-07-03 04:54:11,078: django.core.exceptions.ImproperlyConfigured: 'user.apps.AppConfig' must supply a name attribute. 2022-07-03 04:54:11,078: File "/var/www/atmadevrt99_pythonanywhere_com_wsgi.py", line 16, in 2022-07-03 04:54:11,078: application = get_wsgi_application() 2022-07-03 04:54:11,078: 2022-07-03 04:54:11,078: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2022-07-03 04:54:11,079: django.setup(set_prefix=False) 2022-07-03 04:54:11,079: 2022-07-03 04:54:11,079: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/init.py", line 24, in setup 2022-07-03 04:54:11,079: apps.populate(settings.INSTALLED_APPS) 2022-07-03 04:54:11,079: 2022-07-03 04:54:11,079: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate 2022-07-03 04:54:11,080: app_config = AppConfig.create(entry) 2022-07-03 04:54:11,080: 2022-07-03 04:54:11,080: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/config.py", line 239, in create 2022-07-03 04:54:11,080: "'%s' must supply a name attribute." % entry 2022-07-03 04:54:11,080: *************************************************** 2022-07-03 04:54:11,081: If you're seeing an import error and don't know why, 2022-07-03 04:54:11,081: we have a dedicated help page to help you debug: 2022-07-03 04:54:11,081: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2022-07-03 04:54:11,081: *************************************************** 2022-07-03 04:54:13,244: Error running WSGI application 2022-07-03 04:54:13,244: django.core.exceptions.ImproperlyConfigured: 'user.apps.AppConfig' must supply a name attribute. 2022-07-03 04:54:13,244: File "/var/www/atmadevrt99_pythonanywhere_com_wsgi.py", line 16, in 2022-07-03 04:54:13,245: application = get_wsgi_application() 2022-07-03 04:54:13,245: 2022-07-03 04:54:13,245: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2022-07-03 04:54:13,245: django.setup(set_prefix=False) 2022-07-03 04:54:13,245: 2022-07-03 04:54:13,245: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/init.py", line 24, in setup 2022-07-03 04:54:13,245: apps.populate(settings.INSTALLED_APPS) 2022-07-03 04:54:13,245: 2022-07-03 04:54:13,245: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate 2022-07-03 04:54:13,245: app_config = AppConfig.create(entry) 2022-07-03 04:54:13,246: 2022-07-03 04:54:13,246: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/config.py", line 239, in create 2022-07-03 … -
How to get only ID on URL bar in selenium python
I have code like this: if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): text = form['look'].value() chrome_options = Options() chrome_options.add_experimental_option( "excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option( 'useAutomationExtension', False) chrome_options.add_experimental_option("prefs", { "download.prompt_for_download": False, "safebrowsing.enabled": True }) driver = webdriver.Chrome( ChromeDriverManager().install(), options=chrome_options) driver.maximize_window() driver.get(text) ... Then I get a URL like this: https://lovepik.com/image-610179440/cartoon-mothers-day-vector-material.html But I want the returned result to only get the ID of 610179440, what should I do? -
Why AuthenticationForm() in Django is not being valid?
So I've been trying to create a function in Django for users to log into their accounts. But it is only working for super users. When I try to log in from other accounts, it keeps resetting the password and gives error message 'Please enter a correct username and password'. However, both username and password are correct. Data from request.POST is coming as a QuerySet (keys-'csrfmiddlewaretoken','username','password'). When I put request.POST into AuthenticationForm(), it is not going through 'if form.is_valid():' part. What should I do to make this work? Please, can someone help me? Thanks, in advance. Here is the code: form=AuthenticationForm() if request.method=="POST": form=AuthenticationForm(request, data=request.POST) if form.is_valid(): username=form.cleaned_data.get('username') password=form.cleaned_data.get('password') user=authenticate(username=username,password=password) if user is not None: login(request,user) messages.info(request,'You have successfully logged in!') return redirect('news') else: messages.error(request,'Invalid data!') else: messages.error(request,'Invalid data!') return render(request,'post/login.html',{'form':form})``` -
Why django drf_yasg generate more unecessary APIs documentation than expecected?
I create Swagger APIs of a GET request, but drf_yasg generates a POST and a GET request. Here is my settings.py INSTALLED_APPS = [ 'django.contrib....', ... 'drf_yasg', 'business' ] Here is my APIs #TODO: Get all #URL: ('/CartItem/get-all', methods=['GET']) class GetAll(generics.CreateAPIView): serializer_class = CartItemFilter @Logging def get(self, request): request_data = dict(zip(request.GET.keys(), request.GET.values())) serializer = self.serializer_class(data=request_data) serializer.is_valid(raise_exception=True) request_data["deleted_at__isnull"] = True cartItem = CartItem.objects.filter(**request_data).values() return Response.NewResponse(status.HTTP_200_OK, "Success", list(cartItem)) Here is the app url file path('cart-item/get-all', CartItem.GetAll.as_view(), name="Get all cart item"), Here is the url file in the root folder schema_view = get_schema_view( openapi.Info( title="6********", default_version='1.0', description="API *******" ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('documentation', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('', include('business.urls')), ] I dont see anythign wrong with my setup, but when I turn on my swagger I see this The cart-item/get-all path has an extra POST request. Making my swagger becomes very messy since there are many unnecessary APIs