Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Crispy Forms does not use specified template pack
I have a Django project where I use django-crispy-forms to style my forms. (I use {{ form|crispy }} in my template file to insert the template) Works perfectly fine. Now I upgraded from Bootstrap 4 to Bootstrap 5 and wanted to update my forms accordingly. I pip installed crispy-bootstrap5 (package recommended on django-crispy-forms GitHub) and added "crispy_bootstrap5" to INSTALLED_APPS as well as added CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" and CRISPY_TEMPLATE_PACK = "bootstrap5" to my settings.py file. All according to crispy-bootstrap5's GitHub Page. But nothing changed. It still renders the same html as before. Maybe you can help me with getting that to work. Thank you. -
how do you identify a user every time they load up the page in React, Django rest framework web app
So usually in regular Django you can identify a user doing request.user but in django rest framework and in a completely separated frontend and backend how do you identify a user when a frontend makes a request to the backend? So lets just say I'm using react and I have an access JWT token in my localStorage and and the user object in my state. Should I just make a useEffect hook and call fetch and make a POST request in it before the component loads? and if I did, should I fetch out the user object or the access token? Or maybe there's other way of doing this? -
How to create a nice post form like the ones in forum or in stack overflow?
I am currently building a forum app in my website from scratch with django. I am quite happy with the result so far however I want to improve it. So far, when users want to post a message they need to fill a simple text form : my app Because it's only a simple text field, users can not use emojis, images or add links and the layout looks terrible. It does not look pro and any other forum would embbed a richer message form. How can I make it look like the one from stack overflow ? : my goal Thanks in advance. -
Getting a specific field (e.g. name) instead of pk in object_list for rendering
I have an app for example: class example(models.Model, TemplateHelperClass): reviewer = CharField(max_length=255, verbose_name="Title") book = ForeignKey(books, on_delete=models.PROTECT) review = TextField() ... class books(models.Model, TemplateHelperClass): author = CharField(max_length=255, verbose_name="Author") book_title = CharField(max_length=255, verbose_name="Title") publisher = CharField(max_length=255, verbose_name="Author") def __str__(self): return self.book_title ... class templateHelperClass(): paginate_by = 15 def get_fields(self): return [(field, field.value_to_string(self)) for field in self._meta.fields] *views.py* class bookReviewList(ListView): model = example template_name = "bookreviews.html" ... *bookreviews.html* {% extends "base.html" %} {% block content %} <table class="table"> <thead> <tr> {% for fld, val in object_list.0.get_fields %} <th>{{ fld.verbose_name |title }}</th> {% endfor %} <th></th> </tr> </thead> <tbody> {% for object in object_list %} <tr> {% for fl1, val1 in object.get_fields %} <td>{{val1}}</td> {% endfor %} <td><a class="btn btn-dark" href='{{ object.get_absolute_url }}'>Update</a></td> </tr> {% endfor %} </tbody> </table> {% endblock %} The output html displays the pk for the book, and not the book title (the __str__ method) in this case. I'd like to display the __str__ method. Two questions, both related: (1) Is there a more elegant way to represent the form with my attributes in table format. (I'm using bootstrap for some of the formatting) (2) If not, how do I get the foreignkey field to display the __str__ return … -
Django + django-oauth-toolkit: How to Register OpenIdConnect Endpoints?
How can I access OpenId Connect endpoints in a django + oauth environment? I'm trying to set up a Django (3.2.5) env with OAuth v2 + OpenId Connect using django-oauth-toolkit (1.5.0). I was able to follow the tutorials, which means that I have oauth support. I'm able to get Oauth tokens, and protect endpoints with them. But when I try to configure OpenId Connect, I'm unable to access o/.well-known/... end-points, they simply are not registered. I get a HTTP 404, and the debug page shows that django only knows about o/authorize/, o/token/, and o/revoke-token/. OpendId Connect section seems to imply I don't need to do anything else but enable OpenId for those views to appear. My urls.py looks like: oauth2_endpoint_views = [ path('authorize/', oauth2_views.AuthorizationView.as_view(), name="authorize"), path('token/', oauth2_views.TokenView.as_view(), name="token"), path('revoke-token/', oauth2_views.RevokeTokenView.as_view(), name="revoke-token"), ] urlpatterns = [ path('admin/', admin.site.urls), re_path('^accounts/', admin.site.urls), path('o/', include((oauth2_endpoint_views, 'oauth2_provider'), namespace="oauth2_provider")), path('api/hello', ApiEndpoint.as_view()), # an example protected resource endpoint path('api/secret', secret_page, name='secret'), # requires authentication ] As a part of OAuth config I already Added oauth2_provider to settings.INSTALLED_APPS. Added oauth2_provider.middleware.OAuth2TokenMiddleware to settings.MIDDLEWARE. Added django.contrib.auth.backends.ModelBackend, oauth2_provider.backends.OAuth2Backend, django.contrib.auth.backends.ModelBackend to settings.AUTHENTICATION_BACKENDS. Since this is a testing env, CORS_ORIGIN_ALLOW_ALL is set to True. Added path('o/', include((oauth2_endpoint_views, 'oauth2_provider'), namespace="oauth2_provider")) to `urls. Registered a … -
Django Many-To-One IntegrityError
I am new to Python and Django. I created database due to documents. I tested it and there has been error to many-to-one relationship between two models. It looks weird to me because It works like one to one relationship between those classes but it gives error if I try to add many. There are other classes with same relationship as many-to-one. I created same way and they work just fine. I am using sqlite by the way. class unites (models.Model): id = models.IntegerField(primary_key=True) unitename = models.CharField(max_length=128) class intensivecare_forms (models.Model): id = models.IntegerField(primary_key=True) hospitals_id = models.ForeignKey(hospitals, on_delete=models.CASCADE) formname = models.CharField(max_length=128) data = models.JSONField() unites_id = models.ForeignKey(unites, on_delete=models.CASCADE) It gives this error if I try to add second form into unites. IntegrityError at /admin/LocalManager/intensivecare_forms/add/ UNIQUE constraint failed: LocalManager_intensivecare_forms.unites_id_id Request Method: POST Request URL: http://localhost:8000/admin/LocalManager/intensivecare_forms/add/ Django Version: 3.2.4 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: LocalManager_intensivecare_forms.unites_id_id Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 Python Version: 3.9.6 -
Simple Django blog using JSON files?
I am seeking AdSense approval and my site, even though it contains content, is apparently insufficient for AdSense approval. So I want to add a lightweight blog to the site. However, I don't want to create additional data models, etc. and would prefer to just edit a JSON file that is parsed for blog content. And following that, just include a "blog.html" template on various pages which will load the content. Is there any JSON-fed blog module for Django? I feel like this wouldn't be too hard to create, but I don't want to reinvent the wheel. Thanks! -
Handling request in django view: accessing the body
I' trying a modify my database on a condition based on a body object from the request. here is my fetch function: document.addEventListener('change', function(e) { event.preventDefault(); const magazinOption = e.target.value; const mag_url = "{% url 'my-subscriptions' %}"; if (magazinOption === 'digital') { fetch(mag_url, { method: "POST", headers: { "X-CSRFToken": Cookies.get('csrftoken'), "Accept": "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ 'magazine': 'digital' }) }) .then(response => { return response.json(); }) .then(data => { console.log('Choix de magazin:', paper_magazine ); }); } }); Then in my view file i have this. def post(self, request): ... request_body = json.loads(request.body.decode('utf-8')) print(request_body) print('body:', request_body['magazine']) print('body to string:', str(request_body['magazine'])) if str(request_body['magazine']) == 'digital': user.paper_magazine = False user.save() And in my terminal this is what i see: 04/Jul/2021 08:08:18] "GET /static/src/images/earth.svg HTTP/1.1" 200 3503 {'magazine': 'digital'} body: digital body to string: digital Internal Server Error: /client-profile-new/subscriptions/ Traceback (most recent call last): File "/Users/marcusbey/.pyenv/versions/jaenv36/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/marcusbey/.pyenv/versions/jaenv36/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view apps.front.views.profile.NewProfileSubscriptionsView didn't return an HttpResponse object. It returned None instead. [04/Jul/2021 08:08:25] "POST /client-profile-new/subscriptions/ HTTP/1.1" 500 73892 What am i missing ? Why can't i access the body object's value? -
how to notify the user about the incoming message to the receiver in flutter chat app?
So, I need a chat feature implementation to my flutter app. Since on research many tutorials uses Firebase Firestore as their database. I use my own Django server to have my logic. So, If I'm going to use Django I can implement websockets to connect a user to database and update the changes in real time. The chat is going to be like a one to one connection. So, I have some question First of all, in all those firebase application uses a single documentID to make changes to firebase which will be like room is it a good practice to do so for professional? How can I notify the receiver about the sender message when receiver app is not open state(cleared the app from cache)? What will be the best database design for this application(I have mentioned mine below)? If all the above satisfies, How can I reinitiate the chat sequence of that one to one chat? -
Nuxt Auth Token & refresh token not set
I took the following example from the Nuxt Auth documentation: auth: { strategies: { local: { scheme: 'refresh', token: { property: 'access', maxAge: 1800, global: true, type: 'Bearer' }, refreshToken: { property: 'refresh', data: 'refresh', maxAge: 60 * 60 * 24 * 30 }, endpoints: { login: {url: '/token', method: 'post'}, refresh: { url: '/token/refresh', method: 'post'}, user: false } } } } And I got the following response from my API (Django): { "refresh": "y", "access": "x" } At last, I have the exact same login 'page' as show in the documentation of Nuxt Auth but when I run this neither the refresh or access token is set into the local storage. Upon changing login: {url: '/token', method: 'post'} to login: {url: '/token', method: 'post', propertyName: 'access'} the access token is set properly but doing similar for the refresh token doesn't work. How can I get Nuxt Auth to set both my refresh and access token properly? -
Django Multiple filter with range look-up
my model: class Attendance(models.Model): date = models.DateField() subject = models.ForeignKey(Subject, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) attendance = models.BooleanField() the query i am trying att = Attendance.objects.filter(date__range=(st_date,ls_date)).filter(student__range=(1,10)) it is giving me an error : File "C:\Users\user1\Desktop\backend\environment\lib\site-packages\django\db\models\sql\query.py", line 1184, in build_lookup raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: range -
how to filter django model object if contains in python django
i am trying to filter out a model which contain sender,receiver,user, the problem is when i try to use return Private_messages.objects.filter(sender__contains=sender,receiver__contains=receiver,user=user) it is strict in checking and will only return if condition are met... model example id:1 sender:"dan" reciever:"harry" id:2 sender:"harry" reciever:"dan" id:3 sender:"dan" reciever:"harry" in this sometimes sender is dan sometimes not. with Private_messages.objects.filter(sender="dan",receiver="dan") i want to get all object with the who has sender dan and receiver dan not both dan how can i get something like this in python django? -
Auto-populating a Django model field using JavaScript fails consistently
I have a model named Package. It has fields named, diagnosis, treatment, patient_type, max_fractions and total_package. The fields diagnosis, treatment and patient_type have foreign keys defined in separate individual classes, making diagnosis, treatment and patient_type choice fields. Now what I want is to auto-populate the max_fractions and total_package fields whenever treatment and patient_type's values are selected. I was suggested to use JavaScript to accomplish that. I tried and wrote the codes but to no avail. I'm trying it on max_fractions field first, when I succeed in doing that, I will do it for all the needed fields. Can anyone help me on this, it will be much appreciated. Here are my models: class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) def __str__(self): return self.diagnosis class Treatment(models.Model): treatment=models.CharField(max_length=15, blank=True) def __str__(self): return self.treatment class PatientType(models.Model): patient_type=models.CharField(max_length=15, blank=True) def __str__(self): return self.patient_type class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) forms.py: class DiagnosisForm(ModelForm): class Meta: model=Diagnosis fields='__all__' class TreatmentForm(ModelForm): class Meta: model=Treatment fields='__all__' class PatientTypeForm(ModelForm): class Meta: model=PatientType fields='__all__' class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "max_fractions" : forms.NumberInput(attrs={"onfocus":"mf();"}), } views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST, prefix='package_form') fm_diagnosis=DiagnosisForm(request.POST, prefix='diagnosis_form') fm_treatment=TreatmentForm(request.POST, prefix='treatment_form') fm_patient_type=PatientTypeForm(request.POST, prefix='patien_type_form') if fm_package.is_valid() and fm_diagnosis.is_valid() and fm_treatment.is_valid() and fm_patient_type.is_valid(): … -
Automatically change price when I change inventory in Django?
I am creating an invoice form. I would like to have a function where if I change the inventory (dropdown search), the corresponding price will also change. You can see an illustration of what I want here: https://www.dropbox.com/s/4kpyfve3gzxmcls/dj006_ultimate_goal_for_adding_variable_attr.jpg?dl=0 What I know so far is I can I can query the inventory dropdown search through: inventory = Inventory.objects.get(pk=request.POST['inventory_dropdown_id']) price = inventory.price But how do I propogate such "get" function throughout all the forms (since I'm using query set) how do I set the price (in the view.py) back to the html file when the html file is already rendered? Is there away around this? P.S. Probably been asked before here but I couldn't find any reference. (Hard to find what proper keyword to search) So if you want to post a link. I'd be happy to take a look at it. -
Celery Beat how to calculate difference between datetime.now() and the next scheduled Periodic Task django
I have a celery beat cron schedule set for day 3 of every week. In django shell I can access this schedule: >>> schedule = PeriodicTask.objects.get(name="Bulk Newsletter Send") which results in: >>> <PeriodicTask: Bulk Newsletter Send: * * * * 3 (m/h/dM/MY/d) UTC> My question is, how can I calculate the time difference in days between datetime.now() and the next PeriodicTask? -
When I can call myself a Django developer and be able to apply for a job?
I learnt a Python and Django, by using these I build a web-app but it is not live/online. I have neither certificate and nor IT degree. Now, I wanna actually want to know which things make me a Django/Python web-developer or I am not a web-developer? -
Cannot resolve keyword 'username' into field. Choices are: address, age, city, country, gender, name, phone, pt_id, user, user_id
Please help me, I am stuck at this error. I am new to django, I don't know how to solve this errorstrong text patients/views.py @method_decorator([login_required, patient_required], name='dispatch') class EditPatient(UpdateView): model = Patient_Profile fields = ['pt_id', 'name', 'gender', 'age', 'phone', 'address', 'city', 'country'] template_name = 'patient/patient_edit.html' slug_field = 'username' slug_url_kwarg = 'slug' success_url = reverse_lazy('patients:patient_page') def get_context_data(self, *args, **kwargs): context = super(EditPatient, self).get_context_data(*args, **kwargs) return context patients/models.py class Patient_Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) pt_id = models.CharField(max_length=50) name = models.CharField(max_length=100) gender = models.CharField(max_length=15) age = models.CharField(max_length=10) phone = models.CharField(max_length=20) address = models.TextField() city = models.CharField(max_length=100) country = models.CharField(max_length=100) def __str__(self): return self.user.username patients/urls.py app_name = 'patients' urlpatterns = [ path('', views.patient_page, name='patient_home'), path('profile/<slug>', views.EditPatient.as_view(), name='profile'), ] template <h1>I am {{user.username}} </h1> <a href="{% url 'patients:profile' slug=user.slug %}">Edit Patient</a> {%endblock%} -
Try Uploading multiple image but form was not submitting
I was trying to add multiple images in django. I had shared my code below. every time i click on submit(Add Farm) it will remain on same page. it is not calling post method. models.py class Farm(models.Model): user=models.ForeignKey(FarmUser,related_name="farm_owner",on_delete=models.CASCADE) farmname=models.CharField(max_length=50) SizeOfFarm=models.IntegerField() address=models.TextField(default='') area=models.CharField(default='',max_length=20) city=models.CharField(default='',max_length=20) pincode=models.IntegerField() class FarmImage(models.Model): farm = models.ForeignKey(Farm, related_name="farm_image", on_delete=models.CASCADE) images = models.FileField(upload_to='farm/') forms.py class FarmFormFileds(forms.ModelForm): class Meta(): model = Farm fields=('user','farmname','SizeOfFarm','address','area','city','pincode') class FarmForm(FarmFormFileds): images=forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta(FarmFormFileds.Meta): fields = FarmFormFileds.Meta.fields + ('images',) views.py class NewFarm(CreateView): form_class=FarmForm template_name='farmuser/addfarm_form.html' success_url=reverse_lazy('dashboard') def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('images') if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) I just want to upload multiple files. In above code some functionalities are missing but the problem is that the method is not calling -
Wishlist items are showing correctly in Django
wishlist column from All_Collections have PK of Wishlist.But this below code pointing to the user id instead Wishlist PK(id). products = All_Collections.objects.filter(wishlist= request.user.id) in this line facing issue Can anyone please help me to solve this. View.py @login_required def wish_list_add(request,id): item = get_object_or_404(All_Collections,id=id) wished_item,created = Wishlist.objects.get_or_create(product_id=item, user = request.user.id) messages.info(request,'The item was added to your wishlist') return redirect('all_collections') @login_required def wish_list(request): data = All_Collections.objects.filter() print("All Collections(product table) : ", data.values('wishlist')) data = Wishlist.objects.filter() print("Wishlist PK : " ,data.values('id')) data1=Wishlist.objects.filter(user=request.user.id).values_list('id', flat=True) print("Wishlist pk values :" ,data1) user_id = Wishlist.objects.filter(user = request.user.id) print('wishlist user :' ,user_id) products = All_Collections.objects.filter(wishlist= request.user.id) print('Wishlist Items : ',products) return render(request=request, template_name="D_Crown/wishlist.html",context={'wishlist': products}) @login_required def wish_list_remove(request,id): item = get_object_or_404(Wishlist,id=id) Wishlist.delete(item.id) return redirect('wish_list') Model.py class All_Collections(models.Model): name = models.CharField(max_length=200) image = models.ImageField(upload_to='Images') collection_desc = models.TextField() material_details = models.TextField() price = models.IntegerField() color = models.CharField(max_length=200) shape = models.CharField(max_length=200) review = models.IntegerField() no_purchases = models.IntegerField() offer = models.BooleanField(default=False) offer_percentage = models.IntegerField() new_price = models.IntegerField() exchange = models.BooleanField(default=False) quantity = models.IntegerField() items_left = models.IntegerField() delivery_info = models.CharField(max_length=300) def _str_(self): return self.d_crown_all_collection class Wishlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(All_Collections, on_delete=models.CASCADE) added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username output: Quit the server with CTRL-BREAK. All Collections(product table) : <QuerySet [{'wishlist': 4}, … -
Reverse for 'product_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['products/detail/(?P<slug>[-a-zA-Z0-9_]+)/$']
What I am trying to do I was trying to make urls as human-readable urls with slug, instead of using the pk that Django automatically gives me. What I tried at first time Here are my codes that are relevant to my works. models.py from django.urls import reverse class Product(TimeStampModel): slug = models.SlugField(max_length=80, null=False, default='', editable=False) ... def save(self, *args, **kwargs): from django.utils.text import slugify if not self.slug: self.slug = slugify(self.product_name, allow_unicode)=True super().save(*args, **kwargs) def get_absolute_url(self): kwargs = { 'slug': self.slug, } return reverse('products:product_detail', kwargs=kwargs) views.py ProductListView is the view that shows products from all categories ProductDetailView is the view of detail page of product. from django.views.generic import DetailView, ListView class ProductListView(ListView): model = models.Product template_name = 'products/product_all.html' context_object_name = 'products' paginate_by = 12 paginate_orphans = 5 ordering = 'created' class ProductDetailView(DetailView): model = models.Product template_name = 'products/product_detail.html' context_object_name = 'products' urls.py urlpatterns = [ path('all/', views.ProductListView.as_view(), name='product_list_all'), paht('detail/<slug:slug>/', views.ProductDetailView.as_view(), name='product_detail'), ] templates Directory for template file for ProductListView is templates/products/product_all.html Directory for template file for ProductDetailView is templates/products/product_detail.html <section id="all" class="product-list"> <ul class="item-grid"> {% for product in products %} <li class="item"> <a href="{{ product.get_absolute_url }}"> <img src="{{ product.product_thumbnail.url }}" alt="product-image" class="product-image"> <div class="product-info"> <h1 class="product-name">{{ product.product_name }}</h1> <h2 class="product-price">{{ … -
Django + postgres CI/CD testing guide
Working example for how to implement Gitlab CI/CD testing for Django using postgres? -
Django: create endpoint for a file
I have a mesh.obj file and I would like to create an endpoint for it. For example, the endpoint could be of the form 'path/to/mesh'. How would I do this? -
DRF: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
I am creating ecommerce api using Django Rest Framework. This is my order model. I have 2 many to many fields for address and order items. payment_options= ( ('COD', 'Cash on Delivery'), ('BANK', 'Bank Transfer'), ('WALLET', 'Wallet Transfer'), ) delivery_options= ( ('Placed', 'Placed'), ('Processing', 'Processing'), ('Delivered', 'Delivered'), ('Cancelled', 'Cancelled'), ) order_number = models.AutoField(primary_key=True) items = models.ManyToManyField(OrderItem) order_address = models.ManyToManyField(Address) delivery_date = models.DateTimeField(auto_now_add=False) price = models.FloatField() payment_method = models.CharField(max_length=6, choices=payment_options) delivery_status = models.CharField(max_length=16, choices=delivery_options, default='Placed') class Meta: ordering = ['order_number'] def __str__(self): ord = str(self.order_number) ord_text = "Order #"+ord return ord_text Here is my Serializer: class OrderItemSerializer(serializers.ModelSerializer): prod = ProductSerializer() class Meta: model = OrderItem fields = ["quantity", "prod"] class AdressSerializer(serializers.ModelSerializer): class Meta: model = Address fields =[ "address_1", "address_2", "city", "state", "postcode", "country" ] class CompleteOrderSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) order_address = AdressSerializer(many=True) class Meta: model = Order fields =[ "order_number", "items", "delivery_date", "price", "payment_method", "delivery_status", "order_address", ] def create(self, validated_data): ord_id = [] address_data = validated_data.pop('order_address') print(address_data) for j in range(len(address_data)): address = Address.objects.create( address_1=address_data[j]['address_1'], address_2=address_data[j]['address_2'], city=address_data[j]['city'], state = address_data[j]['state'], postcode=address_data[j]['postcode'], country=address_data[j]['country'] ) ord_id.append(address.id) item = validated_data.pop('items') ids = [] for i in range(len(item)): prod = item[i]['prod']['name'] count = item[i]['quantity'] product = OrderItem.objects.create( prod=Product.objects.get(name=prod), quantity=count ) ids.append(product.id) Order.order_address = Address.objects.filter(id__in=(ord_id)) … -
Django setup url parameter for certain requests only
So I'm trying to setup my Django view such that when they POST to an endpoint they don't need an url parameters, but when they call GET they require it path('posts/', views.PostView.as_view(), name="post"), path('posts/<int:count>/', views.PostView.as_view(), name="post"), The issue with this is that it makes swagger messy and swagger with assume that url/posts/ you can POST and GET from, and url/posts// you can as well, but I only want to be able to POST to the first and GET from the 2nd. Is there a way to do this without creating separate view classes for them? Or is it better practice in this case to create separate view classes? -
Is it easier to create a web or mobile app using Python and Django? What are the other things I need to know?
I am Python intermediate programmer and have no experience in web or mobile development. I only do wish to create a website using python only. I would really be grateful if you could explain all the necessary stuff I should know in order to this. What I am intending to do is to create a QUiz application.