Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need a documentation for using sslcommerz api in django
Can someone help me out to build a payment gateway in django. I want to use sslcommerz. They dont have any documentation for django.Here is their documentation sslcommerz I badly need this or any documentation which i can follow.Because of some mobile banking i have to use their service. -
Django wagtail login required not working
I'm working on wagtailcms.I just want to display a page only if the user is logged in. I have tried LoginRequiredMixin,@method_decorator(login_required, name='dispatch') but nothing works from django.contrib.auth.decorators import login_required @login_required(login_url='/login/') class LessonListPage(RoutablePageMixin, Page): """ Lists all the lessons on one page """ template = "lesson/lesson_list_page.html" custom_title = models.CharField( max_length=100, blank=False, null=False, help_text='Overwrites the default title', ) content_panels = Page.content_panels + [ FieldPanel("custom_title"), ] def get_context(self, request, *args, **kwargs): """Adding custom stuff to our context""" context = super().get_context(request, *args, **kwargs) context["posts"] = LessonDetailPage.objects.live( ).public().order_by('-first_published_at')[:10] #Change 'public' to adjust which posts are displayed context["postcategories"] = Category.objects.all() return context -
html select tag not working in django template
This question is asked many times, but I think I am having issues with strings in the Django template I have a select tag and I want to select the default option from database <select name="category" class="form-control" required="" id="id_category"> <option value="" >--------</option> {% for cat in all_categories %} <option value="{{cat}}" {% if form.instance.category == cat %} selected {% endif %}> {{cat}}</option> {% endfor %} </select> my {{cat}} variable has value 'Django Book' and {{form.instance.category}} also have same value i.e. 'Django Book'. But it doesn't select the desired option however, I am using similar logic in another part <select class="form-control" id="client" required name="client"> <option value=" ">-----</option> {% for customer in all_customers %} <option value="{{customer.pk}}" {% if form.instance.client_id.pk == customer.pk %}selected{% endif %}>{{customer}}</option> {% endfor %} </select> but this time I am comparing ids to select the default option and it works. what is the issue in the above code?? is this issue with strings?? and how can I overcome this. Also, I would like to set strings in the value attribute in the first code example. Thanks for any help. -
How do I proceed after authenticating the user through python social auth?
Hello so I'm very new to Django and I have successfully authenticated a user through twitter using python-social-auth. However, now I need to make a call to Twitters API and I am very lost in how I should retrieve and process the necessary data after authentication such as the user_id and access token in order to be able to do that. Thank you. -
Django ValueError: Field 'id' expected a number but got 'S'
Below is my models that are used in view where errors occur and error occurs in StockQuantity model particularly, when i try to filter or use get to retreive query it says expected number but got 'stringvalue' models.py # StockQuantity class StockQuantity(models.Model): item = models.ForeignKey('Item', on_delete=models.CASCADE, null=True) color = models.ForeignKey( 'ItemColor', on_delete=models.CASCADE) cloth_size = models.ForeignKey( 'ClothSize', on_delete=models.CASCADE, blank=True, null=True) footwear_size = models.ForeignKey( 'FootwearSize', on_delete=models.CASCADE, blank=True, null=True) stock_quantity = models.IntegerField(null=True, default=10) #OrderItem class OrderItem(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) footwear_size = models.CharField(max_length=50, null=True) cloth_size = models.CharField(max_length=50, null=True) color = models.CharField(max_length=50, null=True) ordered = models.BooleanField(default=False) #Order class Order(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) shipping_address = models.ForeignKey( 'Address', related_name='shipping_address', on_delete=models.SET_NULL, blank=True, null=True) billing_address = models.ForeignKey( 'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey( 'Payment', on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) being_delivered = models.BooleanField(default=False) received = models.BooleanField(default=False) requested_refund = models.BooleanField(default=False) refund_status = models.BooleanField(default=False) #Payment class Payment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) paypal_transaction_id = models.CharField(max_length=50) amount = models.FloatField() timestamp = models.DateTimeField(default=timezone.now) Below is my views.py and specifically the view where the error is thrown, I have … -
app.js:6 Uncaught TypeError: Cannot read property 'addEventListener' of null
Here is my app.js const navBtn = document.getElementById("nav-btn"); const navbar = document.getElementById("navbar"); const navClose = document.getElementById("nav-close"); navBtn.addEventListener("click", () => { navbar.classList.add("showNav"); }); navClose.addEventListener("click", () => { navbar.classList.remove("showNav"); }); I have placed the script tag at the end of the body tag in my html. I am using django as my backend and the javascript files have been loaded properly as I am not getting a 404 error. Need some help to resolve the issue -
I want to show customers phone_number and coin in home page
I am trying to fetch customers phone_number & Coin from the DB to my home page But I am stuck here and got really confused about this topic.I tried request.session.customer but it only shows the customers ID. Here is my Customer Models: class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100) coin = models.FloatField(null=True, blank=True) Here is views.py class Index(View): def get(self, request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} #products = None products = Product.get_all_products() cats = Category.get_categories() brands = Brand.get_brands() sliders = Slider.objects.all() offers = Offer.objects.all() # balance = Customer.objects.get(user=request.user) # balance = get_object_or_404(Customer, coin = request.coin) categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: # products = Product.get_products_by_category(categoryID) products = products.filter(category__id = categoryID) # else: # products = Product.get_all_products() if brandID: # proucts = Product.get_brands_by_products(brandID) products = products.filter(brand__id = brandID) # else: # products = Product.get_all_products() args = { 'products':products, 'cats': cats, 'brands': brands, 'sliders':sliders, 'offers':offers, # 'balance':balance } return render(request, 'Home/index.html', args) I commented somelines to show only coin in homepage but its not showing :( -
Django, Permissions other than'view' do not work
First of all, I can't speak English well. test1 account permissions.py from rest_framework import permissions import copy class ViewPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['GET'] = ['%(app_label)s.view_%(model_name)s'] class AddPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['POST'] = ['%(app_label)s.add_%(model_name)s'] class UpdatePermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['PATCH'] = ['%(app_label)s.change_%(model_name)s'] view.py from rest_framework import viewsets, permissions, generics from .serializers import PlayerListSerializer from .models import PlayerList from .permission import ViewPermissions, AddPermissions, UpdatePermissions class ListPlayer(generics.ListCreateAPIView): permission_classes = [ViewPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class AddListPlayer(generics.ListCreateAPIView): permission_classes = [AddPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class DetailPlayer(generics.RetrieveUpdateDestroyAPIView): permission_classes = [UpdatePermissions, ] queryset = PlayerList.objects.all() serializer_class = PlayerListSerializer Through a simple test I confirmed that I can't see the list without 'view' permission. But for the rest of the permissions I get a '401 (Unauthorized)' error and it doesn't work. I have clearly given the authority right. Can you please let me know where the hell is the problem? Thanks in advance to those who answer. No answer was posted, so I ask again. -
Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update_order/(?P<pk>[^/]+)/$']
I am currently using django 3.1.3 on Windows 10. I was following Dennis Ivy's tutorials for creating a django app, and I reached part 11: Inline Formsets. I am 100% sure I have everything Dennis has but for some reason I am getting the error I mentioned in the title. It was able to access the dashboard once, when I went to update orders it crashed, and after that I was never even able to access dashboard (http://127.0.0.1:8000/dashboard/) again! Here are my files: views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from .models import Customer, Address, Credit_Card, Order, Grocery_Store, Product, Supplier, Warehouse, Staff_Member, Price from .forms import OrderForm #Create your views here. def index(request): return render(request, 'index.html', {}) def dashboard(request): orders = Order.objects.all() customers = Customer.objects.all() total_customers = customers.count() total_orders = orders.count() delivered = orders.filter(status='Delivered').count() pending = orders.filter(status='Pending').count() context = {'orders':orders, 'customers':customers,'total_orders':total_orders,'delivered':delivered,'pending':pending } return render(request, 'dashboard.html', context) def customer(request, pk_test): customer = Customer.objects.get(Customer_ID=pk_test) orders = customer.order_set.all() order_count = orders.count() context = {'customer':customer, 'orders':orders, 'order_count':order_count} return render(request, 'customer.html', context) def products(request): products = Product.objects.all() return render(request, 'products.html', {'products':products}) def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields=('Product_Name', 'status'), extra=10 ) customer = Customer.objects.get(Customer_ID=pk) formset = OrderFormSet(queryset=Order.objects.none(),instance=customer) … -
The view register.views.ActivateAccountView didn't return an HttpResponse object. It returned None instead
Request Method: GET Request URL: http://localhost:8000/activate/MTA/adw60x-512068e272684badad26f51a29e1412f/ Django Version: 3.1.3 Exception Type: ValueError Exception Value: The view register.views.ActivateAccountView didn't return an HttpResponse object. It returned None instead. Exception Location: E:\python\soalnesia\venv\lib\site-packages\django\core\handlers\base.py, line 307, in check_response Python Executable: E:\python\soalnesia\venv\Scripts\python.exe Python Version: 3.9.0 Python Path: ['E:\python\soalnesia\soalnesia', 'C:\Users\uec\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\uec\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\uec\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\uec\AppData\Local\Programs\Python\Python39', 'E:\python\soalnesia\venv', 'E:\python\soalnesia\venv\lib\site-packages'] Server time: Wed, 25 Nov 2020 04:46:31 +0000 class ActivateAccountView(View): def get(self,request,uidb64,token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.Objects.get(pk=uid) except Exception as identifier: user=None if user is not None and generate_token.check_token(user,token): user.is_active=True user.save() messages.success(request, 'ACCOUNT IS ACTIVATE') return redirect('login') else: return render(request,'auth/activate_failed.html', status=401) path('activate///',views.ActivateAccountView.as_view(), name='activate'), Hi, {{user.username}} Please click this link below to verify your account http://{{domain}}{% url 'activate' uidb64=uid token=token %} -
update the choice list of django model using django Admin panel
my model is currently as follows : class Food(model.Model): CUISINE_CHOICES = ( ('1', 'Chinese'), ('2', 'French'), ('3', 'Italian'), ('4', 'Indian'), ('5', 'Japanese'), ('6', 'Moroccan'), ('7', 'Spanish'), ('8', 'Thai'), ) Cuisine = models.CharField(max_length = 20,choices = CUISINE_CHOICES,default = '1') Dish = models.CharField(max_length=200, blank=True) Is there a way by which I can update the CUISINE_CHOICES list in future from the admin panel. Say I need to add Arabian as the 9th cuisine. I know that manually updating the cuisine_choices list will resolve it, I want to know if i can do the same from Admin Panel. If yes, How ? I've searched for similar questions/ solutions but could not find one that matches my requirement. TIA. -
Inlineformset_factory saving parent without child and not displaying validation errors if child is none
I am having 2 issues, one if you submit and click back and then submit again it duplicates the instance in the database - in this case Household. In addition it is saving the parent 'Household' without the child 'Applicants' despite me setting min_num=1 can someone point me in the right direction to resolve this issue. Many thanks in advance class Application(models.Model): name = models.CharField(max_length=100, blank=True, null=True) application_no = models.CharField(max_length=100, unique=True, default=create_application_no) created_date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) class HouseHold(models.Model): name = models.CharField(max_length=100) application = models.ForeignKey(Application, on_delete=models.CASCADE) no_of_dependents = models.PositiveIntegerField(default=0) class Applicant(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) household = models.ForeignKey("HouseHold", on_delete=models.CASCADE) forms.py class ApplicationForm(ModelForm): class Meta: model = Application fields = ( "name", ) class ApplicantForm(ModelForm): class Meta: model = Applicant fields = [ "household", "first_name", "last_name" ] class HouseHoldForm(ModelForm): class Meta: model = HouseHold fields = [ 'name', 'application', 'no_of_dependents' ] def __init__(self, application_id=None, *args, **kwargs): super(HouseHoldForm, self).__init__(*args, **kwargs) self.fields['name'].label = 'House Hold Name' if application_id: self.fields['application'].initial = application_id self.fields['application'].widget = HiddenInput() ApplicantFormset = inlineformset_factory( HouseHold, Applicant, fields=('household', 'first_name', 'last_name'), can_delete=False, extra=1, validate_min=True, min_num=1) views.py class HouseHoldCreateView(LoginRequiredMixin, generic.CreateView): model = models.HouseHold template_name = "households/household_create.html" form_class = HouseHoldForm def get_parent_model(self): application = self.kwargs.get('application_pk') return application def … -
Querying Many To Many relationship in Django
I'm experimenting with Django and I'm trying to figure out Many to Many Relationships. Let's say I have certain model named "Facility", similarly I created another model named "Hotels" which contains fields 'facility' and 'featured_facility' both are in Many To Many relationship with "Facility". I want to add featured_facility only if it is available in 'facility' fields how can I do that? Here is my models code. class Facility(models.Model): name = models.CharField( max_length=100, validators=[validate_facility_name], unique=True, ) description = models.CharField(max_length=100, validators=[validate_facility_description]) can_be_featured = models.BooleanField(default=False) similarly Hotel model is class Hotels(models.Model): hotel_name = models.CharField( max_length=20, unique=True, validators=[validate_hotel_name] facility = models.ManyToManyField( Facility, related_name='hotel_facility', blank=True, ) featured_facility = models.ManyToManyField( Facility, related_name='featured_hotel_facility', blank=True, ) class Meta: default_permissions = () verbose_name = 'Hotel' verbose_name_plural = 'Hotels' def __str__(self): return self.hotel_name Now I want to add 'featured_facility' only if it is available in 'facility' no new featured facility from Facility can be added in 'featured_facility' I am stucked on querying many to many relationship part? -
Django, Only the view permission works, the rest of the permissions do not
First of all, I can't speak English well. test1 account permissions.py from rest_framework import permissions import copy class ViewPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['GET'] = ['%(app_label)s.view_%(model_name)s'] class AddPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['POST'] = ['%(app_label)s.add_%(model_name)s'] class UpdatePermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['PATCH'] = ['%(app_label)s.change_%(model_name)s'] view.py from rest_framework import viewsets, permissions, generics from .serializers import PlayerListSerializer from .models import PlayerList from .permission import ViewPermissions, AddPermissions, UpdatePermissions class ListPlayer(generics.ListCreateAPIView): permission_classes = [ViewPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class AddListPlayer(generics.ListCreateAPIView): permission_classes = [AddPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class DetailPlayer(generics.RetrieveUpdateDestroyAPIView): permission_classes = [UpdatePermissions, ] queryset = PlayerList.objects.all() serializer_class = PlayerListSerializer Through a simple test I confirmed that I can't see the list without 'view' permission. But for the rest of the permissions I get a '401 (Unauthorized)' error and it doesn't work. I have clearly given the authority right. Can you please let me know where the hell is the problem? Thanks in advance to those who answer. -
File upload with Django form
I am trying to upload video files to vimeo, this is my code views.py def upload_to_vimeo(request): token = 'xxxxx' if request.method == 'POST': video_file = request.POST.get("video_file") v = vimeo.VimeoClient( token=token, ) video_uri = v.upload(video_file) print(video_uri) return redirect('home') return render(request, 'forms/video_upload_form.html', {}) template <form action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file"> <input type="submit" class="button" value="Upload"> </form> but it throws error AttributeError at /upload_to_vimeo/ 'NoneType' object has no attribute 'read' but I can directly upload without a form as follows v = vimeo.VimeoClient( token=token, ) video_uri = v.upload('client_admin/test1.mp4') How I can do it with a form, any help -
Getting all the users name who liked a post in django
I am trying to show the List of Users who Liked a Particular Post. Here is what I have tried but nothing is showing. I have created the post_likes in the views.py and tried to loop through its users in the post-details.html: Here is the post_detail.html template: {% for user in post_likes %} <p>{{ user.username }}f</p> {% endfor %} but nothing is showing. Here is the Post Models.py: class Post(models.Model): content = RichTextUploadingField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here are the like model.py: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) Here are the views.py: class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) --------Comment Related Lines-------------------------------- else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form context["total_likes"] = total_likes context["liked"] = liked return context def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() if self.request.is_ajax(): context = self.get_context_data(self, *args, **kwargs) html = render_to_string('blog/comments.html', context, request=self.request) return JsonResponse({'form': … -
horizontal multiselect checkboxes in django admin
Hopefully this is a simple fix, although I haven't found anything through searching. I am using this code in admin.py to make my manytomany field appear as checkboxes in admin. class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } But, I have about 10 choices, which is annoying as a vertical list. Is there a way to get the checkboxes to display horizontally or even more flexibly as 2 columns of five choices (or some other arbitrary look)? -
Best approach to an API update project
I'm working in a personal project to segment some data from the Sendinblue Api (CRM Service). Basically what I try to achieve is generate a new score attribute to each user base on his emailing behavior. For that proposed, the process I've plan is as follows: Get data from the API Store in database Analysis and segment the data with Python Create and update score attribute in Sendin every 24 hours The Api has a Rate limiting 400 request per minute, we are talking about 100k registers right now which means I have to spend like 3 hours to get all the initial data (currently I'm using concurrent futures to multiprocessing). After that I'll plan to store and update only the registers who present changes. I'm wondering if this is the best way to do it and which combinations of tools is better for this job. Right now I have all my script in Jupyter notebooks and I recently finished my first Django project, so I don't know if I need a django app for this one or just simple connect the notebook to a database (PostgreSQL?), and if this last one is possible which library I have to learn … -
why json response is returning nothing?
Here I am using django 3.0.3. i have two question here. 1-you can see in terminal output json response is equal to {} brackets, i don't its not returning api data. and at the send i am using condition where set if there is json response than redirect that condition is becoming true but not redirecting to the desire template or page. 2-i am trying to redirect template landpage to dashboard page but with my code that is not working. I search about this but got nothing helpful so now I am asking this question maybe you guys can figure out. you will understand more better once you see code below and the output from terminal is also mentioned below. views.py def get(self, request): # <view logic> output = self.request.GET.get('hash', None) print('print',output) if output is not None: print("Hash",output) print('Proper url =',f'https://api.shasta.tronscan.org/api/transaction-info?hash={output}') response = requests.get(f'https://api.shasta.tronscan.org/api/transaction-info?hash={output}') print('Resposne =',response) # session = requests.Session() # response = session.get(f'https://api.shasta.tronscan.org/api/transaction-info?hash={output}') print('Response.header =',response.headers['content-type']) print('Response.json =',response.json) print('Response.json =',response.json()) json = response.json() if response.json() is not None: print('condition is true') return redirect('dashboard') # return JsonResponse(response.json()) return render(request, self.template_name, {}) output in terminal Hash 0850eb3e2428f870209b53ffdb0000000000000000000 Proper url = https://api.shasta.tronscan.org/api/transaction-info?hash=0850eb3e2428f870209b53ffdb0000000000000000000 Resposne = <Response [200]> Response.header = application/json;charset=utf-8 Response.json = <bound method … -
DOS attacks in Django?
I wanted to know how Denial of Service attack and XSS attacks are handled in Django? I tried reading it on official site, but still it's not clear . -
Printing out dictionary values from Python to HTML
Hey guys I'm trying to figure out how to print the values from newqueries, which I get from view.py. Why am I able to print out the values in the loop but not outside of them? What is the correct syntax to print out the username of newquery. Right now I'm getting this error when I try to print out the way below, which I know is wrong: Could not parse the remainder: '[0].username' from 'newqueries[0].username' Any ideas? view.py: def profile(request, username): userSearch = User.objects.get(username = username) userID = userSearch.id newquery = NewPost.objects.filter(username = username) followersCount = Follow.objects.filter(following_id = userID).count() return render(request, "network/profile.html", {'followers_count': followersCount, 'newqueries': newquery}) profile.html: {% extends "network/layout.html" %} {% block body %} <h2>{{user.username}}'s Profile</h2> <h1>{{newqueries[0].username}}</h1> <input type="button" value="Follow" id="followButton"> <p>Followers: <span id="followers">{{ followers_count }}</span></p> <p>Follows: </p> {% for newquery in newqueries reversed %} <div class="newpost"><p>{{ newquery.body }}</p><p>By: {{ newquery.username }} on: {{ newquery.timestamp }} Likes: {{ newquery.likes }}</p> {% endfor %} </div> {% endblock %} -
Why does sending a delete request trigger the get_queryset() Django method?
I am having trouble sending a delete request from axios to my Django backend. With axios I call delete in the following way for many of my models: // DELETE DAY export const deleteDay = (day_id) => (dispatch, getState) => { axios .delete(`/api/days/${day_id}/`, tokenConfig(getState)) ... The value of tokenConfig(getState) is just: { headers: { Authorization: "Token 032b2f569037f0125753ef8f67e7774d34a756646ae28cefd54eb1c54bd0b149" Content-type: "application/json" } } In my api.py file I have many viewsets which use my predefined model and serializer objects. The viewset that should catch this request is the DayViewSet. I followed a guide to create all of these viewsets and from what I could find online, it seems that the guide I used uses GenericAPIView functions. For this reason I've been using functions like perform_create, get_queryset, etc. I have been able to successfully call this deleteDay function, and it would just delete the instance of the object based on the day_id I gave it, but recently, after changing my get_queryset function, it seems that a strange issue has arisen. Now, when I call the deleteDay function, it calls my get_queryset function instead of whatever is normal. Here is the DayViewSet object: class DayViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = DaySerializer def … -
django - combine two tables in one in views.py for using in template
There are two models: class Person(models.Model): id = models.IntegerField(primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) class Job(models.Model): title = models.CharField(max_length=100) and here are the data in them: table A: +---+--------+-------+ | 1 | Alex | King | +---+--------+-------+ | 2 | Jo | Ford | +---+--------+-------+ | 3 | Bill | Arm | +---+--------+-------+ | 4 | Donald | Black | +---+--------+-------+ Table B: +---+-----+ | 1 | X | +---+-----+ | 2 | XL | +---+-----+ | 3 | S | +---+-----+ | 4 | XXL | +---+-----+ What I want to get in template is a result like this: +---+--------+-------+-----+ | 1 | Alex | King | X | +===+========+=======+=====+ | 2 | Jo | Ford | XL | +---+--------+-------+-----+ | 3 | Bill | Arm | S | +---+--------+-------+-----+ | 4 | Donald | Black | XXL | +---+--------+-------+-----+ The foreignkey is the id. I know annotate may wok here but I do not know how to use it, and the examples on the internet are not so clear. I want to use it in a for loop to get the result like this: {% for field in combined %} <td>{{ field.id }}</td> <td>{{ field.firstname }}</td> <td>{{ … -
Django: Making a value in a model unique specific to a user
I have a model for a project: class Project(models.Model): name = models.CharField(max_length=200, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE) I want to make the project name a unique value per user but at the moment if user 1 creates a name of "project 1" then user 2 is unable use that project name. What is the best way to go about this? Thanks! -
Django Dynamic EditView for a model
I have a Table: I want to create an EditView for particular Type like shown below: When user edits values for C1 & C2 I want my EditView to save it back into my table for Type=T1. Do I write a custom TemplateView? I dont know how to use FormSet in this scenario. Thanks