Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set lookup_field of GenericViewSet with JSONfield key?
How do I set the lookup_field with a key in JSONField model? The model: exchange = models.ForeignKey(StockExchange, on_delete=models.CASCADE, related_name='tickers') fundamentals = models.JSONField(null=True, blank=True) The viewset: class StockCardsV2ViewSet(BaseGetViewSet): search_fields = ('^fundamentals__General__Name', '^fundamentals__General__Code') filter_backends = (filters.SearchFilter,) queryset = Ticker.objects.all() serializer_class = StockCardsV2Serializer lookup_value_regex = '[0-9a-zA-Z_.]+' lookup_field = 'fundamentals__General__Code' The Serializer: class Meta: model = Ticker fields = ('id', 'url', 'name', 'ticker', 'logo_url', 'currency_symbol', 'sector', 'industry', 'esg_rating', 'weekly_prices', 'monthly_prices', 'yearly_prices', 'two_yearly_prices', 'ad', 'in_watchlist') lookup_field = 'fundamentals__General__Code' extra_kwargs = { 'url': {'lookup_field': 'fundamentals__General__Code'}, } There are no problems with search_fields but I get this error for the lookup_field. 'Ticker' object has no attribute 'fundamentals__General__Code' Example fundamentals: "fundamentals": { "General": { "CIK": null, "LEI": null, "Code": "SATX-WTA", "ISIN": null, "Name": "Satixfy Communications Ltd.", } }, -
AttributeError at /profile/1/ 'User' object has no attribute 'room_set
I created profile page and out of nowhere it just broke. Everything was working fine but then it just broke outta nowhere. I have no clue what's wrong Here is my code and traceback. Let me know if more detail and code is needed. views.py def userProfile(request, pk): user = User.objects.get(id=pk) rooms = user.room_set.all() room_messages = user.message_set.all() topics = Topic.objects.all() context = {'user': user, 'rooms': rooms, 'room_messages': room_messages, 'topics': topics} return render(request, 'authentication/profile.html', context) traceback Traceback (most recent call last): File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\issuetracker\users\views.py", line 59, in userProfile rooms = user.room_set.all() Exception Type: AttributeError at /profile/1/ Exception Value: 'User' object has no attribute 'room_set' -
DRF - Upload a valid image
Hope someone would be able to help me out here. I am trying to update an image on a table called MyCards, when updating this image the system should then look to see if this image contains certain word, if so then the field points would be increased by one. But, when trying to update the image I get the following error { "image": [ "Upload a valid image. The file you uploaded was either not an image or a corrupted image." ] } Not sure how to solve this issue, if anyone could help on it, would be great. please find here my model, viewset and serializer MODEL: class MyCards(models.Model): profile = models.ForeignKey(AppUserProfile, on_delete=models.CASCADE) card = models.ForeignKey(Cards, on_delete=models.CASCADE) points = models.IntegerField(default=0) image = models.ImageField(upload_to=f'media/app_user/', blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.card.business.business_name VIEWSET class MyCardsViewSet(ModelViewSet): serializer_class = UpdateMyCardsSerializer queryset = MyCards.objects.all() def update(self, request, pk=None, *args, **kwargs): super().update(request, *args, **kwargs) x = self.get_object() img = f"media/{x.image}" result = pytesseract.image_to_string(img) if "Petel Chang" in result: x.points += 1 return self.update(request, *args, **kwargs) SERIALIZER class UpdateMyCardsSerializer(serializers.ModelSerializer): class Meta: model = MyCards fields = ('profile', 'card', 'points', 'created', 'updated', 'image') -
DRF: Overwrite inculded default endpoints to custom views
So I am using dj-rest-auth with Simple-JWT. My urls.py is: urlpatterns = [ path('dj-rest-auth/', include('dj_rest_auth.urls')), ] But I want to update a specific endpoint of dj-rest-auth.urls to a custom view: path('dj-rest-auth/login/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair') Simply adding both the lines together ain't doing the job. dj-rest-auth/login/ gives the default view only. How shall I overwrite it? -
Django lookup by JSONField array value
Let's say I have MySQL database records with this structure { "id": 44207, "actors": [ { "id": "9c88bd9c-f41b-59fa-bfb6-427b1755ea64", "name": "APT41", "scope": "confirmed" }, { "id": "6f82bd9c-f31b-59fa-bf26-427b1355ea64", "name": "APT67", "scope": "confirmed" } ], }, { "id": 44208, "actors": [ { "id": "427b1355ea64-bfb6-59fa-bfb6-427b1755ea64", "name": "APT21", "scope": "confirmed" }, { "id": "9c88bd9c-f31b-59fa-bf26-427b1355ea64", "name": "APT22", "scope": "confirmed" } ], }, ... Any way I can filter all of the objects who's actors name contains '67', for example? Closest variant I have is that I got it working like that: queryset.filter(actors__contains=[{"name":"APT67"}]) But this query matches by exact actor.name value, while I want to to accept 'contains' operator. I also have it working by quering with strict array index, like this: queryset.filter(actors__0__name__icontains='67') But it only matches if first element in array matches my request. And I need that object shall be returned in any of his actors matches my query, so I was expecting something like queryset.filter(actors__name__icontains='67') to work, but it's not working :( So far I have to use models.Q and multiple ORs to support my needs, like this - search_query = models.Q(actors__0__name__icontains='67') | models.Q(actors__1__name__icontains='67') | models.Q(actors__2__name__icontains='67') | models.Q(actors__3__name__icontains='67') queryset.filter(search_query) but this looks horrible and supports only 4 elements lookup(or I have to include more … -
Project with django,docker,celery,redis giving error/mainprocess] cannot connect to amqp://guest:**@127.0.0.1:5672//: [errno 111] connection refused
I'm trying to create a Django project with celery and redis for the messaging service using docker-compose. I'm getting Cannot connect to amqp://guest:**@127.0.0.1:5672. I'm not using guest as a user anywhere or 127.0.0.1:5672 and amqp is for RabbitMQ but I'm not using RabbitMQ. So, I don't know if my docker-compose volumes are not set correctly for celery to get the settings, where is it getting amqp from, or is the broker miss configured. docker-compose.yml: version: '3' network networks: data: management: volumes: postgres-data: redis-data: services: nginx: image: nginx ports: - "7001:80" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro - ../static:/static command: [nginx-debug, '-g', 'daemon off;'] networks: - management depends_on: - web db: image: postgres:14 restart: always volumes: - postgres-data:/var/lib/postgresql/data/ - ../data:/docker-entrypoint-initdb.d # import SQL dump environment: - POSTGRES_DB=link_checker_db - POSTGRES_USER=link_checker - POSTGRES_PASSWORD=passw0rd networks: - data ports: - "5432:5432" web: image: link_checker_backend build: context: . dockerfile: Dockerfile environment: - DJANGO_LOG_LEVEL=ERROR - INITIAL_YAML=/code/initial.yaml volumes: - ../:/code - ../link_checker:/code/link_checker - ../link_checker_django/:/code/link_checker_django - ./settings.py:/code/link_checker_django/settings.py working_dir: /code command: > sh -c " python manage.py migrate --noinput && python manage.py collectstatic --no-input && python manage.py runserver 0.0.0.0:7000 " networks: - data - management depends_on: - db redis: image: redis volumes: - redis-data:/data networks: - data celery-default: image: link_checker_backend volumes: - ../:/code … -
DRF - Unable to log in with provided credentials
I tried to get a token from django rest framework. bigissue@vmi995554:/opt/ftusbrdp/sbin$ http POST http://172.18.0.1:7000/api-token-auth/ username='nicola' password="Password12345" HTTP/1.1 400 Bad Request Allow: POST, OPTIONS Content-Length: 68 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Tue, 29 Nov 2022 14:19:40 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.9.15 X-Content-Type-Options: nosniff X-Frame-Options: DENY { "non_field_errors": [ "Unable to log in with provided credentials." ] } I have create superuser and also a normal user from admin web gui. All users are active. What I'm missing? Here down is my configuration. I have import module app like rest_framework and rest_framework.authtoken, I set REST_FRAMEWORK variable for token use. Then I call views.obtain_auth_token methods to get string token. The settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appjud', 'rest_framework', 'rest_framework.authtoken' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ), } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbjud', 'USER': 'root', 'PASSWORD': 'Password19', 'HOST':'localhost', 'PORT':'3306', } } The router.py file from appjud.viewsets import userviewsets from rest_framework import routers router = routers.DefaultRouter() router.register('user', userviewsets, basename ='user_api') The serialiers.py file class userSerializers(serializers.ModelSerializer): class Meta: model = User fields = '__all__' The viewsets.py file from rest_framework import viewsets from .serializers import userSerializers from django.contrib.auth.models import User class userviewsets(viewsets.ModelViewSet): queryset … -
Django- Template not found
I can't seem to get my delete, edit and add review functionality working. The errors come as soon as I try to navigate to the urls I have set up. When I try and add a new review using my link on the reviews page I get the below message: TemplateDoesNotExist at /reviews/add I don't understand why because I have linked the url above to the template, which I have created. The issue I have with my edit/delete views is that the url it searches for when I click the button is just /edit/ or /delete/ rather than reviews/edit/int:pk or reviews/delete/int:pk as per my urls. I have pasted my code below, any help would be much appreciated! I have the feeling I am going to kick myself when I realise! reviews.html: {% extends "base.html" %} {% load static %} {% block content %} <div class="container-fluid home-container"> <div class="row align-items-center"> <div class="col-sm-12 text-center mt-4"> <h2><strong>Reviews</strong></h2> </div> </div> {% for review in reviews %} <hr class="hr-1"> <div class="row featurette"> <div class="col-sm-12"> <h2 class="featurette-heading">{{ review.title }}</h2> <p class="lead">{{ review.content }}</p> <div class="row justify-content-between mx-1"> <p>By: {{ review.user }}</p> <p>Created on: {{ review.created }}</p> <p>Last Updated: {{ review.updated }}</p> </div> <!-- Add user authentication … -
Getting Datefield after Today and Before another date not returning the expected object
I am writing an app in Django where I have created a PayPeriods model as such: class PayPeriods(models.Model): first_day = models.DateField(default=date.today) last_day = models.DateField(default=date.today) pay_day = models.DateField(default=date.today) I've created a small function that allows me to get the current PP through my app, def get_pp(): _pp = PayPeriods.objects.filter(first_day__gte=datetime.today())[0] return _pp but its not returning as expected. What am I missing? Current day today is 11/29/2022, so I am expecting to return Obj #4, as the code is written. PP Object #3: first_day = 11/13/22, last_day = 11/26/22 PP Ojbect #4: first_day = 11/17/22, last_day = 12/10/22 PP Ojbect #5: first_day = 12/11/22, last_day = 12/24/22 I have verified that my dates are formatted the same way, (stored data & datetime.today(), and my timezone settings are correct.). -
How to set a logic that only event attendant can give review regarding an event in drf?
i'm new in drf i'm managing event management system, i tried to count event attendees and only event attendees can review about event. i facing issue to in review model. i manage attendees in Event model with ManyToManyField. here my models , class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="event_user") attendees = models.ManyToManyField(User, blank=True, related_name='attendees_user') venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='venue_user') event_type = models.CharField(max_length=50, choices=event_type) event_name = models.CharField(max_length=25) start_time = models.DateTimeField(blank=False, null=True) end_time = models.DateTimeField(blank=False, null=True) def __str__(self): return f'{self.venue} - {self.event_name}' class Reviews(models.Model): reviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="reviewer_user") event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="event") review = models.TextField() class Meta: verbose_name_plural = "Reviews" def __str__(self): return f'{self.reviewer} -- {self.review} -- {self.event}' here my serializers class EventSerializer(serializers.ModelSerializer): images = serializers.ListField( child=serializers.FileField(allow_empty_file=True, use_url=True, ), required=False) class Meta: model = Event fields = ( 'id', 'user', 'attendees', 'venue', 'event_type', 'event_name', 'start_time', 'end_time', 'images') def create(self, validated_data): uploaded_data = validated_data.pop('images') attendees = validated_data.pop('attendees') instance = Event.objects.create(**validated_data) instance.attendees.set(attendees) instance.save() for pics in uploaded_data: EventImages.objects.create(event=instance, event_pics=pics) return instance def to_representation(self, instance): response = super(EventSerializer, self).to_representation(instance) response["venue_name"] = instance.venue.venue_name response["start_time"] = instance.start_time.strftime("%d/%m/%Y, %H:%M:%S") response["end_time"] = instance.end_time.strftime("%d/%m/%Y, %H:%M:%S") return response def validate(self, data): if data.get("start_time") > data.get("end_time"): raise serializers.ValidationError("'End time' must be after 'Start time'.") else: pass if Event.objects.filter( (Q(venue=data['venue']) & … -
How do I test views in Django Rest Framework that make calls to other apis/ google earth engine
A lot of views on my project makes http requests to other services, and one of the views makes a call to google earth engine service. How do I go about testing these components? Should I just let them make the calls and make my tests depend on an internet connection? Is there a design structure in which I can choose to mock the request data? -
Update is creating new entry rather than updating it
I have a model where users save their details. I am able to save user details through the template I have created. But whenever I edit the data to update it, a new entry is created in database models.py class User(AbstractUser): pass def __str__(self): return self.username class Detail(models.Model): """ This is the one for model.py """ username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default="") matricno = models.CharField(max_length=9, default="") email = models.EmailField(default="") first_name = models.CharField(max_length=200, default="") last_name = models.CharField(max_length=255, default="") class Meta: verbose_name_plural = "Detail" def __str__(self): return self.first_name+ " "+self.last_name views.py @login_required(login_url="signin") def details(request): form = Details() if request.method == "POST": form = Details(request.POST) if form.is_valid(): detail = form.save(commit=False) detail.username = request.user detail.save() return redirect(success, pk=detail.pk) else: form = Details(initial={"matricno":request.user.username}) return render(request, "details.html", {"form":form}) def success(request,pk): return render(request, "success.html", {"pk":pk}) def updatedetails(request, pk): detail = Detail.objects.get(id=pk) form = Details(instance=detail) if request.method == "POST": form = Details(request.POST, instance=detail) if form.is_valid(): form.save() return redirect(success, pk=detail.pk) return render(request, "details.html", {"form":form}) urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("details/", views.details, name="details"), path("success/<int:pk>/", views.success, name="success"), path("edit/<int:pk>/", views.updatedetails, name="updatedetails"), ] The template used for rendering out the form to input user details goes as follows <!DOCTYPE html> <html lang="en"> <head> … -
Get values of Enum fields from Django Queryset
I have a model with an enum column, e.g. from django_enum_choices.fields import EnumChoiceField class Service(Enum) MOBILE: "MOBILE" LAPTOP: "LAPTOP" class Device(models.Model): service = EnumChoiceField(Service) ... Is it possible to get get the query results with the enumerated column being the value of the enum? For example: If I do: query = Device.objects.values("service") print(query) I get: <QuerySet [{'service': <Service.MOBILE: 'MOBILE'>}, {'service': <Service.MOBILE: 'MOBILE'>}, {'service': <Service.LAPTOP: 'LAPTOP'>}]> I wish to get: <QuerySet [{'service': 'MOBILE'}, {'service': 'MOBILE'}, {'service': 'LAPTOP'}]> I get errors when I run: query = Device.objects.values("service__value") or query = Device.objects.values("service.value") I want to something like how we can get value of an enum field by saying mobile_service = Service.MOBILE # <Service.MOBILE: "MOBILE"> mobile_service_as_string = mobile_service.value # "MOBILE" The errors: django.core.exceptions.FieldError: Cannot resolve keyword 'value' into field. Join on 'service' not permitted. django.core.exceptions.FieldError: Cannot resolve keyword 'service.value' into field. Choices are: service, .. -
Django Selenium Parsing Data
How can return WebDriver=auth in function parameters? I have a task.py file in which, first, in the login function, I use Selenium to log in to my personal account, then the form_fill function receives the Url parameters in which the form is filled, and the WebDriver and returns the data and the driver. I'm trying in views.py to first call the login function for authorization and return the WebDriver to another form_fill function. task.py def login(url): driver = webdriver.Chrome(service=service,options=options) driver.maximize_window() driver.get(url) driver.find_element(By.ID,"login").send_keys(LOGIN) driver.find_element(By.ID,"password").send_keys(PASSWORD) driver.find_element(By.ID,'bind').click() return driver def form_fill(url_pars,driver,name_flat): driver.get(url_pars) driver.find_element(By.ID,"epd_field").click() codplat=driver.find_element(By.CLASS_NAME,"home_right").text driver.find_element(By.XPATH,'//span[contains(text(),"name_flat}")]'.format(name_flat)).click() driver.find_element(By.CLASS_NAME,"js-find-btn").click() driver.find_element(By.CLASS_NAME,"js-more-btn").click() driver.find_element(By.CLASS_NAME,"btn-close-pop").click() return [driver,codplat] views.py class AuthView(TemplateView): template_name="mos_sel/login.html" def get_context_data(self, **kwargs) : context=super().get_context_data(**kwargs) # login(URL_LOGIN) return WebDriver in auth auth=login(URL_LOGIN) return context views.py class PaymentListView(AuthView,ListView): template_name='mos_sel/parse_list.html' model=Flat context_object_name='fields' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['name_flat']=Flat.objects.get(pk=self.kwargs['pk']).name_flat # How get WebDriver in parameters call form_fill function forma_fill=form_fill(GET_USLUGA_URL,auth,context['name_flat'].upper()) return context login.html {% extends "base.html" %} {% block content %} <h3>Enter for authorization</h3> <a href="{% url 'AuthView' %}"><button type="button" class="btn btn-success">Enter</button></a> {% endblock content %} parse_list.html {% extends "base.html" %} {% block sidebar %} <h5>{{name_flat}}</h5> {% for field in fields %} {{field.cod_platelshika}} {{field.period_oplaty}} {{field.summa}} {% endfor %} {% endblock sidebar %} I want get WebDriver in function fill_form parameters -
Render multiple models with pk in a single view
I'm trying to pass lesson.price, and lesson.invoice_id from Lesson model and student.student_id from Student Model into the single view so that I can display them in a template. However, Lesson model has a field "student" which has a foreign key to User, not to Student model. You will see my code for view class is wrong since I have no clue how to get a proper student object with a primary which is used for lesson object. How could I get a proper student object with lesson_id primary key in view class? class User(AbstractUser): '''User model for authentication and lessons authoring.''' class Role(models.TextChoices): ADMIN="ADMIN",'Admin' STUDENT="STUDENT",'Student' TEACHER="TEACHER",'Teacher' id = models.AutoField(primary_key=True) username = models.CharField( max_length=30, unique=True, validators=[RegexValidator( regex=r'^@\w{3,}$', message='Username must consist of @ followed by at least three alphanumericals.' )] ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True, blank=False) gender = models.CharField(max_length=255) address = models.TextField(default='') baseRole = Role.ADMIN role = models.CharField(max_length=50, choices=Role.choices) created_at = models.DateTimeField(default=timezone.now, blank=True) updated_at = models.DateTimeField(default=timezone.now, blank=True) def save(self, *args, **kwargs): self.role = self.baseRole return super().save(*args, **kwargs) def __str__(self): return self.first_name+" "+self.last_name class Student(User): student_id = models.CharField(max_length=10, default=uuid.uuid4) baseRole = User.Role.STUDENT student = StudentManager() class Lesson(models.Model): lesson_id = models.AutoField(primary_key=True) lesson_name = models.CharField(max_length=255) student = models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='studying', unique=True) teacher … -
Is it possible to pass command line arguments to a decorator in Django?
I have a decorator that is supposed to use a parameter that's passed in from the commandline e.g @deco(name) def handle(self, *_args, **options): name = options["name"] def deco(name): // The name should come from commandline pass class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--name", type=str, required=True, ) @deco(//How can I pass the name here?) def handle(self, *_args, **options): name = options["name"] any suggestions on this? -
How to show a field seperately in drf
I have Reviews & Ratings serializer. I want to show the total count of reviews in response. The current implementation I am getting review count but it shows on all review response like below: [ { "review_count": 2, "user": "don sebastian", "rating": 3.9, "review": "Rating for pendant 1 by Don", "created_at": "2022-11-27", "updated_at": "2022-11-27" }, { "review_count": 2, "user": "Jackson Patrick Gomez", "rating": 4.5, "review": "cool review Pendant 1", "created_at": "2022-11-27", "updated_at": "2022-11-29" } ] What I want to get is like this review_count seperatley [ "review_count": 2, { "user": "don sebastian", "rating": 3.9, "review": "Rating for pendant 1 by Don", "created_at": "2022-11-27", "updated_at": "2022-11-27" }, { "user": "Jackson Patrick Gomez", "rating": 4.5, "review": "cool review Pendant 1", "created_at": "2022-11-27", "updated_at": "2022-11-29" } ] #Serializer.py class ReviewSerializer(ModelSerializer): user = SerializerMethodField() review_count = SerializerMethodField() class Meta: model = ReviewRatings fields = ["review_count", "user", "rating", "review", "created_at", "updated_at"] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" def get_review_count(self, obj): -
Web page I am scraping requires credit card details to work. Any idea how I can keep my credit card info secure?
Hello I have a Django/postgres backend service that starts jobs with my webscraper service running puppeteer/express. Additionally, all these services are running on Dokku. The webscraper goes and purchase products from websites and thus need to enter my credit card number each time. Kind of scared about storing my credit card number some where and what service to give it to. I have never done this before. Should have I just hash the credit card number and store it in an environment variable or is there any better ideas? -
Software for creating interactive forms [closed]
my problem is in relation with structuring text. i am searching for a opportunity that helps me structuring text. It should be able to create a fillable form and generate an PFD out of this. Hope you have any idea... -
Problem of signature with webauthn on django with djoser
I'm working at the moment on an implementation of webauthn on a project. The main point is to give the possibility to user to use FaceId or fingerprint scan on their mobile on the website. I tried the djoser version of webauthn but I wanted to give the possibility to user that already have an account so I took the implementation of webauthn of djoser and I updated it to make it working with already created account. I can ask for the signup request of a webauthn token and create the webauthn token with the front (Angular) where I use @simplewebauthn/browser ("@simplewebauthn/browser": "^6.3.0-alpha.1") . Everything is working fine there. I use the latest version of djoser by pulling git and the version of webauthn is 0.4.7 linked to djoser. djoser @git+https://github.com/sunscrapers/djoser.git@abdf622f95dfa2c6278c4bd6d50dfe69559d90c0 webauthn==0.4.7 But when I send back to the backend the result of the registration, I have an error: Authentication rejected. Error: Invalid signature received.. Here's the SignUpView: permission_classes = (AllowAny,) def post(self, request, ukey): co = get_object_or_404(CredentialOptions, ukey=ukey) webauthn_registration_response = WebAuthnRegistrationResponse( rp_id=settings.DJOSER["WEBAUTHN"]["RP_ID"], origin=settings.DJOSER["WEBAUTHN"]["ORIGIN"], registration_response=request.data, challenge=co.challenge, none_attestation_permitted=True, ) try: webauthn_credential = webauthn_registration_response.verify() except RegistrationRejectedException as e: return Response( {api_settings.NON_FIELD_ERRORS_KEY: format(e)}, status=status.HTTP_400_BAD_REQUEST, ) user = User.objects.get(username=request.data["username"]) user_serializer = CustomUserSerializer(user) co.challenge = … -
Django json response stay in the same page
I'm making a like button for a post in django. What I need is that when the like button is clicked, the function is executed, but I need the page not to be reloaded (To later use javascript). To do that I return a jsonresponse() instead of a return render. But the real problem is that it redirects me to the page that I show in the photo. The page is not reloaded. as I want it. but I don't want it to show me the blank page with the jsonresponse data (like this photo).I want to stay in the same page without reload. Thanks in advance! My view function: def liking (request, pk): posts = get_object_or_404(Post, id = pk) if request.user in posts.likes.all(): posts.likes.remove(request.user) else: posts.likes.add(request.user.id) likes_count = posts.likes.all().count() print(f'likes_count = {likes_count}') data= { 'likes_count': likes_count, } #return redirect ('index')# This is commented return JsonResponse(data, safe=False, status=200 ) -
Products are not displayed when simple search on django
I do search on Django and faced with a problem: products are not displayed. I dont understand why views class SearchView(ListView): template_name = 'store/products.html' def get_queryset(self): query = self.request.GET.get('search', '') if query: products = Product.objects.filter(Q(name__icontains=query) | Q(description__icontains=query)) else: products = Product.objects.all() return products search template <form class="form-inline mb-3" action="{% url 'search' %}" method="get"> <div class="form-group col-8 col-md-10 pl-0"> <input class="form-control w-100" type="search" placeholder="Поиск по сайту" name="search"> </div> <div class="form-group col-4 col-md-2 pl-0"> <button class="btn btn-info" type="submit">Найти</button> </div> </form> products template {% extends 'base.html' %} {% block title %} List {% endblock %} {% block content %} <body style="background-color: whitesmoke;"> {% for product in products %} <main class="container mt-3" style="text-align: center; max-width: 500px;"> <div style="border: 5px solid white; background-color: white;"> <a href="{% url 'product_detail' product.id %}"> <img src="{{ product.image.url }}" style="width:15vh; height:auto;"><br> </a> <p style="font-size: 20px">{{ product.name }}</p> <p style="font-size: 22px">{{ product.price }} руб.</p> <form method="post" action="{% url 'cart_add' product.id %}"><br> <p style="display: none"></p> {{ form }} {% csrf_token %} {% if request.user.is_authenticated %} <input type="submit" value="Add to cart"> {% else %} <p></p> {% endif %} </form> </div> </div> </div> </main> {% endfor %} </body> {% endblock %} I did the same search and all good. I think problem with templates … -
create Model objects inside another models's Adminview
I'm trying to generalize access permissions to certain Nodes for each of my Groups. I have an Access Model model with three different fields: access_type, group and node. Each group can have either Source, Destination or Bidirectional Access to a node which has a name: class Access(models.Model): class AccessType(models.TextChoices): BIDIRECTIONAL = "bi", "Bidirectional" SOURCE = "src", "Source" DESTINATION = "dst", "Destination" access_type = models.CharField(max_length=3, choices=AccessType.choices) group = models.ForeignKey(Group,on_delete=models.CASCADE, related_name='GroupAccess') node = models.ForeignKey(DicomNode, on_delete=models.CASCADE) name = models.CharField(unique=True, max_length=128, null = True) Similar to the common permission view inside the adminView I'd like to create Access objects inside the GroupView, so that they are created with the group which I am inside at the moment. Also, I'd like them do be displayed on the left side with all available Accesstypes and nodes, seperated with an '|' just like all the available permissions: enter image description here I have done the same already with a form to add existing users to a group: class GroupForm(forms.ModelForm): users = forms.ModelMultipleChoiceField( label='Users', queryset=User.objects.all(), required=False, widget=admin.widgets.FilteredSelectMultiple( "users", is_stacked=False)) class Meta: model = Group exclude = () # since Django 1.8 this is needed widgets = { 'permissions': admin.widgets.FilteredSelectMultiple( "permissions", is_stacked=False), } class MyGroupAdmin(GroupAdmin): form = GroupForm list_display … -
how to add pagination in Django?
I want to apply pagination on my data I tried to watch lots of videos and read lots of articles but still can't solve my problem. This is my Views. def car(request): all_products = None all_category = category.get_all_category() categoryid = request.GET.get('category') if categoryid: all_products = Product.get_all_products_by_id(categoryid) else: all_products = Product.get_all_products() data = {} data['products'] = all_products # all products data['category'] = all_category # all category all_products = Product.get_all_products() data['product'] = all_products ] return render(request, 'car.html', data) as you can see I made some changes in above code but its make no diffrence def car(request): all_products = None all_category = category.get_all_category() categoryid = request.GET.get('category') if categoryid: all_products = Product.get_all_products_by_id(categoryid) else: all_products = Product.get_all_products() #pagination paginator = Paginator(all_products,2) **Changes** page_number=request.GET.get('page') **Changes** finaldata=paginator.get_page(page_number) **Changes** data = {'all_products':finaldata,} **Changes** data['products'] = all_products #all products data['category'] = all_category #all category all_products = Product.get_all_products() data['product'] = all_products return render(request, 'car.html', data) I want to display 4 products per page I tried to apply data limit query that work but that not a genuine approach to display data. I read many articles and watch YouTube video. but can't find any solution. which videos and articles I watched there pagination method is totally different they use pagination with … -
Django form with multi input from loop save only last record to database
I have a problem with saving data from a form in django. Only the last record is saved. I generate a list of dates (days of the month) in the view and display it in the form in templates along with the fields next to the type. Everything is displayed correctly in templates, but when I submit to, only the last record from the form appears in the save view. What am I doing wrong, can someone help? forms.py ''' class DoctorsSchedule(forms.ModelForm): # work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00') # official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00') class Meta: model = DoctorSchedule fields = ['date', 'day_type', 'work_hours', 'scheme', 'official_hours'] ''' model.py ''' class DoctorSchedule(models.Model): id = models.AutoField(primary_key=True, unique=True) date = models.DateField(blank=True, null=True) day_type = models.CharField(max_length=255, blank=True, null=True, default='Pracujący') work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00') scheme = models.CharField(max_length=255, blank=True, null=True, default='20') official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00') def __str__(self): return self.date ''' view.py ''' def terminarz(request): today = datetime.now() now = date.today() locale.setlocale(locale.LC_TIME, 'pl_PL') def months(): months = {'1': 'Styczeń', '2': 'Luty', '3': 'Marzec', '4': 'Kwiecień', '5': 'Maj', '6': 'Czerwiec', '7': 'Lipiec', '8': 'Sierpień', '9': 'Wrzesień', '10': 'Październik', '11': 'Listopad', '12': 'Grudzień'} return months ##################### days of month list ###################################### def days_of_month_list(): …