Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Shows ERROR 405 in browser and method not allowed in shell - Django
I'm building a website that has 2 user types. The registration forms works fine but the login form and the Add Products form gives HTTP 404 ERROR in the browser and shows method not allowed in the shell. Here's all the codes of the project: seller/forms.py def login_seller(request): if request.user.is_authenticated: return redirect('home') else: if request.method=='POST': logform = AuthenticationForm(data=request.POST) if logform.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None : login(request,user) return redirect('home') else: messages.error(request,"Invalid username or password") else: messages.error(request,"Invalid username or password") return render(request, 'Seller/login-seller.html', context={'logform':AuthenticationForm()}) seller/models.py from django.db import models from Accounts.models import CustomUser class SellerProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete= models.CASCADE) name = models.CharField(max_length= 90) email = models.EmailField(max_length = 90, unique = True) store_name = models.CharField(max_length = 30, unique = True) def __str__(self): return self.name products/models.py CATEGORY_CHOICES = [ ("ILLUSTRATION", "Digital Illustration"), ("EBOOKS", "eBooks"), ("PHOTOGRAPHS", "Photographs"), ("COMICS", "Comics"), ] class Products(models.Model): seller = models.ForeignKey(SellerProfile, on_delete = models.CASCADE) title = models.CharField(max_length = 255) product_category = models.CharField(choices = CATEGORY_CHOICES, max_length = 100, default = 'eBooks') description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2, default = 0.00) thumbnail = models.ImageField(upload_to = 'media/thumbnail/',null=True, blank = True) files = models.FileField(upload_to = 'media/product_files/', null = … -
Get list of linked objects(used as foreign keys) when deleting an object in Django
I wish to create an API that can be called from the frontend and displays the summary and linked objects to the object i want to delete( Just like in the Django admin delete view) The linked objects are deleted as cascade is being used in the model definition How can I do that? I tried overriding the delete model and the delete view but couldn't get the desired results. -
pop up at if condition in views.py in django
I want to show a pop-up instead of the httpresponse shown as below in views.py after satisfying the if condition - (below is section of code in views.py) if data['check_in'] > now and data['check_out'] > now and data['check_out'] > data['check_in']: #Check if the room is available if available_rooms is not None: if len(available_rooms) >= int(num_rooms_req): for i in num_rooms_req_lst: #Book the First available room # print(available_rooms[i-1]) booking = book_room(request, available_rooms[i-1],data['check_in'],data['check_out'],total_cost) return HttpResponse(booking) else: return HttpResponse('Only 1 rooms available in this category') else: return HttpResponse('All the rooms of this category are booked! Try another category!') else: return HttpResponse('checkin/checkout date in past or checkout date is prior to checkin date!') so in the above views.py code section - what would be the best way to show the return HttpResponse pop-ups or alerts (but alerts would take me to different html) - I don't want to navigate away from the parent html... -
Dynamic user creation in django
I'm creating web-app with the following users, National Director Regional Director Project Coordinator Agent Expected Outcome: A National Director should be able to create a Regional Director, a Regional Director should be able to create a Project Coordinator, and a Project Coordinator should be able to create Agents. Question: How should I make views and forms to accomplish such? #Models class User(AbstractUser): pass class National_Director(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) address = models.TextField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) class Regional_Director(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) REGION = ( ('North', 'Northern Region'), ('East', 'Eastern Region'), ('West', 'Western Region'), ('South', 'Southern Region'), ) region = models.CharField(max_length=20, null=False, blank=False, choices=REGION) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) national_director = models.ForeignKey(National_Director, null=True, blank=True, on_delete=SET_NULL) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) address = models.TextField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) class Coordinator(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) regional_director = models.ForeignKey(Regional_Director, null=True, blank=True, on_delete=SET_NULL) region = models.CharField(max_length=15, null=True, blank=True) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) … -
What do you think the pros/cons of the integration of Django and Vue.js? [closed]
Vue.js can handle SQL with node.js. Django can have Javascript. Integration of Django and Vue.js is more complicated than the above two ways. My question is what kind of situation is suitable for the Integration of Django and Vue.js. And if you could, give me some example of service of it. -
Is there a posibility to link 2 models in Django?
I'm trying to create a quiz web app , where u will enter the app and u will have 2 buttons: create a quiz , and solve a quiz. You can do it without needing to register. I've created the models, one for Quiz and one for Question and i've put an UUID primary key to the quiz so that i can use this unique id as an extension to my link to get to the quiz that contains the questions. My problem is this. After i create a quiz , i want to directly go to the create questions file regarding the created quiz. Becouse right now after i create the quiz, i need to separately go and create a question, then make a dropdown to select the quiz wich the question is for. [image1][1] [1]: https://i.stack.imgur.com/dr4iP.png [image2][2] [2]: https://i.stack.imgur.com/K5tFt.png [image3][3] [3]: https://i.stack.imgur.com/7GdcK.png -
how to show active page while using base template and bootstrap
base.html The below file is my base template, I'm extending this template in my other pages like index, profile, etc. now in base.html home is my active page and I have done this with help of bootstrap class active, help me that how I can use this active class for different pages to show them active. I'm using the Django framework for rendering templates. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Student Portal</title> </head> <body> <!-- nav bar start --> <nav class="navbar navbar-expand-lg navbar-light "> <div class="container-fluid"> <a class="navbar-brand" href="/">StudentPortal</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo02"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'signup' %}">signup</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'profile' %}">profile</a> </li> </ul> </div> </div> </nav> {% block content %} {% endblock content %} <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <!-- Option 2: … -
Can I modify the URLs Django uses for "View on site" admin links to override caching?
My site is behind a cache. I use Django's "View on site" functionality (eg. by defining a get_absolute_url method for each model), but when I make a change to an object and then click "View on site", I don't see the changes because the cache hasn't expired. I don't particularly want to do things like check the referrer header (eg. Django admin routes these URLs via a redirect like /admin/r/19/1653/, which I could test for) as this breaks my cache strategy (I don't currently cache based on referrer). I tried injecting a timestamp query parameter via JavaScript (eg. to send admin users to /some-django-url?ts=12345, which would bust the cache) but this doesn't work because of the above redirect step (eg. I can't "see" the final Django URL in the admin screen, just the /admin/r/ redirect). Does anyone have a good strategy for this? -
Add single field for queryset
I have a list of elements (queryset) that I display in my admin as a list, and also as detail for each element. The whole list should be sent to the frontend with a Boolean flag, saying if these elements will be displayed before or after other elements (the frontend takes care of this, depending on this flag). The flag, which will be a checkbox in the admin, applies for the whole list, not for each element. I am not sure how to handle this, and two options come to mind: I could add a model just to handle this flag, and then combine it with my model for the queryset in the admin class, so the checkbox appears next to the list. I could display the checkbox in each detail view, which will change the value for all elements on save, and keep the exact same flag with the same value inside each element. I could add a helper_text in the admin saying that the value changes all elements' value. Any other idea is welcome. For clarity, this is what I would like to end up in my API: {display_at_beginning: true, elements: [{...}, {...}, {...}]} -
How to implement the "selectpicker" class for all the select element in website?
I have a website, backend using Django, frontend using normal HTML5. I want to change all the default selection box to the class: "selectpicker" once in some place so it could be implemented in all the selection box in the websites. How could I do that in one place? I have tried: base.html <style> select { class="selectpicker"; } </style> ... app.html {% extends 'base.html' %} <style> select { class="selectpicker"; } </style> But failed to do so. I want this kind of solution, better only make change in base.html to change all the selection box in the websites as I have tons of HTML in my website. -
Django admin page copy ManyToMany related field from one model to another
I am trying to write a scheduling app. Here there are multiple workers and I create a group of workers. The Group is used as a template to create schedule. When I create a Schedule object I want to take input of a Group object and copy the members from the Group object to the Schedule object. I don't want to give a ForeignKey to the Group object itself because the workers might change for a single day, whereas the group should be left intact as a template. models.py class Worker(models.Model): name = models.CharField(max_length=30) email = models.EmailField() class Group(models.Model): name = models.CharField(max_length=30) members = models.ManyToManyField(Worker, blank=True) class Schedule(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() date = models.DateField() members = models.ManyToManyField(Worker, blank=True) I understand this can be done easily with views and html templates. But I am trying to do the same under admin page. I have a form for Schedule and registered it in admin.py forms.py class CreateScheduleForm(forms.ModelForm): group = ModelChoiceField(queryset=Group.objects.all()) class Meta: model = Schedule fields = ( 'date', 'start_time', 'end_time') admin.py @admin.register(Schedule) class ScheduleAdmin(admin.ModelAdmin): form = CreateScheduleForm I don't quite understand how to receive this input and process the Group object instance and copy the members. Any help … -
How to get modelform field data filtered by another field?
I am trying to create a new custome model form forthe admin page, but i am facing an issue getting districts filtered by selected city. Here is my code class MinimumListingPriceAdminForm(forms.ModelForm): city = forms.ModelChoiceField( queryset=City.objects.all(), empty_label="Select a city", required=False ) districts = forms.ModelMultipleChoiceField( queryset=District.objects.all(), required=False ) class Meta: model = ListingPrice exclude = ('price',) I need to filter districts based on the selected city. -
getting error on migrating raise TypeError("'Collection' object is not callable. If you meant to " TypeError: 'Collection' object is not callable
I am using djongo to connect my rest_framework API with MongoDB. I have deleted the 0001_initial.py file and try to push the migrations using python manage.py makemigrations and python manage.py migrate but I am getting these errors while doing this. my settings.py file DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'TMS', } } (env) D:\inductionplan\django-api\backend>python manage.py migrate Operations to perform: Apply all migrations: admin, api, auth, authtoken, contenttypes, sessions, token_blacklist Running migrations: This version of djongo does not support "NULL, NOT NULL column validation check" fully. Visit https://nesdis.github.io/djongo/support/ Applying contenttypes.0001_initial...This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying auth.0001_initial...This version of djongo does not support "schema validation using KEY" fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "schema validation using REFERENCES" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name...This version of djongo does not support "COLUMN DROP NOT NULL " fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "DROP CASCADE" fully. Visit https://nesdis.github.io/djongo/support/ Traceback (most recent call last): File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 894, in _alter query.execute() File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 533, in _drop_column self.db[self.left_table].update( … -
Insert data into models which has a foreign key in Django
I want to perform the below query in Django models where image and caption is the field of posts model and user is the foreign key of posts model : insert into posts values('" + user + "','" + image + "','" + caption + "') Here are my models: #posts model class Posts(models.Model): user=ForeignKey(User, on_delete=models.CASCADE) image=ProcessedImageField(upload_to="/images",help_text="Post", verbose_name="Post", processors=[ResizeToFill(400, 400)], format='JPEG', options={'quality': 80}) caption=models.CharField(max_length=40,null=True,default=" ",blank=True) def __str__(self): return self.user.username #user model the default user model #views def UploadPost(request): if 'user' in request.session: if request.method=='POST': post_form=UploadPostForm(request.POST, request.FILES,instance=request.user) if post_form.is_valid(): post_form.save() messages.success(request,"post uploaded") else: return error else: post_form=UploadPostForm(instance=request.user) return render(request, 'users/upload_post.html', context={'post_form': post_form}) else: return redirect('login') #html {% extends "users/base.html" %} {% load static %} {% block content %} <div class="container text-center"> {% if messages%} {% for msg in messages%} {{msg}} {%endfor%} {%endif%} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{post_form.as_p}} <button class="btn btn-outline-dark" type="submit">Upload</button> </form> <a href="{% url 'logout'%}">logout</a> </div> {% endblock content %} when I click on the upload button, it shows the success message but the post isn't uploaded -
Django (DRF) - get_queryset - Trying to return "images" with model "Product" as an extra field
I'm trying to make a queryset which returns all Products. Every Product has one or more ProductImages and I want to add them as an extra field "images" for every product. So the response I'm after is like [ { id: 1, name: "prod1", images: images } ] I've tried the following implementations: Models class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() price = models.FloatField() class ProductImage(models.Model): name = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.CASCADE) My idea implemented in the simplest way class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def get_queryset(self): queryset = Product.objects.all() product_list = [] # iterate over all products for product in queryset: images = ProductImage.objects.filter(product=q.id) product['images'] = images product_list.append(product) return product_list gives error "TypeError: 'Product' object does not support item assignment" New idea, make a new dict and add elements of product and add "images" as an extra field. class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def get_queryset(self): queryset = Product.objects.all() product_list = [] # iterate over all products for q in queryset: images = ProductImage.objects.filter(product=q.id) product = {"id": q.id, "name": q.name, "description": q.description, "price": q.price, "images": images} product_list.append(product) return product_list gives error Internal Server Error: /api/product/ Traceback (most recent call last): File "C:\Users\Simon\.virtualenvs\django_backend-ZmgaAA1F\lib\site-packages\django\core\handlers\exception.py", line … -
UNIQUE constraint failed: account_customuser.username
I have a problem with user's signup. I use Django. When I register the first user everything is fine and the user appears in the admin panel. The problem occurs when I want to register the second user. After submiting the signup form, this error shows up: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: account_customuser.username So it looks like the user will not be saved because the username (email) is not unique, but the email of the second user is different from the first one. Only superuser and first registered user appear at the admin panel. models.py from django.db import models from django.contrib.auth.models import AbstractUser from orders.models import Order class CustomUser(AbstractUser): email = models.EmailField(unique=True, max_length=255, default='') zip_code = models.CharField(max_length=6) address = models.CharField(max_length=255) street = models.CharField(max_length=255) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) email_confirmed = models.BooleanField(default=False) orders = models.ForeignKey( Order, related_name='orders', on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email views.py from django.shortcuts import render, redirect from .forms import CreateUserForm def signup(request): form = CreateUserForm() if request.method … -
Root domain showing nginx default welcome page while subdomain (www) is ok
I am using django + nginx and so far I encounter this issue where if I go to www.stochie.com or the IP address it work fine while if i type in stochie.com it has some issue as in showing the nginx welcome or default page. here is my nginx config file: server { listen 80; server_name www.stochie.com stochie.com "" 18.139.57.168 ; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/stochie; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } while in the django settings.py: ALLOWED_HOSTS = ['www.stochie.com', 'stochie.com', '18.139.57.168'] and in the google domain: Hostname Type TTL Data stochie.com A 1 hour 18.139.57.168 www.stochie.com CNAME 1 hour stochie.com. After checking around, figure out it might be due to nginx using the default config instead of the stochie config but when it is not possible to modify and remove the default config due to permission issues. So currently not sure how to go about this :( -
how to create list history django
sweetest programmer, I am still a beginner And I made a warehouse program with django There is something standing in front of me, but I want to create a page that answers the history of all the arguments that have been added or disposed of. For example, if I add the same girl like this once, it will only give me the total. I want to make a page that answers item details. Added how many times in what days? I want to create a page like the simple history admin, but it remains in my form so that I can control it. Anyone can help me with this. Thank you for it -
no such function: to_tsvector - Django
I'm using Django and PostgreSQL. I have a website where I want to be able to search for books based on both author and its title. I'm using SearchVector to search in both of these fields together. Here's my view: def search(request): query = request.GET.get("query") searched = Book.objects.annotate(search=SearchVector('title', 'author'),).filter(search=query) return render(request, "main/search.html", { "query": query, "searched": searched, }) Here's my template: {% extends "main/base.html" %} {% load custom_filters %} {% block content %} <h1>You searched for {{ query }}</h1> {% for book in searched %} <div class="reading_box"> <h3>{{ book.title }}</h3> <p>{{ book.author }}</p> </div> {% endfor %} {% endblock %} Django gives this weird error about a function I've never even heard of: Internal Server Error: /main/search/ Traceback (most recent call last): File "/opt/homebrew/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/opt/homebrew/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such function: to_tsvector The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/homebrew/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/homebrew/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/adithraghav/Documents/Work/centel/books/main/views.py", line 369, in search return render(request, "main/search.html", { File "/opt/homebrew/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render content = … -
how wrapper function works with same name within different functions in python?
i have two wrap function with same name within two different functions (in a single .py file) def related_to_restaurant(function): def wrap(request, *args, **kwargs): user = AuthUserExtension.objects.filter(Q(user_id=request.user.id)&Q(is_restaurant=True)).exists() data = get_auth_user_extentension(request.user.pk) if data: data = data[0] user_admin = data.is_team_member else: user_admin = False if user or (user_admin and request.user.is_active) or request.user.is_superuser: return function(request, *args, **kwargs) else: # raise PermissionDenied return redirect('logout_store_user') #return function(request, *args, **kwargs) return wrap def user_has_restaurant(function): def wrap(request, *args, **kwargs): restaurant_id = kwargs["restaurant_id"] print({"restaurant_id": restaurant_id}) if int(restaurant_id) != -1: restaurant = RestaurantUser.objects.filter(Q(user_id=request.user.id)&Q(restaurant_id=restaurant_id)).exists() else: restaurant = True data = get_auth_user_extentension(request.user.pk) if data: data = data[0] user_admin = data.is_team_member else: user_admin = False if restaurant or request.user.is_superuser or (user_admin and request.user.is_active): return function(request, *args, **kwargs) else: # raise PermissionDenied return redirect('list_restaurant') return wrap I'm using both as a decorator for different functions So when i call @related_to_restaurant decorator it calls the wrap function of both the functions related_to_restaurant and user_has_restaurant. is this how decorator works or I'm doing something wrong in it. -
Django how to add query results foreign key model to queryset
How can I get the Author model objects into a queryset through the foreign key of B model? I would like to use the Author objects in my template. #Models.py class Book(models.Model): name = models.CharField(max_length=5) class Author(models.Model): # lots of fields class B(models.Model): author = models.ForeignKey(Author) book = models.ForeignKey(Book) selected_book = "ABC" book = Book.objects.get(name=selected_book) original_queryset = B.objects.filter(name=book) for i in original_queryset: print(i.author) # returns what i want queryset = # get all i.author objects somehow return render(request,"template.html", {"queryset": queryset} -
How to send django url with parameters to ajax request?
Currently, I am sending url to the ajax as : $('.togglebtn').on("click",function(){ console.log("Hello") $.ajax({ type: 'GET', url: "http://localhost:8000/toggle/2945016571198", contentType: 'application/json', success: function (data) { appendData(data); function appendData(data) { var mainContainer = document.getElementById("switch_{{forloop.counter}}"); for (var i = 0; i < data.length; i++) { var div = document.createElement("div"); div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ; mainContainer.appendChild(div); } } } }); Currently, I am sending request into a static url. Can we use {% url toggle i.id %} to set the url dynamically in the ajax request? Does this ajax function repeats at all or not? -
Issue executing cron job using django_crontab
I have followed the instructions to use Django-crontab package to execute my cronjobs.The cronjobs gets executed perfectly if I run the command "python manage.py crontab run ".However when I run the server , I get an error Traceback (most recent call last): File "/Users/Documents/GitHub/python_test_env/lib/python3.8/site-packages/django/core/management/init.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'crontab' -
How to use variables as name of fields in order to update objects dynamically in Django
there are three fields in the model below in a Django app, just for example. class MyModel(models.Model): field1 = models.IntegerField(default=0, blank=False,null=False) field2 = models.IntegerField(default=0, blank=False,null=False) field3 = models.IntegerField(default=0, blank=False,null=False) In order to update multiple fields, I want to use a variable "target_field" instead of using each name of fields. for i in (1,3): target_field = "field{0}".format(i) sample_object = get_object_or_404(MyModel, id=sample_d) sample_object.target_field = "sample_value" # this couldn't work. sample_object.save() In the code described above, "target_field" is not recognized as a name of fields. -
IsOwnerOrReadOnly permission
Im trying to do crud api with IsOwnerOrReadOnly permission but other users can still delete posts from the others. Could you please have a look. I have no clue what goes wrong // permissions.py from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self,request,view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user.userprofile // views.py class PostDetail(APIView): permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, ] def get_obj(self, pk): try: return Post.objects.get(id=pk) except Post.DoesNotExist: raise Http404 def get(self, request, pk, format=None): post = self.get_obj(pk) serializer = PostSerializer(post) return Response(serializer.data) def put(self, request, pk, format=None): post = self.get_obj(pk) serializer = PostSerializer(post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): post = self.get_obj(pk) post.delete() return Response(status=status.HTTP_204_NO_CONTENT) // users.models.py class Profile(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True) intro = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_image = models.ImageField(default=None, upload_to='profile/', blank=True, null=True) github = models.CharField(max_length=200, blank=True, null=True) linkedin = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.user.username)