Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework - the best way to use POST request to other model API endpoint?
I have two models - with users profiles and with events. When the user profile is creating, I want to create for him the timetable with events. When I get the events[] list - I want to send all events using POST to Event model API's in url 127.0.0.1:8000/api/all-events/. What is the simplest way to do that? Event models.py: class Event(models.Model): user_name = models.CharField(max_length=128, default='') event = models.CharField(max_length=128, default='') date = models.DateField(default='') Profiles view.py: class ProfilesList(generics.ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['user_name'] def post(self, request, format=None): saveserialize = AccountSerializer(data=request.data) if saveserialize.is_valid(): saveserialize.save() timetable = Timetable(request.data["user_name"], 2021) events = timetable.create_timetable() for event in events: // Here I want to put the .post request to every event. I want to send // {'username': event[0], 'event': event[1], 'date': event[2]} to // Event model API's on url /api/all-events/ return Response("it's working") -
Infinite loop caused by ordering error Django
Faced an issue in Django 3.1.10. It used to work fine for me, however, when deploying the database, when I execute the Payments.objects.all() request, I get the following error. Infinite loop caused by ordering. ['File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/app/bot/assets/BaseRequests.py", line 42, in handle\n await self.__handler(callback, path_args, bot, user)\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/app/bot/commands/subscription.py", line 291, in _\n await subscription_cmd(bot=bot, callback=callback, user=user, path_args=path_args)\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/app/bot/commands/subscription.py", line 227, in subscription_cmd\n for num, pd in enumerate(payment_data, start=1):\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/query.py", line 280, in __iter__\n self._fetch_all()\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all\n self._result_cache = list(self._iterable_class(self))\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__\n results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1162, in execute_sql\n sql, params = self.as_sql()\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 513, in as_sql\n extra_select, order_by, group_by = self.pre_sql_setup()\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 56, in pre_sql_setup\n order_by = self.get_order_by()\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 356, in get_order_by\n order_by.extend(self.find_ordering_name(\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 765, in find_ordering_name\n results.extend(self.find_ordering_name(item, opts, alias,\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 765, in find_ordering_name\n results.extend(self.find_ordering_name(item, opts, alias,\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 765, in find_ordering_name\n results.extend(self.find_ordering_name(item, opts, alias,\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 755, in find_ordering_name\n raise FieldError(\'Infinite loop caused by ordering.\')\n'] The model itself from the models.py: class Payments(models.Model): rate = models.ForeignKey(Rates, help_text='Rate', blank=True, null=True, on_delete=models.CASCADE, related_name='rate_Payments') coupon … -
How to populate database data into multiple modal windows based on ID in Django?
I want to fetch the data of database to the modal window based on their IDs. User Storage is the model name contains multiple IDs based on users. for example, ID -1 should have data A. For ID -2, there should be data B and so on till it iterate IDs of specific user. In views.py file, @csrf_exempt def profile(request,module_id): if request.user.is_authenticated: user_storage_main = user_storage.objects.filter(custom_user=module_id) user_storage = user_storage.objects.get(id=module_id) return render(request, 'profile.html',{"user_storage_main":user_storage_main,"user_storage":user_storage}) and in HTML page, <table> {% for objects in user_storage_main %} <tr> <td><li class="dsi"><a title="" href="#{{ forloop.counter }}"><i class="fa fa-edit"></i></a></li></td> <td><a href="#"><i class="fa fa-trash"></i></a></td> <td>{{objects.store_name}} , {{objects.store_category}}, {{objects.store_start_date}}</td> </tr> {% endfor %} </table> <!-- MODAL WINDOWS STARTED HERE --> <div class="dsi_popup" id="{{ forloop.counter }}"> <div class="new-popup"> <span class="close-popup"><i class="la la-close"></i></span> <h3>Heading</h3><br><br> <form id="www_id" method="post"> <div class="row"> <div class="col-lg-10"> <span class="pf-title">Update Store Name</span> <div class="pf-field"> <input id="sn" type="text" value="{{user_storage.store_name}}" /> </div> </div> <div class="col-lg-4"> <span class="pf-title">Update Store Category</span> <div class="pf-field"> <input id="sc" type="text" value="{{user_storage.category}}" /> </div> </div> <div class="col-lg-4"> <span class="pf-title">Update Start Date</span> <div class="pf-field"> <input id="sd" type="date" name="sd"> </div> </div> <div class="col-lg-12"> <button type="submit">Update</button> </div> </div> </form> </div> </div><!-- MODAL WINDOW END HERE --> EXPECTED OUTPUT : Currently in my database, there are 3 user storages of user with … -
Django get data from included html page
I have a website, where on the "search" page I search for a user in a database, on the "results" page, the data appears, and on this site, I want to make a filtering option. I make this with a "filtered.html" page, which is included in the "results.html" and is having checkboxes. I want to get the checkbox value and according to that, filter the "results.html". If I could get the data from the checkboxes! I don't get any error message, simply nothing shows. (I know that my results page doesn't filter, but I just want it to print my filtered.html data for a start) results.html {% extends "base_generic.html" %} {% block content %} {% include "filtered.html" %} {% csrf_token %} <table> {% for dictionary in object_list %} <td><tr> {% for key, value in dictionary.items %} <td>{{ value }}</td> {% endfor %} </tr></td> {% endfor %} </table> {% endblock %} filtered.html <form method="GET" name="FormFilter"> <div class="form-check"> <input type="checkbox" value="apple" name="fruits" checked> <label for="scales">apple</label> </div> <div class="form-check"> <input type="checkbox" value="plum" name="fruits" checked> <label for="scales">plum</label> </div> <button type="submit">submit</button> </form> view.py def filter(request): fruits = request.GET.getlist('fruits') print(fruits) if fruits == ['apple']: print('you selected apple') if fruits == ['plum']: print('you selected plum') return render(request,'results.html') … -
Why getting .accepted_renderer not set on Response error in django?
I want to return response to my react Js frontend here is my code def save_stripe_info(request): email = 'testing@gmail.com' payment_method_id = 'pm_1K5xfXBbWBJ638dR1WMitwx1' # creating customer customer = stripe.Customer.create( email=email, payment_method=payment_method_id) return Response(status=status.HTTP_200_OK, data={ 'message': 'Success', 'data': {'customer_id': customer.id} } ) but getting error AssertionError: .accepted_renderer not set on Response How can I resolve this. I saw this How to resolve AssertionError: .accepted_renderer not set on Response in django and ajax but this is for only django and returning an HTML page as a template How can I solve this error -
Fetching static files failed in nginx when same route exists
I'm now deploying an django app with nginx and gunicorn on ubuntu. And I configure the nginx virtual host file as below: location /admin { proxy_pass http://admin; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/static/; } I can request the django admin well, but when request a admin static file, it response with 404 status. I'm sure the root path of static file and permissions are correct. Can anyone help? /admin/... (works) /static/admin/... (not works) /static/others (works) -
How can I a Djanog auth user on the command line and not have to manually enter the password?
I'm using Django 3.2 and the auth module. I would like to create a super user on the command line (for eventual inclusion in a docker script). When I try this $ python manage.py createsuperuser --username=joe --email=joe@example.com I'm prompted for a password. The module does not seem to support a "--password" argument ... $ python manage.py createsuperuser --username=joe --email=joe@example.com --password=password usage: manage.py createsuperuser [-h] [--username USERNAME] [--noinput] [--database DATABASE] [--email EMAIL] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] manage.py createsuperuser: error: unrecognized arguments: --password=password Is there a way I can auto-create a user without manual intervention? -
Math in Django ORM and SQLite: decimal ignored if round number, correct result if not round
In a complex query, I have an annotate like this one: result.annotate(test=ExpressionWrapper(485.00 / F( 'period_duration' ), output_field=DecimalField())) This gives me the correct result: Decimal('8.01917989417989E-10') However, if I replace 485.00 with 485: result.annotate(test=ExpressionWrapper( 485 / F( 'period_duration' ), output_field=DecimalField())) I get: Decimal('0') This wouldn't be a problem, if it wasn't that 485 also comes from a field, called "value". My query looks like this: result.annotate(test=ExpressionWrapper( F( 'value' ) / F( 'period_duration' ), output_field=DecimalField())) Value is a MoneyField, basically just a fancy wrapper around DecimalField. I can force my users to always use proper decimals (485.00 as opposed to 485), which in itself would be bad design but... even then, if the database value is 485.00, Django behaves as if it is 485 and thus returns 0 while doing floating point math. I have tried Casting value to a DecimalField, to no avail. result.annotate( res=ExpressionWrapper( Cast('value', output_field=DecimalField()) / F( 'period_duration' ), output_field=DecimalField() )).last().res Result is always: Decimal('0') Instead of the correct one: Decimal('8.01917989417989E-10') How can I force Django to always use floating point math? p.s. period_duration is 604800000000, if it's of any help. -
How can I insert values into database which will retrieves from Category, Seller and Origin model in django?
'''I have made the foreign key relationship in product attributed with Category, Seller, and Origin but could not save the retrieve the values ''' models.py from django.db import models from django.contrib.auth.models import User #from django.db import Seller # Create your models here. class Category(models.Model): category_name = models.CharField(max_length=10) def __str__(self): return self.category_name class Origin(models.Model): origin_name = models.CharField(max_length=10,default=1) def __str__(self): return self.origin_name class Seller(models.Model): seller_name = models.OneToOneField(User, on_delete=models.CASCADE,default=1) def __str__(self): return self.seller_name.username class Product(models.Model): product_code = models.CharField(max_length=20) product_name = models.CharField(max_length=20) product_category = models.ForeignKey(Category, on_delete=models.CASCADE,null=True,related_name='cat',blank=True) product_quantity = models.PositiveBigIntegerField(null=True) product_seller = models.ForeignKey(Seller, on_delete=models.CASCADE,null=True,related_name='seller',blank=True) product_purchase_price =models.PositiveIntegerField(null=True) product_selling_price = models.PositiveIntegerField(null=True) product_origin = models.ForeignKey(Origin, on_delete=models.CASCADE,null=True,related_name='origin',blank=True) #product_image = m #profit_percentage = models.PositiveIntegerField(null=True) def __str__(self): return self.product_name ''' Here's the views.py vile. Can you please tell me where I have to change? I want to insert the data without using the forms.py file. ''' views.py from django.http.response import HttpResponse from django.shortcuts import render from django.contrib.auth.models import User from .models import Product,Category, Seller, Origin from django.contrib.auth import authenticate, login, logout # from .models import * # Create your views here. def add_product(request): cat=Category.objects.all() sell=Seller.objects.all() ori=Origin.objects.all() if request.method=="POST": product_code=request.POST['product_code'] product_name=request.POST['product_name'] product_category=request.POST.get('product_category') product_quantity=request.POST['product_quantity'] product_seller=request.POST.get('product_seller') product_purchase_price=request.POST['product_purchase_price'] product_selling_price=request.POST['product_selling_price'] product_origin=request.POST.get('product_origin') if Product.objects.filter(product_code=product_code).exists(): return HttpResponse('This Product has already taken. Please Try another Product') else: new_product=Product( product_code=product_code, … -
Profile has no user
Im trying to use context processor to show profile page and when I use it the website show Profile has no user context processor: from .models import Profile `def get_profile (request): profile = Profile() return{'information':profile}` models.py" `class Profile(models.Model): user = models.OneToOneField(User, verbose_name=_("user"), on_delete=models.CASCADE) slug = models.SlugField(blank=True, null=True) image = models.ImageField(_("image"), upload_to='profile_img', blank=True, null=True) country = CountryField() address = models.CharField(max_length=100) join_date = models.DateTimeField(_("join date"),default = datetime.datetime.now)` also i made primary url for profile so when i want to go to profile page i write on url accounts/profile/mohammad account is the name of apps profile is the name of page mohammad is user name hints: i want to use profile.html on dropdown menu -
How to pass a js-function to django template with include?
I'm trying to include another template with a js function as variable. {% include "einkaufsliste/components/unorderedlist.html" with items=friends clickAction="see_friend()" %} <script> function see_friend(){ var x = $(this).attr("the_item") console.log(x) } </script> I get $(this), but not $(this).attr("the_item") (returns undefined) <div class="col-12 col-md-11"> <ul> {% for i in items %} <li {% if clickAction %} onclick="{{ clickAction }}" {% endif %} the_item="{{ i }}" >{{ i }}</li> {% endfor %} {% if not items %} <li>keine</li> {% endif %} </ul> </div> Maybe that's also not the proper way to pass a function? Any suggestions? Thanks in advance! -
How to organase smothly Redirect in Django for new Url-name princip
I wanna change url forming system in my site. The old URLs (that was indexed by Search Engines and link-build sites) have type: https://<hostname>/<old_site_section_name>/<id>/ I want change to: https://<hostname>/<new_site_section_name>/<product_brand-name>/ So, indexed url now is like: https://allgid.ru/Mnt/4149 and must be in future as like: https://allgid.ru/Monitor/acer-v227qabmix how make redirect in urls.py in Django: Now there: urlpatterns = [ path('<slug:cat_>/<slug:product_>', views.page_new_Product, name='product'), ... ] Can i use some regular expression directly in urlpattern like this: path(r'^\+\/\d+$', RedirectView.as_view(url='<new_url>', permanent=True)) But how can i get this re r'^\+\/\d+$' and pass it as an argument to some function; that function will connect to my Database, and get <new_site_section_name> by r'^\+ part of re and <product_brand-name> by \d+ part of re, so it 'id' of the Model (Table in db) and compute right new url like: /Monitor/acer-v227qabmix to put it in the place of <new_url> in RedirectView. Can i do it like: path(r'^\+\/\d+$', My_Function()) and this My_Function return RedirectView.as_view(url='<new_url>', permanent=True)? Does this will works? Or there is some enothe way to do this? -
get city from postal code using Geonames service
I am trying to create an API Rest in Django. I have created the models and the endpoints. The next step I have to perform is to retrieve the username' city from the postal code using the Geoname service: www.geonames.org. I have never used this service, I have seen something similar but in Java but haven't managed to make it work. This is my code if it is helpful: models.py: class UsuarioMaster(models.Model): nombre = models.CharField(max_length=50) class UsuarioDetalle(models.Model): usuario = models.ForeignKey(UsuarioMaster, on_delete=models.CASCADE, null=True) codigo_postal = models.CharField(max_length=5) ciudad = models.CharField(max_length=50) views.py: class UsuarioMasterListView(View): def get(self, request): if('name' in request.GET): u_list = UsuarioMaster.objects.filter(name__contains=request.GET['name']) else: u_list = UsuarioMaster.objects.all() return JsonResponse(list(u_list.values()), safe=False) class UsuarioDetailView(View): def get(self, request, pk): usuario = UsuarioDetalle.objects.get(pk=pk) return JsonResponse(model_to_dict(usuario)) -
why getting 'WSGIRequest' object has no attribute 'data' error?
I am trying to use card payment through stripe in react Js and Django. I am following https://betterprogramming.pub/how-to-integrate-django-react-app-with-stripe-payments-95709b3f23e5 this tutorial. frontend const handleSubmit = async (event) => { event.preventDefault(); const card = elements.getElement(CardElement); const {paymentMethod, error} = await stripe.createPaymentMethod({ type: 'card', card: card }); ApiService.saveStripeInfo({ email, payment_method_id: paymentMethod.id}) .then(response => { console.log(response.data); }).catch(error => { console.log(error) }) } export const api = axios.create({ baseURL: API_URL, headers: { "Content-type": "application/json" } }); export default class ApiService{ static saveStripeInfo(data={}){ return api.post(`${API_URL}/payments/save-stripe-info/`, data) } } server @api_view(['POST']) def test_payment(request): test_payment_intent = stripe.PaymentIntent.create( amount=1000, currency='pln', payment_method_types=['card'], receipt_email='test@example.com') return Response(status=status.HTTP_200_OK, data=test_payment_intent) def save_stripe_info(request): print('this => ',request.data) data = request.data email = data['email'] payment_method_id = data['payment_method_id'] # creating customer customer = stripe.Customer.create( email=email, payment_method=payment_method_id) return Response(status=status.HTTP_200_OK, data={ 'message': 'Success', 'data': {'customer_id': customer.id} } ) but whenever I click the submit button it given me following error AttributeError: 'WSGIRequest' object has no attribute 'data' [12/Dec/2021 21:55:57] "POST /payments/save-stripe-info/ HTTP/1.1" 500 71355 for full code please visit https://betterprogramming.pub/how-to-integrate-django-react-app-with-stripe-payments-95709b3f23e5 -
Django CBV - How to test get_context_data with uuid in url?
I use the UUID in the url instead of the primary key. I assume, but am not sure, that this is the cause of my problem in testing my CBVs. my view for user profile : class ProfileView(DetailView): slug_url_kwarg = 'uuid' slug_field = 'uuid' model = User template_name = 'users/profile.html' context_object_name = 'user_profile' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['uuid'] = self.kwargs.get("uuid") return context My url : path( route='profile/<uuid:uuid>', view=views.ProfileView.as_view(), name='profile', ), I can't test get_context_data, Django tells me that my view has no "object" attribute. Maybe I need to override get_object, but my search didn't find anything. My test : class BaseTest(TestCase): def setUp(self): # Set up non-modified objects used by all test methods self.factory = RequestFactory() self.user2 = User.objects.create_user( email='caroline.dupont@free.fr', password='fhh456GG455t', status='VALIDATED', ) return super().setUp() def profile_view_instance(self, test_user): request = self.factory.get(reverse('profile', args=(test_user.uuid,))) request.user = test_user view = ProfileView() view.setup(request) return view class ProfileViewTestCase(BaseTest): def test_get_context_data(self): self.client.force_login(self.user2) context = self.profile_view_instance(self.user2).get_context_data() self.assertIn('uuid', context) The error : ERROR: test_get_context_data (tests.appusers.test_views.ProfileViewTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\Developpement\projet13\tests\appusers\test_views.py", line 75, in test_get_context_data context = self.profile_view_instance(self.user2).get_context_data() File "D:\Developpement\projet13\users\views.py", line 66, in get_context_data context = super().get_context_data(**kwargs) File "D:\Developpement\projet13\venvp13\lib\site-packages\django\views\generic\detail.py", line 94, in get_context_data if self.object: AttributeError: 'ProfileView' object has no attribute 'object' -
How to check email verification code equality in django rest framework?
I am trying to build a email verification for my website with django rest framework. The mechanism is like this: User enters his email and presses continue button He gets a 6 digit verification code He enters the 6 digit code that he received If the code is valid he goes to next step and else an error occurs My problem is in step 4. I don't know how to check the verification code equality, because I can't get it from step 2. My codes are below. I'd be so happy if anyone can help me through this problem:) serializers.py class CodeSerializer(serializers.Serializer): code = serializers.IntegerField() class EmailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email', ] methods.py import random from django.conf import settings from django.core.mail import send_mail def generate_activation_code(): return int(''.join([str(random.randint(0,10)) for _ in range(6)])) def send_verification_mail(email): generated_code = generate_activation_code() subject = 'Sinjim verification code' message = f'Your verification code:\n{generated_code}\nThanks for using sinjim.' from_email = settings.EMAIL_HOST_USER recipient_list=[email, ] send_mail(subject, message, from_email, recipient_list) views.py class EmailView(APIView): def post(self, request, format=None): serializer = EmailSerializer(data=request.data) if serializer.is_valid(): email = serializer.validated_data['email'] methods.send_verification_mail(email) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class CodeView(APIView): def post(self, request, format=None): serializer = CodeSerializer(data=request.data) code2 = methods.generate_activation_code() if serializer.is_valid(): if … -
How do i get all the objects which is in ManyToMany field in Django models
I have two models and in the second model, i created a ManyToMany field class Listing(models.Model): title = models.CharField(max_length=50) name = models.CharField(max_length=100) description = models.TextField() starting_bid = models.IntegerField() category = models.CharField(max_length=50, blank=True) image = models.TextField(blank=True) posted_by = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) def __str__(self): return self.title class Catagories(models.Model): category = models.CharField(max_length=100) listings = models.ManyToManyField(Listing, blank=True, related_name="cat") Now let's assume i have created a category "Electronics" and I had saved 3 listings in this category with title "Mobile, laptop, microwave". Now i want to get all the listings inside this category and I'm not getting it. Now Questions is: How do i get all of the listing items inside this category? -
How to change the content of navbar after user registration in django
I want to change the content of my django home page from Login,Register to Logout when the user gets redirected to the home page after successful registration. I was able to achieve the following change when the user logs in by using the user.is_authenticated but unable to do the same when user registers and gets redirected without the need to log in. views.py: from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm def register(request): if(request.method=='POST'): form=UserRegisterForm(request.POST) if(form.is_valid()): form.save() username=form.cleaned_data.get('username') messages.success(request,f'Account created for {username} , you can now login') return redirect('blog-home') else: form=UserRegisterForm() return render(request,'users/register.html', {'form':form}) @login_required def profile(request): return render(request,'users/profile.html') home.html: {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav … -
How do i test for authentication in django
def authenticate(username=None, password=None): try: user = User.objects.get(email=username) if user.check_password(raw_password=password): return user return None except User.DoesNotExist: return None def authenticate(username=None, password=None): try: user = User.objects.get(email=username) if user.check_password(raw_password=password): return user return None except User.DoesNotExist: return None -
RelatedObjectDoesNotExist at /profile/ User has no customer
I have created the user Customer model. I migrated the model to syn with the database. However I am getting an error of User has no customer. click to profile page through http://127.0.0.1:8000/profile But after adding profile code for every user I am getting the below error Here is my code from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) full_name = models.CharField(max_length=200, null=True) address = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.full_name class CustomerProfileView(TemplateView): template_name = "app/CustomerProfile.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) customer = self.request.user.customer context['customer'] = customer orders = Order.objects.filter(cart__customer=customer).order_by("-id") context["orders"] = orders return context -
Pass kwargs to model save method
I am stuck in weird situation i have this kwarg['device_id'] which i need to access in my save method , it there any way i can achieve this, the reason i want to avoid overriding update method because i have kept my external API calls in model save method , help is needed thanks def save(self, *args, **kwargs): device_uid = (getattr(self,'device_id')).upper() device_name = getattr(self,'device_name') device_profile_name = getattr(self,'device_profile_name') app_id = getattr(self,'device_profile_name') # check whether model is getting saved or updated if self._state.adding: device_status, error_remarks = add_device(app_id,device_profile_name,device_uid,device_name) else: print(device_name,device_uid,device_profile_name,app_id) device_status, error_remarks = update_device(app_id,device_profile_name,device_uid,device_name) <<-- API call if device_status == 200 : super(DeviceSubscription, self).save(*args, **kwargs) schedulars.check_device() else: print(error_remarks) raise RequestException('err:{}'.format(er #update device @api_view(['PUT']) def update_device(request,*args,**kwargs): if kwargs['device_id']: try: device_ins = DeviceSubscription.objects.get(device_id = kwargs['device_id']) serialized_data = DeviceAdditionSerializer(device_ins,request.data,partial = True) if serialized_data.is_valid(raise_exception=True): serialized_data.save() return Response({'data':serialized_data.data},status=200) except Exception as e: return Response({'err':str(e)},status=400) else: return Response({'status':'bad request'},status=400) -
Django rest framework serializer Got AttributeError when attempting to get a value for field `field` on serializer. Try to nest serializers
AttributeError: Got AttributeError when attempting to get a value for field vesting_choice_id on serializer VestingLocationRateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'vesting_choice_id'. Model class VestingChoice(models.Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) participant = ForeignKey('Participant', on_delete=CASCADE, related_name="participants_id") vesting = ForeignKey('Vesting', on_delete=CASCADE, related_name="vestings") class VestingLocationRate(models.Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) vesting_choice_id = ForeignKey('VestingChoice', on_delete=CASCADE, related_name="vesting_choice") country_id = ForeignKey(Country, on_delete=CASCADE, related_name="country_id") Serializers class VestingChoiceSerializer(serializers.ModelSerializer): class Meta: model = VestingChoice fields = "__all__" class VestingLocationRateSerializer(serializers.ModelSerializer): vesting_choice_id = VestingChoiceSerializer(many = False) country_id = CountrySerializer(many = False) class Meta: model = VestingLocationRate fields = "__all__" -
Add multiple "Place of Interest" model to a "Tour" model in Django and allow one "Place of Interest" to be in multiple "Tour" model
What is the best way to represent this situation: I want to create a tour app that consists of "Tour" and "Place of Interest" The "Tour" model would have multiple "Place of Interests". One "Place of Interest" should be able to be added to multiple "Tour". I can't wrap my head around this. So far, I can only add one "Place of Interest" to one "Tour" Here's my model: class PlaceOfInterest(models.Model): name = models.CharField(max_length=255) tour = models.ForeignKey("Tour", on_delete=models.CASCADE, related_name="tours", blank=True, null=True) class Tour(models.Model): title = models.CharField(max_length=255) Any pointer would be greatly appreciated. Thanks in advanced. -
Script returns an empty list data with 200 response, fetching data from django backend
I am working on an autocomplete app that I want users be able to make address search through the backend of Django but somehow the Api doesn't fetch data through the script, why is the payload show any data in the log console but rather an empty list?, I have tried calling the data from the browser as in example http://127.0.0.1:8000/search/?address=val , which fetches the json data response with a payload of data of addresses that match my search, but when i pass the url in my javescript it returns an empty data list with a 200 response. My experience in Js is mediocre, since I'm a novice. <script> new Autocomplete('#autocomplete',{ search : input => { console.log(input) const url = "/search/?address=${input}" return new Promise(resolve => { fetch(url) .then( (response) => response.json()) .then( data => { console.log(data) resolve(data.data) }) }) }, onSubmit : result => { console.log(result) window.open('/search/?address=${result}') } }) </script> my view for search def search_address(request): address = request.GET.get('address') playload = [] if address: fake_address_objs = Address.objects.filter(address__icontains=address) for fake_address_obj in fake_address_objs: playload.append(fake_address_obj.address) return JsonResponse({'status':200 , 'data': playload }) Returned empty data in the console log Returned data in browser using http://127.0.0.1:8000/search/?address=v -
DRF - lack of JWT when creating user instance
I'm struggling with jwt. When I create user's instance, there is not jwt. When I try to obtain jwt with registered credentials I receive info that provided credentials are not correct. It works fine when I create superuser via cmd. serializers: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User write_only_fields = "password" read_only_fields = ('id',) fields = ["email", "password", "first_name", "last_name"] for field in fields: extra_kwargs = {field: {'required': True,'allow_blank': False}} def create(self, validated_data): validated_data["username"] = f'{validated_data["first_name"]}_{validated_data["last_name"]}_{User.objects.count()}' return User.objects.create(**validated_data) signals: from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from rest_framework.authtoken.models import Token @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) views class CreateUserView(CreateAPIView, GenericViewSet): model = User permission_classes = [ permissions.AllowAny ] serializer_class = UserSerializer response = {} def create(self, request): validation_selializer = UserRegistrationSerializer(data=request.data) if validation_selializer.is_valid(): final_selializer = self.get_serializer(data=validation_selializer.data) if final_selializer.is_valid(): self.response = { "info":{ "status":"created", "email":validation_selializer.data["email"] } } return Response(self.response, status=status.HTTP_200_OK) self.response = validation_selializer.errors return Response(self.response, status=status.HTTP_400_BAD_REQUEST)