Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Migrations Issue that cause my django admin panel to error out
I am working on a backend for some web app Using Django and it is working 100% fine on my local machine, However; I had to deploy on digital ocean apps and i followed a guide and it went perfectly well but when i try to open the admin panel and access some of my tables i get this error. Below is a small log portion related to error. django.db.utils.ProgrammingError: column myapi_schedule.Start_Time does not exist [scheduler-live] [2021-12-12 21:51:50] LINE 1: ...."Start_Date", "myapi_schedule"."Products_Array", "myapi_sch... [scheduler-live] [2021-12-12 21:51:50] ^ [scheduler-live] [2021-12-12 21:51:50] HINT: Perhaps you meant to reference the column "myapi_schedule.Start_Date". -
reverse query GeoJSONLayerView Django GeoJson
I have a model that looks like this: class Site(models.Model): site_id = models.TextField(primary_key=True) site_name = models.TextField() region = models.TextField(blank=True, null=True) ccamlr_id = models.TextField() latitude = models.DecimalField(max_digits=5, decimal_places=3) longitude = models.DecimalField(max_digits=6, decimal_places=3) centroid = models.GeometryField(blank=True, null=True) class SiteSpecies(models.Model): site_species_id = models.AutoField(primary_key=True) site = models.ForeignKey(Site, models.DO_NOTHING, blank=True, null=True,related_name="sites") species = models.ForeignKey('Species', models.DO_NOTHING, blank=True, null=True) class Species(models.Model): species_id = models.TextField(primary_key=True) common_name = models.TextField() genus = models.TextField(blank=True, null=True) species = models.TextField(blank=True, null=True) And I'm rendering these sites as a GeoJSONLayerView like this: class MapLayer(GeoJSONLayerView): def get_queryset(self): X = Site.objects.all() return X geometry_field = 'centroid' srid = '3031' properties = ['site_name','ccamlr_id'] What I'm trying to do is use the reverse lookup here so when I get the properties for this layer view, I also get Species in the output JSON. I was thinking something like this: class MapLayer(GeoJSONLayerView): def get_queryset(self): X = Site.objects.all() return X geometry_field = 'centroid' srid = '3031' properties = ['site_name','ccamlr_id','sites.all.species_id'] But that doesn't seem to work. Nor does 'sites__all__species_id' Thanks in advance, folks. -
Django 3.x - field in model should not be sent from client but only from admin
I am using a Django model with a field named "status". This field should not be sent from the client and this should be validated by the server. Once the object is created an admin can update this field as the object undergoes different status. How is this best implemented? So far I could not come up with a good idea (readonly fields? Using http methods? ...) -
Cannot get values from request in Django - Empty QueryDict
I’m new to ViewSets and am trying to get the values sent from the front-end fetch method to Django’s request object in the create function. I don’t know whether it’s just a simple syntax error or whether the data isn’t being sent properly from the front-end, but I think it’s a back-end issue. The stringified data in the post method seems to log correctly at the front-end like with this test: {"title":"test","type":"landing","slug":"","notes":""} Printing variables in the ViewSet’s create function however shows these: print(request.POST["title"]) # fails with keyerror: 'title' MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'title' print(request["title"]) # fails with TypeError: 'Request' object is not subscriptable print(request.POST.get("title", “test”)) # fails as print test print(request.POST.get("title")) # fails as it just returns None print(request.get("title")) # fails with AttributeError: 'WSGIRequest' object has no attribute 'get' print(self.request.query_params.get("title", None)) # prints None print(self.request.query_params) # prints empty QueryDict: <QueryDict: {}> Here’s the create function: class PagesViewSet(viewsets.ViewSet): def create(self, request): # printing went here page = Page.objects.create( title="testing", type="other", slug="test-slug", notes="test notes" ) serializer = PageSerializer(page) return Response(serializer.data) I’ve just chucked in demo data inside the page create method to ensure it works, which it does, and now want to use the real data which should be in the request. Does anyone … -
What's the best way to define a particular number with special characters in a database django
I have a specific requirement for a Django model field, essentially I want to create this type of series: 0025-0007 Essentially 4 integer fields, one character, and 4 integer fields thereafter, I don't need an auto-increment as the number changes, is there anything available in Django already that handles such fields, ideally something with automatic validation? -
Query lookups in SQLAlchemy
I can’t find any information about lookup api in the SQLAlchemy, is it supported? I’m talking about this feature in Django ORM: https://docs.djangoproject.com/en/4.0/ref/models/lookups/ It’s very useful for my case because I have a table on frontend with many filtering options, and in Django I can just queryset.filter(**kwargs). If this is not supported, is there any way to achieve it? -
400 http error on all post method of a blueprint
So I have this project that I have added a blueprint to it... everything worked fine and I tested the endpoints. All good All ok . Now after 2 weeks I'm debugging and testing the tasks I have done in the sprint and now all of my requests getting 400 HTTP Error.... Any idea what could have caused the problem ? app file from my_bp import bp app.register_blueprint(bp,url_prefix="/test") my_bp file bp = Blueprint("my_bp",__name__) @bp.route("/test",methods=["GET","POST"] def test(): return {"test":"helloworld"} Now if I send a get request via postman it's all good, but when I try to send a simple post request without a body ( or with the body ) I get the 400 Error response... Thanks in advance P.S. All other blueprints are doing fine but this one is returning 400 on all of my post requests P.S. I use Post-man for sending requests -
Django: How to delete a group which is related to a team?
I want to extend Django's group model. To do so I've created a Team class, which references the group model with a OneToOne field. Create and update work as expected, but I fail to delete the team. # teamapp/models.py from django.db import models from rules.contrib.models import RulesModel from django.contrib.auth.models import Group class Team(RulesModel): group = models.OneToOneField( Group, on_delete=models.CASCADE, primary_key=True, ) name = models.CharField(max_length=80) def save(self, *args, **kwargs): self.update_or_create_group() return super().save(*args, **kwargs) def update_or_create_group(self, *args, **kwargs): group, _ = Group.objects.update_or_create( id=self.pk, defaults={"name": self.name}, ) # teamapp/signals.py from django.db.models.signals import post_delete from django.dispatch import receiver from django.db import transaction from django.contrib.auth.models import Group from teamapp.models import Team @receiver(post_delete, sender=Team) def delete_group(sender, instance, created, **kwargs): # TODO: Use celery for async operation: https://docs.djangoproject.com/en/3.2/topics/db/transactions/ transaction.on_commit(lambda: delete_group(instance)) def delete_group(team_instance): Group.objects.filter(id=team_instance.group).delete() Somehow the signal doesn't trigger. Is there an other way? -
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?