Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
csrf token not working when user logged in react js axios django
when i log out and try to post it works but when i log in and try to post it does not work and gives me 403 error , react file class Axios extends React.Component{ constructor(){ super() this.state = { persons: [] } } post(){ axios.post('http://127.0.0.1:8000/api/create', { title: 'titan', body: 'this is working', headers:{ withCredentials: true, 'X-CSRFToken':CSRF_TOKEN, 'Accept': 'application/json', 'Content-Type': 'application/json', }, }) .then(function (response) { console.log(response); }) } get(){ axios.get('http://127.0.0.1:8000/api').then(Response=>{ console.log(Response.data) }) } componentDidMount(){ this.post(); this.get(); } render(){ return( <div> <h1>fetch</h1> </div> ) } } export default Axios; views.py class create(CreateAPIView): queryset = Post.objects.all() serializer_class = postSerializers also added this in setting.py CSRF_COOKIE_NAME = "X-CSRFToken" when logged in when logged out if there anyone who is clever enough pls help me on this.. trying to find the solution for days... -
Dryest way to use a ManyToManyField to store values in model
I've created a real estate back end website with Django and I'm creating a way to track how agents are performing in various cities on Zillow in terms of reviews. While I could create a model that looks like this: class Agent(models.Model): url_los_angeles = models.URLField(default="https://zillow.com/los_angeles") rank_los_angeles = models.IntegerField(default=0) url_san_diego = models.URLField(default="https://zillow.com/san_diego") rank_san_diego = models.IntegerField(default=0) This doesn't seem like a very smart way to do this. Using a ManyToManyField field seems like the right approach, but I don't quite see how this would work. For example, how would an agent's individual ranking be store in the many to many field? Any insight would be greatly appreciated. -
Applying local timezone in Django templates
I use Django 3.1.7 and postgreSQL for the database. So here is the problem, after saving a date in my database I try to display it in a template with the timezone of the visitor and it's still displaying me the date UTC. I have these values in my settings.py: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True my model: class Log(models.Model): user = models.ForeignKey(to=User, on_delete=models.PROTECT) log = models.CharField(max_length=255) type = models.CharField(max_length=50) date = models.DateTimeField(auto_now_add=True) company = models.ForeignKey(to=Company, on_delete=models.PROTECT) my context processor getting me the objects: def logs_processor(request): if request.user.has_perm('loging.can_see_logs'): try: logs = Log.objects.filter(company=request.user.company).order_by('-date')[:50] except TypeError: logs = None return {'side_logs': logs} else: return {'side_logs': []} And my template: {% load tz %} {% for log in side_logs %} {{ log.date|localtime }} {% endfor %} I tried without the |localtime but no luck. When I specify by hand the TZ like log.date|timezone:"Europe/Paris" That works well. As well I precise that I have pytz installed. Here what my dates look like in the database (it seams they are not naive and placed on UTC as planed): 2021-03-10 04:10:11.849048 +00:00 Any idea? -
Don't acctually now how to use ForeginKey in my issue. No idea where the problem is, looked out for HOW TO "ForefinKey use"
In my case I want, to use ForeginKey field. I want to build app something like "Items added by user and I want get ready and clear order with unique ID and items passed by user". Add items Make order with status etc. I stucked almost at the begining... models.py class Item(models.Model): width = models.CharField(max_length=5) length = models.CharField(max_length=5) description = models.CharField(max_length=255) def __str__(self): return "%sx%s" % (self.width, self.length) class Order(models.Model): STATUS = ( (0, 'pending'), (1, 'during'), (2, 'done')) costumer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, on_delete=models.CASCADE) item = models.ForeignKey(Item, blank=False, on_delete=models.CASCADE) startDate = models.DateTimeField(auto_now_add=True) status = models.IntegerField(default=0, choices=STATUS) slug = models.SlugField(blank=False, unique=True, default=create_randomSlug()) def __str__(self): return "Zamówienie ID#%s z dnia %s" % (self.slug, self.startDate) def get_absolute_url(self): return 'order/%s' % self.slug from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Order, Item, Costumer from django.contrib.auth.mixins import LoginRequiredMixin from django.conf import settings views.py class Home(LoginRequiredMixin, ListView): model = Order paginate_by = 100 template_name = "home.html" def OrderDetail(request, slug): order = Order.objects.get(slug=slug) context = {'order': order, } return render(request, 'order_detail.html', context) order_detail.html {% extends 'base.html' %} {% block content %} <!-- Top header --> <header class="w3-container w3-xlarge"> <p class="w3-center">Zamówienie #{{ order.slug }}</p> </header> <div class="table-wrapper"> <table class="fl-table"> <thead> <tr> <th>Lp.</th> <th>Długość</th> <th>Szerokość</th> … -
how to use country name as default instead of code in django-countries package
I am using an a django package called django-countries which gives me access to some countries attributes in the world such as country name, country code, country flag and some other more. It seems the default appears to be the country code, i will like to know how to be able to use the country name instead of the default which is the country code. For example in my views, i have a code like this def analyse_market(request): qs = Product.objects.values('country').annotate( number=Count('pk') ).order_by('country') result = { q['country']: q['number'] for q in qs } print(result) context = {"result":result} return render(request, 'core/analyse-market.html', context) This return a result like this: {'AD': 3, 'AR': 5, 'BH': 1, 'FR': 1, 'JP': 1, 'NG': 1, 'NL': 1} In the documentation, they have different methods used such as country.name, country.code, country.flag, I have tried the country.name because it relates to what I need, but i get KeyError when using the country.name in my views. -
User Form not showing django class based views
I am working on Hospital Management System and there are 5-6 different types of users like Patient, Doctor, Nurse, Accountant, Receptionist, etc. I've extended the User model using AbstractUser which has common fields for all users like DoB, address, etc. models.py class User(AbstractUser): # user_type = models.CharField(choices=USER_TYPES, default='patient', max_length=20) date_of_birth = models.DateField(blank=True, null=True, validators=[validate_future_date]) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+9199999999'. Up to 15 digits allowed.") mobile_num = models.CharField(max_length=15, validators=[phone_regex]) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) date_joining = models.DateTimeField(auto_now_add=True) photo = models.ImageField(default="default.png", upload_to="patients/%Y/%m/%d", blank=True) # other fields def __str__(self): return f"{self.first_name} {self.last_name}({self.username})" class Staff(models.Model): aadhar_number = models.BigIntegerField(verbose_name='Aadhar Number') empCategory = models.CharField(max_length=20, blank=True, verbose_name='Employee Category') class Meta: abstract = True class Patient(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_discharge = models.DateTimeField(auto_now=True) allergies = models.TextField(blank=True, null=True) def __str__(self): return f"{self.user.first_name} {self.user.last_name}({self.user.username})" class Doctor(models.Model): DEPARTMENTS = [('Cardiologist', 'Cardiologist'), ('Dermatologists', 'Dermatologists'), ('Emergency Medicine Specialists', 'Emergency Medicine Specialists'), ('Allergists/Immunologists', 'Allergists/Immunologists'), ('Anesthesiologists', 'Anesthesiologists'), ('Colon and Rectal Surgeons', 'Colon and Rectal Surgeons') ] user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) languages = models.CharField(max_length=20) speciality = models.CharField(max_length=20) department = models.CharField(max_length=50, choices=DEPARTMENTS) # patients = models.ManyToManyField(Patient, related_name='doctors') def __str__(self): return f"{self.user.first_name} {self.user.last_name}({self.user.username})" class Receptionist(Staff): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # patient = models.ManyToManyField(Patient, related_name='receptionists', blank=True) def __str__(self): return f"{self.user.first_name}" class … -
Django Push Notification
I wrote django app for my backend app (Android client), but i haven't idea for push notif or push data to specific client. There are exist tutorial with django-websocket. I read documentation and then conclude that websocket use group for push data. So, user subscribe to group then server push data to all user in group. This did't resolve my problem. I think open new socket based on (TCP) in-same machine (ex. port 5008) for listening client. After client request i will save data connection like address with UID, so i will send data with low socket to client while client already register. Does it work? And Secure? Please remind if there is an wrong theory. Thanks!! -
What type of lookup can i use for a foreign key field in django
I have a search form in my application. I am performing some request with it within the database of my application. The category field is a foreign key relationship in my application. When trying to make a search, i got this error because the category is a foeirgn key and perhaps i used the wrong lookup expression for this. What is the right way i can go about this please? Thanks Error log Exception Type: FieldError at /searchproduct/ Exception Value: Related Field got invalid lookup: icontains models.py class Category(models.Model): name = models.CharField(max_length=256) class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) views.py def search(request): if request.method == 'GET': product_name = request.GET.get('search') products = Product.objects.filter(category__icontains=product_name) or Product.objects.filter(name__icontains=product_name) context = {"products": products} return render(request, "core/search.html", context) else: result = "Sorry there is no product with that name" return render(request, "core/search.html", context) -
Invalid resource lookup data provided (mismatched type) in obj_get_list
I'm having an issue with django-tastypie with tastypie_mongoengine. So I've designed a model that lists contacts from a collection at my MongoDB, all methods are working well except obj_get_list that when called from endpoint myhost/api/v1/contacts raise this error { "error": "Invalid resource lookup data provided (mismatched type)." } So this is how I have structured my model: class ContactResource(resources.MongoEngineResource): class Meta: queryset = Contact.objects.all() allowed_methods = ('get', 'post') resource_name = 'contacts/contact' authorization = CustomerObjectsOnlyDjangoAuthorization() authentication = ApiKeyAuthentication() always_return_data=True paginator_class = Paginator filtering = { "customer_id": [ "exact", ], "campaigns": ["match", ], "id": ["exact", ], "email": ["exact", ], } limit=100 def dehydrate(self, bundle): customs = bundle.data['customs'] if 'customs' in bundle.data: del bundle.data['customs'] excludes = ['customer_id', 'is_spamtrap'] for exclude in excludes: if exclude in bundle.data: del bundle.data[exclude] for c in customs: if c.get('k'): bundle.data[c['k']] = c['v'] return bundle def obj_get_list(self, bundle, **kwargs): if bundle.request.GET.get('campaigns__match'): campaigns = int(bundle.request.GET.get('campaigns__match')) self._meta.queryset = self._meta.queryset.filter(__raw__={'campaigns':{'$elemMatch':{'id': campaigns}}}) if not bundle.request.user.is_staff: kwargs['customer_id'] = bundle.request.user.get_profile().customer.id self._meta.queryset = self._meta.queryset.filter(customer_id=kwargs['customer_id']) return super(ContactResource, self).obj_get_list(bundle, **kwargs) If I call the end point myhost/api/v1/contacts/contact/contac-id I can make it and get data for a specific contact, but to list all the error mentioned above appears Any Help? -
Django: connect social media local user but disallow login using social media credentials
Problem: My Django webapp allows users to login using email/password. Now I need to connect their one or more social accounts to the existing account but only for the purpose of accessing their social media content. They will not be able to login in to my webapp using their social credentials. They still have to use the existing email/password to login in to my webapp. Work so far: I have looked at django-allauth and python-social-auth but not sure if I can be selective about not allowing login but still connect the social accounts. Question: So is it possible to achieve this using django-allauth or python-social-auth ? Is there a simpler method ? Thanks ! -
My Django Project now won't run Python3 manage.py runserver
So I seen this issue here on stack, but for a few slightly different reasons and I can't manage to figure it out for myself. I'm getting this error in my terminal: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? and YES i do have django installed. I'm currently working on the Harvard CS50W project and it was working perfectly fine until i updated my python through HomeBrew. Now my project can't locate django to run the server. I seen stuff online about the virtualenv but I didn't need to set one up prior to starting this project. So I'm not sure what to do in order to get my project back up and running. If someone could please help that would be great! Thanks! Also should mention I'm using the M1 Mac. … -
python remove duplicate element from list
In python i am getting a list in a variable like : [ {'store_id': '321', 'first_name': 'A', 'name': 'A'}, {'second_id': '322', 'first_name': 'B', 'name': 'B', }, {'second_id': '323', 'second_name': 'c', 'name': 'c', }, {'second_id': '324', 'second_name': 'A', 'name': 'A', }, ] what i actually want is i want a list without duplicating the name . if it occur once then i want to remove t and create a new list with distinct data.i am stuck here i want all data in new list. how can i remove the duplicate data from the list . in my case i want a ne list like : Either {'second_id': '322', 'first_name': 'B', 'name': 'B', }, {'second_id': '323', 'second_name': 'c', 'name': 'c', }, {'second_id': '324', 'second_name': 'A', 'name': 'A', }, ] Or [ {'store_id': '321', 'first_name': 'A', 'name': 'A'}, {'second_id': '322', 'first_name': 'B', 'name': 'B', }, {'second_id': '323', 'second_name': 'c', 'name': 'c', }, ] -
Can't pass null fields into django floatfield?
(approach inspired by this thread) I have some json data that I want to import into django models using the example data: [{"orderID": "2b062ac4542172b12f47e2b26d1629ae", "status": "No Car", "specialRequest": "", "endedTime": "2018-12-01T00:02:34HKT", "tunnel": "", "pickedTime": null, "toLocation": {"lat": "22.307488971554207", "lng": "114.2600533354737", "displayName": "\u5c07\u8ecd\u6fb3", "locality": "\u5c07\u8ecd\u6fb3"}, "memberID": "c8dfb02f6d81394582f3ceac57749616", "fromLocation": {"lat": "22.3172022", "lng": "114.16995739999993", "displayName": "\u5f4c\u6566\u9053\u502b\u6566\u5927\u9152\u6a13", "locality": "\u65fa\u89d2"}, "specialRequestText": "85\u6298", "cancelReason": null, "createdTime": "2018-12-01T00:00:00HKT", "paymentMethod": "Cash", "extraTips": 0} This is my model for Member thus far: class Member(models.Model): member_id = models.CharField(max_length=32, primary_key=True) member_loc_lat = models.FloatField(default= None, null=True, blank=True) member_loc_long = models.FloatField(default= None, null=True, blank=True) # blank to be able to pass in null values, null to tell the DB to accept null values member_locality = models.TextField() member_display_name = models.TextField() member_created_time = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return self.member_id And this is the script that loads the member-related fields (from the json file) into my Member model: import json import argparse import django from django.conf import settings import sys import os import pymysql pymysql.install_as_MySQLdb() from mysite.models import Member, Driver, Order def main(): parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", type=str, required=True, help="path to original data file (.data)") args = parser.parse_args() data_members = {} # type list with open(args.input) as f: data_members = json.load(f) for member in range(len(data_members)): … -
Save Django .sqlite3 file in two separate paths
I am trying to deploy an application using SQLite3 as the database and I need to have the same database file stored in two separate paths for production purposes. Is this possible and if so, how? -
Captcha doesn't work, why is this happening?
My captcha appears at the bottom on the right and it's only the logo, there is no challenge and not input bar. Why is this happening? This is the html: <!DOCTYPE HTML> <html> <head> <title>Constancia</title> <script src="https://www.google.com/recaptcha/api.js?render=MYKEY"></script> <script> function onSubmit(token) { document.getElementById("demo-form").submit(); } </script> </head> <body> <div class="header"> </div> <div class="wrap"> <header></header> <form action='/constancia-inscripcion' method="POST"> {% csrf_token %} <label for="cuit">CUIT:</label> <input type="number" name="CUIT"> <label for="email">Email:</label> <input type="text" name="Email"> <input type="hidden" name="g-recaptcha-response" id='recaptcha' > <button type="submit" name="Solicitar constancia"></button> </form> </div> This is the captcha in the backend: c_data = { 'response': request.POST.get('g-recaptcha-response'), 'secret': "6LdEnNsZAAAAANeDqX4oOOaPnidRtoG9yMApCl_t" } resp = requests.post('https://www.google.com/recaptcha/api/siteverify', data=c_data) captcha_response = resp.json() if not captcha_response.get('success') or captcha_response.get('score') < 0.6: print("captcha incorrecto") else: print("captcha correcto") -
Increasing an integer (model variables or view.py dictionary values) by using buttons in Django
Me and my friends are trying to design a translation game website using Django framework. I created a quizloop but I want to add a points system now. I want the point to increase by 10 when the correct answer button is clicked by the player. This is my first time using Django and I couldn't find much explanatory sources for beginners on the Internet. If you are going to suggest using AJAX, JSON or jQuery, I would appreciate explaining your code a bit more in detail. This is my view.py: from django.http import HttpResponse from django.shortcuts import render import random from .models import Test # Create your views here. def question_view(request, *args, **kwargs): randomint = random.randint(1,4) test = Test(questionCounter=1, points=0) question_context = { "Merhaba": "Hello", "Günaydın": "Good Morning", "İyi Akşamlar": "Good Evening", "Bir": "One", "İki": "Two", "Üç": "Three", "Dört": "Four", } dictionary = {"question": random.choice(list(question_context.keys())), "answer1": random.choice(list(question_context.values())), "answer2": random.choice(list(question_context.values())), "answer3": random.choice(list(question_context.values())), "answer4": random.choice(list(question_context.values())), "randomint":randomint, "test": test } if randomint == 1: dictionary["answer1"] = question_context[dictionary["question"]] elif randomint == 2: dictionary["answer2"] = question_context[dictionary["question"]] elif randomint == 3: dictionary["answer3"] = question_context[dictionary["question"]] elif randomint == 4: dictionary["answer4"] = question_context[dictionary["question"]] while dictionary["answer1"] == dictionary["answer2"] or dictionary["answer1"] == dictionary["answer3"] or dictionary["answer1"] == dictionary["answer4"] or dictionary["answer2"] … -
Django Rest Framework Restricting Views
I am building a website that will host multiple apps. Some apps can only be accessed by certain groups from a LDAP backend. To achieve this on a pure Django stack, I used user_has_perm @user_passes_test() so that certain views can only be accessed by users who has permission to add items (I give the permission to add items to certain groups, they are automatically placed into a group from the LDAP) However, I am now migrating to a React + Django stack. How can I achieve a similar effect, where you can only access some apps if you are in the correct LDAP group. Note - I have a single react app frontend that that uses routers to get to different component(apps) -
How can I show the details of a post along with its comments using Django framework?
new to the django framework and a little rusty with coding. I am currently trying to build a tech blog from the ground up and have been using Django Central tutorials as a guide. Currently I am stuck on this tutorial- https://djangocentral.com/creating-comments-system-with-django/#comment-2272, particularly getting my views to show both the details of the post and the comments form. In the tutorial the author switches from a class based view to a function that uses get_object_or_404() in order to retrieve the post. I was able to switch over to this function without any error messages, yet the post detail returns blank. Returning to a class based view solves this issue, but I would like to go with the function provided in the tutorial. Here is the code: views.py def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render(request, template_name, {'post': post, 'comments': comments, 'new_comment': new_comment, … -
TypeError: __init__() got an unexpected keyword argument 'deon_deletefault'
hello I am trying to run a project with python 3.8 and django 3.1.7 and I get the following error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/mauricio/Escritorio/RedDebate/reddebate/resumen/models.py", line 14, in <module> class Debate(models.Model): File "/home/mauricio/Escritorio/RedDebate/reddebate/resumen/models.py", line 25, in Debate args_max = models.IntegerField(deon_deletefault=1) TypeError: __init__() got an unexpected keyword argument 'deon_deletefault' I send you the code that is associated with the error: # … -
How do I update information in the database using POST in Django?
I'm creating a contact list that lets the user Add, Delete, and Edit using Django. I've been able to slowly work my way through most of it except for updating the information in the database after the user hits "Submit". I've tried a few different methods that I thought might work, but unfortunately I just ended up with Errors. So I'm wondering, after I render the html edit form and the user edits whatever field they choose and hits submit, how do I receive that information and update the database with it? I've read that I need to use a 'POST' but I'm not sure how to set it up. views.py file from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest from django.template import loader from .models import Contact def index(request): return HttpResponse("Hello, world. You're at the contacts app.") def list(request): contacts_list = Contact.objects.all() return render(request, 'index.html', {'contact_list':contacts_list}) def add(request): if request.method == 'POST': new_contact = Contact( firstname = request.POST['firstname'], lastname = request.POST['lastname'], age = request.POST['age'], phone = request.POST['phone'], email = request.POST['email'], gender = request.POST['gender'], ) new_contact.save() return redirect('/contacts/list/') return render(request, 'addform.html') def edit(request, cur_id): if request.method == 'GET': contact_to_edit = Contact.objects.get(id=cur_id) contacts_list = Contact.objects.all() return render(request, 'editform.html', {'cur_contact':contact_to_edit, … -
Customizing Django's many-to-many admin widget
I have a many to many field that contains ~7000 options and it is starting to take a long time to load the page when I want to edit or add new objects in the admin interface. I'm aware of the filter_horizontal or filter_vertical options to change the widget for many to many, but is there a way to block the widget from showing me those 7000 options? I only need to be able to add new ones (searching would be nice, but not required). -
Multiple models in a single get_queryset() to populate data in a template
I'm trying to push multiple data sets into a template, home.html, using class based views. I don't know if this is the right way or if there is a better way to do this. views.py class HomePage(ListView): template_name = 'home.html' context_object_name = 'result' def get_queryset(self): query1 = {} query2 = {} query3 = {} query1 = table1.objects.filter(username=self.kwargs['username']) query2 = table2.objects.filter(username=self.kwargs['username']) query3 = table3.objects.filter(username=self.kwargs['username']) return (query1, query2, query3) home.html {% for query1_data in result %} {% if query1_data.url %} <img src="{{query1_data.url}}"> {% endif %} {% endfor %} {% for query2_data in result %} {% if query2_data.text %} ... {% endif %} {% endfor %} It works but it seems like there should be a better way to do this. Thanks! -
Why am I getting error "an unexpected keyword argument 'choises'" in this case?
I am trying to make django models. This is my models.py I am getting this error: TypeError: init() got an unexpected keyword argument 'choises' class Quality(Enum): camrip = "CAMRip" TS = "Telesync" dvdrip = "DVDRip" tvrip = "TVRip" hdtvrip = "HDTVRip" bdrip = "BD-Rip" class Another(models.Model): quality = models.CharField(max_length = 30, choises = [(tag, tag.value) for tag in Quality]) -
Page not found [404] in Django
I am trying to get all the post, posted in the same category. So my url looking like this, '..../category/Sports' where sports is a category. But if I enter this url, I got page, not found. I have also a html file called category. I also made makemigrations and migrate a several times My views.py file: from .models import Post, Category .............. def CatView(request, cats): posts = Post.objects.filter(category=cats) return render(request,'category.html',{"cats":cats, 'posts':posts}) urls.py file: from django.urls import path from .views import * urlpatterns = [ path('',HomeView.as_view(), name='home'), path('article/<int:pk>', ArticleDetailView.as_view(), name='article_detail'), path('add-post/', Addblogview.as_view(), name='add_post'), path('add-category/', AddCategoryview.as_view(), name='add_category'), path('article/edit/<int:pk>', UpdatethePost.as_view(), name='add_task'), path('article/delete/<int:pk>', DeleteThePost.as_view(), name='delete_task'), path('category/<int:cats>', CatView, name='category'), ] If I change <str:cats> I ended up with ValueError Field 'id' expected a number but got 'Sports' My models.py file: from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date class Category(models.Model): name = models.CharField(max_length=255, default='uncategorized') def __str__(self): return self.name def get_absolute_url(self): return reverse('article_detail',args=str(self.id)) class Post(models.Model): title = models.CharField(max_length=255) title_tag=models.CharField(max_length=255) author = models.ForeignKey(User,on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add= True) category = models.ForeignKey(Category,on_delete=models.CASCADE) def __str__(self): return self.title + "|" + str(self.author) def get_absolute_url(self): return reverse('article_detail',args=str(self.id)) My category.html: {{cats}} -
nested custom simple template tag in django
I have a custom template tag as follows : @register.simple_tag() def math(operand1, operator, operand2): add = ['add', 'addition', 'plus'] sub = ['sub', 'subtraction', 'minus'] mul = ['mul', 'multiplication', 'multiply'] div = ['div', 'division', 'divide'] mod = ['mod', 'rem', 'remainder', 'modulus'] pow = ['pow', 'power', 'raiseto', 'powerof', 'exponent', 'exponentiation'] log = ['log', 'logarithm'] if operator in add: return operand1 + operand2 elif operator in sub: return operand1 - operand2 elif operator in mul: return operand1 * operand2 elif operator in div: return operand1 / operand2 elif operator in mod: return operand1 % operand2 elif operator in pow: return operand1 ** operand2 elif operator in log: return math.log(operand1, operand2) else: raise ArithmeticError(f'Couldn\'t find the operator {operator} in math function') And I want to perform a nested operation like the following : <h1>Marks : {% math {% math graph.cutoff_marks|get_dic_item:data "mul" 2 %} "sub" graph.cutoff_marks|get_dic_item:data %}</h1> How do I perform it?