Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle empty passed through a form in django?
I am working on my first django project and I encountered a problem that I could not find any viable solution. So, I am trying to create an e-commerce website. I created a basic search bar and I am trying to render everything that matches the input. The problem occurred at one of the edge cases. If I send an empty input, the following error is being raised: Exception Value: The view mainpages.views.search didn't return an HttpResponse object. It returned None instead. I tried to handle this, but I failed. I've searched for answers, but unsuccessfully. I sincerely appreciate your time! Code: views.py def search(request): if request.method == 'GET' and 'q' in request.GET: query = request.GET.get('q') try: if query: objects_list= ComputerScienceProducts.objects.filter( Q(name__icontains=query) ) if list(objects_list) is None: return render(request, 'search_error.html') else: return render(request, 'search_result.html', {"objects_list": objects_list}) except: return render(request, 'search_error.html') else: return render(request, 'search_error.html') template: {% block cont2 %} <div class="background"></div> <div class="inp"> <form action="{% url 'search_results' %}" method="get"> {% csrf_token %} <label> <i class="bi bi-search" style="position: absolute; margin-left: 15px;margin-top: 13px;"></i> <input type="text" placeholder="What are you looking for?" class="search" name="q"> </label> </form> </div> <div class="container" style="margin-top: 20px;"> {% endblock %} {% block content %} {% if objects_list %} {% for … -
send email verfication link using django-email-verification with celery
I am using django-email-verification for sending verification link to email of the user but it tales time to send email , i want to send mail with celery for the same to speed it up , please guide me how can i add celery configs? -
Django: html button referencing a foreign key
i'm quite new to Django and i'm stuck on foreignkeys here. I have seen multiple tutorials and read a lot of questions on here but i didn't really find an answer :/ So to explain the context: I have 2 models: class example(models.Model): creation_date = models.DateTimeField(auto_now = True) a = models.CharField(max_length=50) b = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class addexample(models.Model): creation_date = models.DateTimeField(auto_now = True) id = models.ForeignKey(Example, on_delete=models.CASCADE) c = models.DecimalField(max_digits=12, decimal_places=2) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) this is my example.html {% for item in example %} <tr> <td>{{ item.a }}</td> <td>{{ item.b }}</td> <td> <a class="btn btn-primary" href="/example2" role="button">Link</a> </td> </tr> {% endfor % So in my table there is a button that refers to a certain database id. So how do i proceed in my views.py? in other words if i click the button and go to that "subform" where i can add addiditions (in this case this means addexample.c). How would I retrieve the Foreign key of the button from the line that I just pushed? I know how to request the user_id but how do I request that ForeignKey of that button? Thanks a lot in advance! -
I am getting an a "TypeError" when trying to add a item to the database in Django
I am trying to add an item in the database but I keep getting the TypeError, what am i doing wrong please. I have the model class for it and I am using the Django ModelForm to implement the Create operation. Error Log Traceback (most recent call last): File "C:\Users\Habib\Documents\django\FIVERR\Alex_SMS\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\FIVERR\Alex_SMS\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\FIVERR\Alex_SMS\SMS\core\views.py", line 26, in Addproduct form = Addproduct() Exception Type: TypeError at /add-product/ Exception Value: Addproduct() missing 1 required positional argument: 'request' models.py class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() description = models.TextField() quantity = models.PositiveIntegerField() image = models.ImageField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name forms.py from django import forms from .models import * class Addproduct(forms.ModelForm): class Meta: model = Product fields = '__all__' views.py def Addproduct(request): form = Addproduct() if request.method == 'POST': form = Addproduct(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Products Added Successfully") return redirect('product') context = {"form":form} return render(request, "core/addstation.html", context) -
Django in production not loading JS files (CSS working)
Running an app in Django. When Debug=True it all works fine. When Debug=False most of the app works fine except from a few static files, from what I was able to understand js files. I run already python manage.py collectstatic and the css of the templates work, so the processs seems to have been succesful. Still though, a few JS files don't get loaded and this is fucking up my admin panel. This is the terminal error for the production environment (debug=False) [21/Feb/2021 17:38:00] "GET /admin/ HTTP/1.1" 200 7803 [21/Feb/2021 17:38:00] "GET /static/admin/css/dashboard.css HTTP/1.1" 200 380 [21/Feb/2021 17:38:00] "GET /static/admin/img/icon-changelink.svg HTTP/1.1" 200 380 [21/Feb/2021 17:38:09] "GET /admin/amonthatatime/post/ HTTP/1.1" 200 9867 [21/Feb/2021 17:38:09] "GET /admin/jsi18n/ HTTP/1.1" 200 3187 [21/Feb/2021 17:38:11] "GET /admin/amonthatatime/post/1/change/ HTTP/1.1" 200 35171 [21/Feb/2021 17:38:11] "GET /admin/jsi18n/ HTTP/1.1" 200 3187 [21/Feb/2021 17:38:11] "GET /summernote/editor/id_medley/ HTTP/1.1" 200 7148 [21/Feb/2021 17:38:11] "GET /summernote/editor/id_whatsapp/ HTTP/1.1" 200 7154 [21/Feb/2021 17:38:11] "GET /static/summernote/lang/summernote-en-US.min.js?_=1613929091381 HTTP/1.1" 200 27 [21/Feb/2021 17:38:11] "GET /static/summernote/lang/summernote-en-US.min.js?_=1613929091408 HTTP/1.1" 200 27 This is my settings.py from pathlib import Path from django.conf import settings from django.conf.urls.static import static import os import psycopg2 import dj_database_url import cloudinary # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development … -
How to improve the speed of bulk_update on a foreign key of a large table?
The following code is working but running very slow and timing out if I try it with too many PostalCode objects. The Address model has about 1 million objects which is taking forever to query every loop. Obviously I am doing this the wrong way so any help would be appreciated! This is my first time dealing with a large set of data. I looked at and attempted transactions (it did work, but still slow) but I am not sure how that would help in this situation. If it takes time to run that is ok, no one will be using it when I do this update periodically, but it can't down for 8 hours or something like that while this process runs. I know I can offload this with celery but that I haven't got that far in my learning yet and really need to understand these fundamentals first. Models: class Address(models.Model): name = models.CharField(max_length=200, blank=True, null=True) address = models.CharField(max_length=300, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) province = models.CharField(max_length=100, blank=True, null=True) postal_code = models.CharField(max_length=6, blank=True, null=True) class Meta: indexes = [ models.Index(fields=['postal_code',]), ] def __str__(self): return self.address class PostalCode(models.Model): postal_code = models.CharField(max_length=6, blank=True, null=True) address = models.ForeignKey('Address', on_delete=models.DO_NOTHING, … -
Django - deleting users with on_delete=models.CASCADE causes problems with signals.post_delete
We are using Django 3.1 for our websites. We have a model, User, which is related to two SiteProfile models for two websites, and is also related to other models such as Friend and UserEmailAddress. All the relations are with on_delete=models.CASCADE. We also have models.signals.post_delete signals for models such as Friend, to update the number of friends a user has, which is saved in one of the SiteProfile models. But the problem is, when deleting a user, the signal is called and then the SiteProfile object is saved, and then I get an exception for django.db.utils.IntegrityError - violations of foreign keys. We used to have the same problem with the UserEmailAddress model (a user's email address), which I fixed with the following code: def delete(self, *args, **kwargs): if ((self.is_staff) or (self.is_superuser)): warnings.warn('Can’t delete staff user.') return False else: with transaction.atomic(): for user_email_address in self.email_addresses.all(): user_email_address.delete() return_value = super().delete(*args, **kwargs) return return_value But I would like to know, is there a better way to delete a user with all its related objects which have on_delete=models.CASCADE, but without saving the counters in models.signals.post_delete to the database? Can I check something in models.signals.post_delete to know if the user is being deleted and then … -
Wagtail: Adding BaseSetting to ModelAdminGroup
I am trying to create edit the admin interface of Wagtail and grouping setting to make more sense. To do this I want to mix BaseSetting and ModelAdmin models within one submenu. I have two types of models for it: BaseSetting, that I use with @register_setting and models.Model, which then are displayed with ModelAdmin and modeladmin_register Currently I have separate apps for both and individually they are working just fine. However, I have noticed a problem. When usign ModelAdminGroup, apparently it can only take ModelAdmin classes into it. Contents of admin.py from wagtail.contrib.modeladmin.options import ( ModelAdmin, ModelAdminGroup, modeladmin_register, ) # Import app self model from .models import Brand # Import sidebar settings from site_settings from site_settings.models import SidebarSettings class BrandAdmin(ModelAdmin): """ Brand Admin model """ model = Brand menu_label = "Brands" menu_icon = "placeholder" add_to_settings_menu = False exclude_from_explorer = False list_display = ("brand_name", "affiliate_program", "contact",) search_fields = ("brand_name", "affiliate_program", "affiliate_link", "contact",) class Commercial(ModelAdminGroup): """ Group the """ menu_label = "Commercial" menu_order = 900 menu_icon = 'placeholder' items = (BrandAdmin, SidebarSettings) modeladmin_register(Commercial) For reference, here is the snippet of the setting imported: @register_setting class SidebarSettings(BaseSetting): skyscraper_ad = models.ForeignKey( 'wagtailimages.Image', blank=True, null=True, on_delete=models.SET_NULL, related_name='+' ) skyscraper_panels = [ ImageChooserPanel('skyscraper_ad') ] edit_handler = … -
filtering reviews according to product django
I want my reviews that are on that particular product to be shown only on that product not on any other . I do not know how to filter it. Recently it is showing all the reviews on every product. My models.py file is: class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product , on_delete=models.CASCADE, null=True) date = models.DateTimeField(auto_now_add=True) text = models.TextField(max_length=3000 , blank=True) rate = models.PositiveSmallIntegerField(choices=RATE_CHOICES) likes= models.PositiveIntegerField(default=0) dislikes = models.PositiveIntegerField(default=0) def __str__(self): return self.user.full_name my product models.py is: class Product(models.Model): title = models.CharField(max_length=110) slug = models.SlugField(blank=True, unique=True) status = models.CharField(choices=CATEGORY_CHOICES, max_length=10) price = models.DecimalField(decimal_places=2, max_digits=6) quantity=models.IntegerField(default=1) discount_price=models.FloatField(blank=True, null=True) size = models.CharField(choices=SIZE_CHOICES, max_length=20) color = models.CharField(max_length=20, blank=True, null=True) image = models.ImageField(upload_to=upload_image_path) description = RichTextField(max_length=1000) featured = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE) time_stamp = models.DateTimeField(auto_now_add=True) my product detail views.py is: class ProductDetailSlugView(ObjectViewedMixin,DetailView): queryset = Product.objects.all() context_object_name = "object_list" template_name = "product_detail.html" def get_context_data(self, *args ,**kwargs): context = super(ProductDetailSlugView , self).get_context_data(*args, **kwargs) context['reviews'] = Review.objects.all() # context['reviews'] = Review.objects.filter(product=self.request.product) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj # context['comments'] = Comment.objects.all() return context -
Why Mails sent with django and mailgun (smtp) to my gmail account don't show up in my gmail inbox yet it gets sent successfully?
I am sending emails using mailgun (smtp) to my Gmail account don't show up in my Gmail inbox yet it gets sent successfully. I am using django web development framework. I am using mailgun (smtp). I am still using the sandbox testing environment -
Correct Django Foreignkey setup with legacy database
I used python manage.py inspectdb > models.py to create models from my old SQL database. Workout.user_id is a foreign key to users table, but inspectdb lost this linking by making it just models.IntegerField(). Database looks like this: Users +----+------------+ | id | name | +----+------------+ | 1 | Bob | | 2 | Alice | | 3 | Tom | +----+------------+ Workout +---------+------------+------------+ | user_id | workout_id | date | +---------+------------+------------+ | 2 | 1 | 2021-02-18 | | 2 | 2 | 2021-02-20 | | 3 | 3 | 2021-02-21 | +---------+------------+------------+ And models.py comes out like this: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models class Users(models.Model): id = models.AutoField(primary_key=True) name = models.TextField(blank=True, null=True) class Meta: … -
Importing models to forms in Django
I am making a quiz web application and I want to create answers to questions from admin panel, not writing a code for each set of answers. How can I do that? forms: from django import forms ANSWER_CHOICES = [ ('1', 'First'), ('2', 'Second'), ('3', 'Third'), ] class AnswerForm(forms.Form): answer = forms.ChoiceField( label = '', required=False, widget=forms.RadioSelect, choices=ANSWER_CHOICES, ) models: from django.db import models class Questions(models.Model): title = models.CharField('Question', max_length=200) def __str__(self): return self.title -
Django Annotations - More efficient way?
In a class Based ListView I want to annotate each Post with the number of comments (this method works) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['approved_comments'] = Comment.objects.values('post_id').annotate(c_count=Count('post_id')).filter(approved=True) return context in my Template I do the following (which feels really inefficient) {% for comment in approved_comments %} {% if post.id == comment.post_id %} {{comment.c_count}} {% endif %} {% endfor %} This gets me the result I want but I'm struggling to find a better way to deliver this since this seems really redundant. I was trying to find a SO question that already deals with this but haven't found one so if you could point me to the link that would be helpful. Thanks in advance :) -
check to check DB tables exists in Django?
I write this form for the product, that's got all brand and then set choice list for brand input class ProductForm(forms.ModelForm): class Meta: BRAND_CHOICE = Brand.objects.all() model = Product fields = '__all__' widgets = { 'brand': forms.Select(choices=BRAND_CHOICE), } but I take error when run python manage.py migrate an error that I taken django.db.utils.OperationalError: no such table: app_product_brand So how can I check DB and if tables exist then make a query to Database? -
Advanced ordering with django ORM
With the following model (it is just an example for the sake of explanation) class Publisher(models.Model): name = models.CharField(max_length=300) class Book(models.Model): name = models.CharField(max_length=300) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, related_name='books') I would like to list all the publishers and orders them first by "whether they have at least one book published" and then by their name The closest I came up to is the following request Publisher.objects.all().annotate(nb_books=Count('books')).order_by('-nb_books', 'name').distinct() Unfortunately it is not exactly what I need since it will display all the publishers that have 5 books then all the ones that have 4 books then all the ones that have 3 published books etc. What I would need is to have all the publishers that have at least one book published in one bloc and then the ones that don't have any Is there a way I can achieve that ? -
Time complexity of query ,django
I have the following models : class Employee(models.Model): full_name = models.CharField(max_length = 64) title = models.CharField(max_length = 64) class Skill(models.Model): name = models.CharField(max_length = 64) class Candidate(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name="employee") skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name="skill",blank=True, null = True) class Job(models.Model): title = models.CharField(max_length = 64) skills = models.ManyToManyField(Skill, blank=True, related_name="Jobs") If the 'Employee' size table is N and 'Skill' size table is M and according to that the 'Candidate' size table is N*M, what is the time complexity of the following query ? title = "foo" job_skills = [1,..5] Candidate.objects.filter(employee__title = job.title).filter(skill__id__in = job_skills).values('employee').annotate(dcount = Count('employee')).order_by('-dcount')[:50] I read about the time complexity of queries in Django but because 'Candidate' table is linked to 'Employee' and 'Skill' tables , its confusing me to know the time complexity about this query. In addition, if the Employee object already had the skill attached, the time complexity will be better ? Or it depends on data size? -
Passing Values in POST Method
I am trying to pass the value or a variable using JS to my Django BackEnd. When click on a Like Button, I am getting the ID of the post and a variable called Iliked saying "yes" or "no" depending if the user already liked the clicked post or not. When I click on Like on Post 77 with my user Bar, I then get in console log : id = 77 Iliked = yes Since my API allows to pass the ID within its URL, all I care about is to pass the Iliked value in order to have my Views.py update the DB accordingly : document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('#likebtn').forEach(item => { item.addEventListener('click', () => { const id = item.getAttribute('data-id'); const Iliked = item.getAttribute('data-Iliked'); like(id, Iliked); }); }); }) function like(id, Iliked) { console.log (id) console.log (Iliked) fetch(`/like/${id}`, { method: 'POST', credentials: 'same-origin', headers:{ 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', }, body: JSON.stringify({ Iliked:'Iliked' }) }) .then(response => {return response.json()}) .then(data => { console.log (data) }) return false; } @login_required @csrf_exempt def like(request, id): if request.method == "POST": CurrentUser = request.user.id Iliked = json.load(request)['Iliked'] #Get data from POST request print("This is the JSON Iliked received from the front end : ", … -
Django 5 star rating system is not saving reviews and rating
I build a model for user reviews and rating. And made the form for my model , then I call the form in my views . When i click on button from detail page to get the "rate.html" it get me there but did not save the data from there and give me this error . IntegrityError at /product/new-shoes/rate/ NOT NULL constraint failed: products_review.user_id my models.py is: class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product , on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) text = models.TextField(max_length=3000 , blank=True) rate = models.PositiveSmallIntegerField(choices=RATE_CHOICES) likes= models.PositiveIntegerField(default=0) dislikes = models.PositiveIntegerField(default=0) def __str__(self): return self.user.full_name my forms.py is: class RateForm(forms.ModelForm): text = forms.CharField(widget=forms.Textarea(attrs={'class':'materialize-textarea'}),required=False) rate = forms.ChoiceField(choices=RATE_CHOICES, widget=forms.Select(),required=True) class Meta: model = Review fields= ('text', 'rate') my views.py is: class RateView(CreateView): form_class = RateForm template_name = 'rate.html' def form_valid(self, form): form.instance.product = Product.objects.get(slug=self.kwargs['slug']) return super().form_valid(form) def get_success_url(self): return reverse('products:detail', kwargs={'slug': self.object.product.slug}) and my rate.html is: {% extends "base.html"%} {% block content %} <form method="POST" action="" role="form" class="col s12"> {% csrf_token %} <div class="input-field col s12"> {{ form.rate }} </div> <div class="input-field col s12"> {{ form.text }} <label for="textarea1">Opinion</label> </div> <button type="submit" name="action" class="waves-effect waves-light btn"><i class="material-icons left">star</i>Rate</button> </form> {% endblock %} my urls.py for the view is: path('<slug:slug>/rate/', … -
How chek if user likes beat
I have BeatLike model (like): class BeatLike(Base): like_from = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='like_from', verbose_name=_("like from")) like_to = models.ForeignKey('Beat', on_delete=models.CASCADE, related_name='like_to', verbose_name=_("like to")) class Meta: db_table = "beats_beatlike" constraints = [models.UniqueConstraint(fields=["like_from", "like_to"], name="unique_beatlike")] verbose_name = _("Beat like") verbose_name_plural = _("Beat likes") ordering = ("-created_on",) def __str__(self): return f'LIKE FROM:{self.like_from} LIKE TO: {self.like_to}' and BEAT MODEL class Beat(Base): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, likes = models.ManyToManyField('self', through=BeatLike, related_name='beat_likes', verbose_name=_("likes"), symmetrical=False, blank=True) How to check if user likes a given beat. In this M2M report, I do not have access to 'beat.like_from' i can oly do 'beat.like_to' ... i want do smoething like this: {% if request user HAVE THIS BEAT IN LIKED%} UNLIKE {%else%} LIKE {%endif} -
Django: autonumbering in HTML
Im currently trying to figure out how to autonumber my tables in my html template. I can't seem to use the id in the database as it is not autoincrementing as it it is user dependant what they see, so the user would see not a correct ordering. Instead of seeing the table numbering go 1. 2. 3. it is 4. 8. 9. for example. Originally i have tried this, which gave me the wrong outcome as described above: template.html {% for item in x%} <tr> <td>{{ item.id }}</td> <td>{{ item.a}}</td> <td>{{ item.b}}</td> <td>{{ item.c}}</td> </tr> I have tried something with a while loop: template.html {% for item in x %} {% while z<= item %} {% z=z+1 %} <tr> <td>{{ z }}</td> <td>{{ item.a}}</td> <td>{{ item.b}}</td> <td>{{ item.c }}</td> </tr> {% endwhile %} {% endfor %} For your reference the model that these templates refer to: models.py from django.db import models from django.conf import settings class x(models.Model): creation_date = models.DateTimeField(auto_now = True) a = models.CharField(max_length=50) b = models.CharField(max_length=50) c = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Thanks in advance for your help! -
django report builder migrate
I'm following django report builder quick start manual: pip install django-report-builder - DONE Add report_builder to INSTALLED_APPS - DONE Add url(r'^report_builder/', include('report_builder.urls')) to url.py url patterns - DONE Ensure django.core.context_processors.static and django.core.context_processors.media are in TEMPLATE_CONTEXT_PROCESSORS - NOT DONE. The Django doc says these options are changed in Django 1.8 and I failed to find where and how do I ensure that. Sync your database. python manage.py migrate -error ModuleNotFoundError: No module named 'report_builder general' -
Django get non-translated values - django-translations
Ok, I am using django-translations to translate my models. Here is my example model: class Product(Translatable): name = models.CharField(verbose_name="Product",max_length=150) def __str__(self): return self.name class Meta: ordering = ['-id'] class TranslatableMeta: fields = ["name"] The default language is tr, turkish. LANGUAGES = ( ('tr', _('Turkish')), ('en', _('English')), ('nl', _('Netherlands')), ) LANGUAGE_CODE = 'tr' When someone visits the website, let's say in en language, when I retrieve an object in view, it automatically returns me the translated version of that object. But I need to compare the non-translated version of name with new name which may have changed so that I can update the translated version too. When I use context; with Context(product) as context: print("Before", translate.ACTIVE) context.reset() # Supposed to clear the translations print("After", translate.ACTIVE) It gives me: Before en After en What should I do? -
is there a method to fix javascript error anchorElement onclick?
i try to have a field , that when i click on , i will fill the filter form: in my function in views.py: def render(self, value): result_str = "134,123,432" num = 3 final_result = '<a href="#" onclick="filter(\'' + result_str + '\')"> articles</a>' return format_html(final_result) and in javascript : function filter(form,value) { var val= value.split(','); var arr= [] for (v in val) { arr.push({ "id":"id", "field":"id", "type":"string", "input":"text", "operator":"equal", "value": Number(v) }) } var rules_transform = { "condition":"OR", "rules": arr, "valid":true }; $('#builder').queryBuilder('setRules', rules_transform); $('#FormQueryBuilder').submit(); }; i cannot get the value of value , i have this error : Uncaught ReferenceError: filter is not defined at HTMLAnchorElement.onclick -
check to check DB tables exists in Django?
I write this form for the product, that's got all brand and then set choice list for brand input class ProductForm(forms.ModelForm): class Meta: BRAND_CHOICE = Brand.objects.all() model = Product exclude = ('crop_it', 'cropping') widgets = { 'brand': forms.Select(attrs={'class': 'form-control'}, choices=BRAND_CHOICE), } but I take error when run python manage.py migrate an error that I taken django.db.utils.OperationalError: no such table: app_product_brand So how can I check DB and if tables exist then make a query to Database? -
Comprobar en template de django si request.user es instancia de un modelo
Tengo dos modelos principales: cliente y vendedor, ambos con clave foránea del modelo User . Debo ocultar/mostrar información en el template según si el usuario que se loguea está relacionado con el modelo cliente o vendedor respectivamente. Así como existen comprobaciones del tipo... {% if request.user.is_authenticated %}, hay alguna que compruebe si es instancia de un modelo?? probé muchas formas de "isinstance " de Python, pero ninguna funcionó