Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selecting multiple options in a form and storing all of the choosen values inside a model using django
I am facing problem in Selecting multiple options in a form and storing all of the chosen values inside a model using Django python. I have created a form inenter code here forms.py file : class CustomerSignup(forms.Form): name = forms.CharField(label="Customer Name",widget=forms.TextInput(),required=True) phone = forms.CharField(widget=forms.NumberInput) address = forms.CharField(widget=forms.TextInput()) time =forms.DateTimeField(label="Time of Arrival",initial=datetime.datetime.today) guests = forms.CharField(label="Number of Guests",widget=forms.NumberInput) orderList=[ ('organic tomato salad','organic tomato salad'), ('Baked broccoli','Baked broccoli'), ('Spicy meatballs','Spicy meatballs'), ('Eggplant parmigiana','Eggplant parmigiana'), ('Grilled Caesar salad, shaved reggiano','Grilled Caesar salad, shaved reggiano'), ('Spicy Calamari and beans','Spicy Calamari and beans'), ('>Bacon wrapped wild gulf prawns','>Bacon wrapped wild gulf prawns'), ('Seared ahi tuna fillet*, honey-ginger sauce','Seared ahi tuna fillet*, honey-ginger sauce'), ('Grilled Caesar salad, shaved reggiano','Grilled Caesar salad, shaved reggiano'), ('Spicy Calamari and beans','Spicy Calamari and beans'), ('chettinad chicken','chettinad chicken'), ('italian salad','italian salad'), ('combo of slad with tuna','combo of slad with tuna'), ('fried chicken65','fried chicken65'), ('hakka noodels','hakka noodels'), ('fruit twist','fruit twist'), ('garlic chilly chicken','garlic chilly chicken'), ('cabbage salad','cabbage salad'), ('grlic bread with white soup','grlic bread with white soup'), ('lentils and chicken salad','lentils and chicken salad'), ('french toast','french toast'), ] order=forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(choices=orderList)) password = forms.CharField(widget=forms.PasswordInput()) confirm=forms.BooleanField() I have a model corresponding to this form as: models.py class Registration(models.Model): name = models.CharField(max_length=30) address = models.TextField() phone = … -
How to store multiple drop-down list selections in variables and use them to fetch data from Google Spreadsheet in Django?
I am creating a website that asks the user to select a subject, level, and medium and returns resources (stored in a Google Spreadsheet) based on the user's selections. When the user opens the website, they are welcomed with a HomePage and a link to get started. After clicking the link, they are brought to the SubjectPage, which prompts the user to choose a subject from the drop-down menu. After submitting their subject selection, they are taken to the LevelPage, which asks the user to select a level of expertise. After submitting their Level selection, they are taken to the last question, which asks the user to choose what medium they prefer for their resource. Finally, the user is taken to the Results Page where they are given a list of resources. So far, I have set up my pages and connected my project to the Google Spreadsheet I am using. However, I am having trouble figuring out how to carry the user's selections between pages and use the user's three selections to display information on the ResultsPage. Below, I have included screenshots and code that may be helpful. Please feel free to ask me for further clarification or more … -
Iterate over int in HTML?
Sorry if this is a silly question but I want to iterate over an integer attribute of an object and I'm just wondering if that's possible in HTML. So something sort of like: {% for review in reviews %} {% for r in review.rating %} <p>*</p> {% endfor %} {% endfor %} The review.rating attribute is an integer between 1 and 5. When I try something like i have above I get "'int' object is not iterable". Is there something like a foreach loop in strictly HTML or will I have to learn a bit of Javascript or something to do this? -
Can I use a function in a Django class-based view to determine template_name?
I'm trying to convert my function-based view into a class-based view to clean some things up in a Django 3 app. I've had no problem using get_context_data to work, but I can't figure out how to determine my template_name since it's normally determined from variables: from the function based view: def tour_page(request, page_safe_name, tour_id): site_name = request.META['HTTP_HOST'] s = Site.objects.get(domain=site_name) t = Tour.objects.get(pk=tour_id) page_location = 'tours/' + t.tour_safe_name + '/' + page_safe_name + '.html' ... return render(request, page_location, context) So.... I can do this with a function based view pretty easily. I'm a little confused on where in a class-based view I could (or even should?) do this. I've read some things about dispatch and potentially overriding get... but I'm not 100% sure where I should be doing this especially since I do some of this processing in the context: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) site_tour_data, s, t = self.get_site_tour_data() context.update( { 'site_safe_name': s.site_safe_name, 'site_name': s.site_name, 'site_tour_data': site_tour_data, 'tour_name': t.tour_safe_name, 'tour_id': t.id, 'domain': s.domain, } ) return context Is there either a way to grab it from the context or process these things out somewhere else in the loading of that particular page? Every other view works great since … -
Django shows "preview" of files like word document and powerpoint?
The websiote I'm developign allows user to upload files like word document, excel, powerpoint etc. Other users will be able to download these but I want to give them an option to open and view it on the site instead of forcing them to download..What is the best solution for this? Do i convert to pdf and embed it in the site? -
Django - Cannot resolve keyword 'slug' into field
When i click on my product this error appears. I already migrate the shop models and admin, and on the /admin i rename the products, slugs and descriptions. The error that i get when i try to go to the product page is this: Cannot resolve keyword 'slug' into field. Choices are: available, category, category_id, created, id, image, order_items, price, translations, updated I dont know what to do my migrations worked fine, and the server is running okay, until i click a product. shop/models.py : from django.db import models from django.urls import reverse from parler.models import TranslatableModel, TranslatedFields class Category(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200, db_index=True), slug = models.SlugField(max_length=200, db_index=True, unique=True) ) class Meta: # ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) class Product(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200, db_index=True), slug = models.SlugField(max_length=200, db_index=True), description = models.TextField(blank=True) ) category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) # class Meta: # ordering = ('name',) # index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) admin.py: from django.contrib import admin … -
How to add auto-escaped characters in Django template?
In my project I'm using a combination of Django template and Vue.js. I'm using Vue.js, so if a user registers a string that contains Mustache syntax, rendering it in a template can cause XSS. So, I'd like to use Django's AutoEscape feature to escape strings in Mustache syntax. If possible, I want to apply the filter to the whole project. Is there a way to add an auto escape character in Django? Or is there no choice but to apply a custom filter to each item? -
SQL Query to Django Query
I'm trying to figure out how can I convert below SQL query into Django query select main_project.name, (main_contacts.first_name) as Name, group_concat(main_property.property_id) as Properties, sum(main_property.super_area), sum(main_property.covered_area), (main_contacts.first_name||main_project.name) as CONPROP from main_project INNER join main_property on main_property.project_id = main_project.id INNER join main_property_owner ON main_property_owner.property_id = main_property.id INNER JOIN main_contacts ON main_contacts.id = main_property_owner.contacts_id group by CONPROP I've learned that it will be done using 'annotate' but somehow I'm unable to do it. -
Updating cart quantity not working properly due to Form in Template
I have been fighting to fix this bug for a long time, I have an item with variations s,m and l, when I try to add or remove in the order summary page it is only updated to the item.slug not the item variations. Adding the same item with different variations is working fine except that in the template order summary.html there is a tag with href to add to cart and remove a single item from cart which I think is the reason for the issue of not updating the quantity to the variant but updating to the item.slug, the addition to the cart is not reading variations. I have drawn arrows in the views and template where I think the reason for the error. I have also tried to add a post method in the order.summary.html template but it didn't work. (the reason I did this is that I have added the item variations from the product detail template through a post method, I have tried to do the same and it is illustrated below) To better clarify here is the models.py class Item(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100) slug = models.SlugField(unique=True) … -
Keep getting: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
I'm working on a password reset feature for my django application. I'm following along using this tutorial: https://www.youtube.com/watch?v=-tyBEsHSv7w&t=924s Everything works great but I get this error when I give the email and press enter on password-reset/: NoReverseMatch at /password-reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. I've done everything in the tutorial yet I still get this error. Thanks -
Only Admin can login but not the user i created in Users admin
Views.py def login_page(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) if 'next' in request.POST: return redirect(request.POST.get('next')) else: return redirect('/orderlist') else: form = AuthenticationForm() return render(request, "login.html",{'form':form}) urls.py app_name = 'accounts' urlpatterns = [ path('', login_page, name='login-page'), ] I have created a function for users to log in to my website. However, it only works if I login with the superuser admin account, otherwise it cannot login with the user that i created in Users admin. When I try to login with User i created in admin Users it says "Please enter a correct username and password. Note that both fields may be case-sensitive. ". -
How can I get current logged in user in django?
When I return request.user from login function, it returns currently logged in user. But, after logged_in when I redirect to other function(getuser) and return request.user from there, it retuns AnonymousUser. This works. It returns logged in user. class Login(APIView): def post(self, request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return HttpResponse(request.user) else: return Response(status=401) But, this won't. It returns AnonymousUser class Login(APIView): def post(self, request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('getuser') else: return Response(status=401) class getuser(APIView): def get(self, request): return HttpResponse(request.user) -
Django import export update field before export signal
I want to update my field before exporting the csv. I just found out about https://django-import-export.readthedocs.io/en/latest/getting_started.html#signals. Say i have a field named totalstudents that stores the total number of students in an empty coloumn before export, how will i do it? I get really confused everytime I have to use signals, so any help would be appreciated -
Why won't this Django TestCase test pass?
I am trying to write tests for an API. I'm having trouble with a couple of User model methods. The methods all work in development and production environments, but the test does not. Here is the test: def test_delete_user(self): USER_DELETED = 1 self.u = self.setup() result = User.delete_user(self.u, self.u.pk) # response self.assertEqual(result, USER_DELETED) # functionality self.assertIsNone(self.u) print(self.u) When I run this test, the return value USER_DELETED is correct, but the user object is not actually deleted. self.setup() returns a single created user. I can post this if it is needed, but the setup and teardown both work with various other tests in the UserTest class. Here is the model method being tested: @staticmethod def delete_user(requesting_user, user_id): # static variables USER_DELETED = 1 NOT_AUTHORIZED = 0 NO_USER = -1 user_to_be_deleted = User.get_user_from_user_id(user_id) if user_to_be_deleted == NO_USER: return NO_USER # check for authorization to delete if requesting_user != user_to_be_deleted: return NOT_AUTHORIZED user_to_be_deleted.delete() return USER_DELETED I also tried creating the user with the setup and then calling self.u.delete() instead of the custom method I have. This gives the same result: AssertionError: <User: test_user> is not None Can someone explain what I am doing wrong here? Thanks. -
User deletion in Django
I created a custom Account table in Django. I even created an email-based activation to activate an account. It is working fine. The problem arises when, while new registration, the user enters an email ID which does not belong to him, or when he enters an invalid email id, or when he doesn't receive any verification mail and is trying to register again. While doing so, Error pops up showing that the email already exists. So what I want is like if the account hasn't been activated, the account details must be removed completely from the table rather than just making is_active=False. Is there any method to do this? -
The view didn't return an HttpResponse object. It returned None instead error when video recording through HTML and Javascript
I have the following function in my view that is doing some background images treatment when we click on the SCAN button. The template is loaded correctly at first before clicking the SCAN Button. In the template (shown below) I have a <video> tag along with js that does webcam recording (even without the SCAN clicked). When I click on the scan button, I face the "The view didn't return an HttpResponse object. It returned None instead". I tried commenting everything related to the webcam recording (that is being done initially without clicking on SCAN), then clicked on scan and did not face this error. I found that the problem is caused by the javascript, since after commenting out the <script> tag, no errors appeared (video tag remained uncommented) Can you please help with this ? Kind regards, view.py def verifyContent(request): matched = False error = False context = { 'matched' : matched } if request.method == "POST": if request.POST.get("scan"): result = frame_detection() if result: search(request) return redirect('main:search') context = {'matched': matched, 'error': error} return render(request=request, template_name="main/verifyContent.html", context=context) verifyContent.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="myFile" name="infos"> <input type="submit" name="upload"> <input type="submit" name="scan" value="Scan"> </form> <h1>Webcam recording</h1> <video … -
Django TabularInline need search list sorted based on date to search faster
Please check the attached image. It has a Video page and a Target (Person) a TabularInline. So one video can have multiple persons associated with it. What I need to do is, whenever I will assign a Person to the Video it should appear first in the Select Person list. Basically every time I am selecting videos related to same Person and perform this operation but every time I have to search for Person. Instead if it appears on top of the list by job will be easy. This data is getting saved in Target model where there is created_at field from which we can sort it. Model details are below, Model: class Target(DFModel): person = models.ForeignKey( Person, models.DO_NOTHING, blank=True, null=True) video = models.ForeignKey( 'Video', models.DO_NOTHING, blank=True, null=True) reviewed = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True, help_text=datetime_help_text) class Meta: db_table = 'target' admin.py class TargetTabularInline(admin.TabularInline): model = Target raw_id_fields = ("person",) fields = ('person',) extra = 1 class VideoAdmin(BaseAdmin): inlines = [TargetTabularInline] readonly_fields = ('page_link', 'page_url', 'views', 'likes', 'dislikes', 'tags', 'video_url', 'thumb_url') list_display = ['title', 'targets', 'source', 'video_link', 'reviewed', 'category', 'sfw', 'upload_date', 'created_at'] search_fields = ('title', 'category', 'source__name', 'target__person__name', 'reviewed',) raw_id_fields = ("creator",) def video_link(self, obj): return format_html( "<a … -
Django singal update field when model objects are created in bulk
I have a model named FinancePending class FinancePending(models.Model): amountPaid=models.IntegerField TotalAmount=models.IntegerField AmountPending = models.IntegerField I will populate them using a csv which means that the objects will be creaeted in bulk. Now i want to update the amountpending field for all the objects respectively in a post_save method. But I cannot seem come up with the proper logic @reciever(post_save, sender = FinancePending) def createAmountPending(sender,instance, **kwargs): finance_pending = FinancePending.objects.update() amount_paid = FinancePending.objects.values_list('amountPaid', flat=True) amount_paid = list(amount_paid) total_amount = FinancePending.objects.values_list('TotalAmount', flat=True) total_amount = list(total_amount) # total - paid TotalFee = [float(s.replace(',', '')) for s in total_amount] AmountPaid = [float(s.replace(',', '')) for s in amount_paid] def Diff(li1, li2): return (list(set(li1) - set(li2))) amount_pending = Diff(TotalFee, AmountPaid) i = 1 while i <= len(amount_pending): FinancePending.objects.filter(invoiceNumber=i).update(AmountPending=str(amount_pending[i])) i = i + 1 instance = FinancePending.objects.all() instance.refresh_from_db() instance.post.save() -
Django - compare user objects by field
I have a Dictionary view that shows the list of words created by a specific (special) user: class Dictionary(FilterView): model = Word template_name = 'vocab/dictionary.html' context_object_name = 'dict_list' paginate_by = 15 filterset_class = WordFilter strict = False def get_queryset(self): qs = self.model.objects.filter(user__username__iexact='special_user') return qs def get_object(self): queryset = qs pk = self.kwargs.get('pk') if pk is None: raise AttributeError('pk expected in url') return get_object_or_404(queryset, pk=pk) Now I want any user to be able to come to this page and add any word that they want to, like this: def custom_create_word(request, object): if request.method == 'POST': pass if request.method =="GET": from .forms import WordForm from .models import Word word = Word.objects.get(pk=object) user = request.user target_word = word.target_word source_word = word.source_word deck_name = "My Words" fluency = 0 new_word, created = Word.objects.get_or_create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:dict')) Everything works as expected. But in the template I want the button to look different depending on whether the logged in user already has this word in their own list (which should be judged by if target_word is the same). My template looks like this: <tr> {% for word in dict_list %} <td>{{word.target_word}}</td> <td>{{word.source_word}}</td> <td> {% if user_word %} <a href="" class="btn btn-success btn-sm" >Added</a> … -
proto.teacher.MultipleObjectsReturned: get() returned more than one TeacherReport -- it returned 2
i'm trying to fetch data from a django model and then store it into another django model but i'm getting this error, can anyone tell how to resolve it. i'm uploading the code with it. lt, created = TeacherReport.objects.get_or_create( Teacher_ID=teacher[i], ) if not created: lt.Teacher_Name = tname[i] lt.save() -
Issue with Django: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
Any idea what's causing this error? I've tried commenting out each app in INSTALLED_APPS one by one to see which one isn't loading, but I get the same error no matter which one is commented out. Traceback (most recent call last): File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/main.py", line 18, in django.setup() File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 953, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in class AbstractBaseUser(models.Model): File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Django foreign key relation do not conserve object identity
I have a model Message with a foreign key to AUTH_USER_MODEL (users model). class Message(models.Model): SUBJECT_MAX_LENGTH = 120 recipient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='received_messages', null=True, blank=True, verbose_name=_("recipient")) simple so far. Question is, when I add a message to a given user by using the related_name: m=Message.objects.create() user1.received_messages.add(m) then: m.recipient is user1 # True however: user1.received_messages.first() is m # False I don't understand why the identity is not conserved both ways. Thanks -
API request from Angular App to Django REST API - blocked by CORS
I have a working Angular app that gets data from a Django REST api. The api requests are successful when I make requests to some endpoints but fail due to being blocked by CORS on other endpoints. My CORS configuration in django app: Whitelist: CORS_ORIGIN_WHITELIST = ( 'http://localhost:4200', # my angular app 'http://localhost:8080', ) Middleware: MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ] Installed Apps: INSTALLED_APPS = [ ... 'corsheaders', ] When I make this get request in my angular app, it succeeds and i get back the result i expect Angular request: public getProviders(searchParams: ProviderSearchParams): Observable<ProviderSearchResult> { const p = this.serializeParams(searchParams, new HttpParams()); return this.http.get<any>(`${this.base_url}/providers/`, {params: p}) .pipe(map(this.deserializeAs(ProviderSearchResult))); } Django Endpoint # urls path('', views.ProviderList.as_view(), name="api_provider_list"), # views class ProviderList(generics.ListAPIView): """ View all providers. """ queryset = Provider.objects.filter(is_accepted=True) filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] filterset_fields = ['name', 'branches__city', 'branches__area'] search_fields = ['name', 'branches__name', 'branches__city', 'branches__area'] ordering_fields = ['name', 'created_date'] pagination_class = PageNumberPagination def get_serializer_class(self): if self.request.user.is_staff: return AdminProviderSerializer return PublicProviderSerializer However, it seems to fail with error blocked by CORS when i make a request to a generics.RetrieveUpdateDestroyAPIView. Here is an example: Angular request: public getProviderBySlug = (slug: string): Observable<Provider> => this.http.get<any>(`${this.base_url}/providers/${slug}`) .pipe(map(this.deserializeAs(Provider))) Django Endpoint # urls path('<slug:slug>/', views.ProviderDetail.as_view(), name="api_provider_details"), # views … -
What is the best way to set ModelAdmin defaults in Django?
ModelAdmin.list_max_show_all defaults to 200. ModelAdmin.list_per_page to 100. Say I want to change those defaults to 500 and to 25. I also want all my ModelAdmin classes to have access to js/admin.js and css/admin.css. Is the best way to do that to create my own MyModelAdmin class and then have all my other ModelAdmin classes inherit from that one? class MyModelAdmin(admin.ModelAdmin): list_max_show_all = 500 list_per_page = 25 class Media: js = ( settings.STATIC_URL + 'js/admin.js' ) css = { 'all': (settings.STATIC_URL + 'css/admin.css',) } @admin.register(Book) class BookAdmin(MyModelAdmin): model = Book ... @admin.register(Author) class AuthorAdmin(MyModelAdmin): model = Author ... # This also inherits from django.contrib.auth.admin.UserAdmin @admin.register(CustomUser) class CustomUserAdmin(MyModelAdmin, UserAdmin): model = CustomUser ... Is there any downside to doing this? -
Django error where the form.as_p does not work [closed]
http://dpaste.com/1FZQE3S this is the traceback from the code, I dont think code needs to be posted