Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering querysets in Django Rest Framework
Today i have a really strange behoviour. I have added a custom mixin to my User Viewset to filter the users by username and password and other fields. the code look like the following: class MultipleFieldLookupMixin(object): """ Apply this mixin to any view or viewset to get multiple field filtering based on a `lookup_fields` attribute, instead of the default single field filtering. """ def get_object(self): queryset = self.get_queryset() # Get the base queryset queryset = self.filter_queryset(queryset) # Apply any filter backends filter = {} for field in self.lookup_fields: if self.kwargs[field] is not None: # Ignore empty fields. filter[field] = self.kwargs[field] obj = get_object_or_404(queryset, **filter) # Lookup the object return obj class UserView(MultipleFieldLookupMixin, viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_fields = ['username', 'pwd', 'token_confirm', 'email', 'token_cng_pwd'] i would like the list operation to filter the queryset in every given parameter (so None if none is avalable and all if all are available). But the list endpoint continues to show every user to me, without filtering them. Where am i wrong? Do i have to manually set a filterbackend? am I doing some stupid mistake? Thanks a lot -
Django Like button working for all posts, but not showing with the change of button in Homepage
I have this like button, it works fine for the first post, but for all the other posts below it, it doesn't show any change of button instead the button changes in the first post, but the like gets registered for those specific posts without changing the like for first post. Its quite a weird situation to explain as I am not much familiar with js. view def like_post(request, slug): user = request.user post = get_object_or_404(Post, slug=slug) is_liked = False if user in post.likes.all(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True # return redirect('posts:myhome') context = { 'post':post, 'is_liked':is_liked, 'total_likes':post.total_likes() } if request.is_ajax(): html = render_to_string('posts/like_snippet.html', context, request=request) return JsonResponse({'form': html}) like snippet.html <form action="{% url 'posts:like_post' post.slug %}" method="post">{% csrf_token %} {% if user in post.likes.all %} <a id="like" name="post_id" value="{% url 'posts:like_post' post.slug %}" class="like-btn">{{ post.likes.count}} <i class="fas fa-heart fa-lg" style="color: red;"></i></a> {% else %} <a id="like" name="post_id" value="{% url 'posts:like_post' post.slug %}" class="like-btn">{{ post.likes.count}} <i class="far fa-heart fa-lg" style="color: red;"></i></a> {% endif %} </form> html div function in homepage <div id="like-snip" class="like_snippet mt-1"> {% include 'posts/like_snippet.html' %} <div> js $(document).ready(function(event){ $(document).on('click', '.like-btn', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: pk, data: {'csrfmiddlewaretoken': … -
How can i use annotate in the ModelSerializer
I have a FooModelSerializer. I want to show count of some field which is can show with Model.objects.annotate(c=Count(some_field)). So if i write queryset as above as in the ModelViewSet, works correctly but another BarModelSerializer include this FooModelSerializer. As i dont write queryset in BarModelSerializer, FooModelSerializer won't show count of some field. Now that i want to show count of some field when FooModelSerializer calls. So how can i override queryset in ModelSerializer. I've tried override to to_representation(instance) function but instance parameter is not query so i cant add annotate. FooModelSerializer(serializers.ModelSerializer): c = serializers.IntegerField() class Meta: model = Foo fields = ('some_field', 'annotate_field', 'c') BarModelSerializer(serializers.ModelSerializer): foo = FooModelSerializer() class Meta: model = Bar fields = ('foo',) -
How to filter Django Form dropdown for currently logged-in user (Class Based Views)
I have the two models, Fillup and Car, and the Fillup model has a Foreign key (for recording times you fill up your car with gas, for example), and in the form to create a new Fillup, I want to limit the dropdown for the Car field to only Cars associated with the current user, but right now it's showing all users cars. I've seen a couple solutions that involve passing the request into the form from the view but I can't figure out how to do it using the Class Based Views I currently have set up. Here's my code: models.py class Fillup(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) date = models.DateField(default=date.today) price_per_gallon = models.FloatField() trip_distance = models.FloatField() gallons = models.FloatField() car = models.ForeignKey('Car',on_delete=models.CASCADE) @property def total_sale(self): return round(self.price_per_gallon*self.gallons, 2) @property def mpg(self): return round(self.trip_distance/self.gallons, 4) class Car(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=25) make = models.CharField(max_length=25) model = models.CharField(max_length=25) model_year = models.IntegerField(choices=MODEL_YEARS) status = models.BooleanField(choices=STATUS) def __str__(self): return self.name views.py class FillupListView(ListView): model = Fillup context_object_name = 'fillup_list' ordering = ['-date'] # NOT USING THIS YET # def get_queryset(self): # return Fillup.objects.filter(user=self.request.user) class CarListView(ListView): model = Car ordering = ['name'] class NewFillup(LoginRequiredMixin,CreateView): model = Fillup fields = ('date', 'price_per_gallon', 'trip_distance', 'gallons', … -
invalid dsn: invalid connection option "postgis_extension"
On localhost everything is working fine. But I am having problems with https://rossdjangoapp.herokuapp.com/. I tried to follow this tutorial https://medium.com/the-geospatials/deploy-geodjango-application-to-heroku-in-2019-part-3-41ca4535f377. I got the below error messages. remote: -----> App not compatible with buildpack: https://github.com/peterkeen/heroku-buildpack- remote: ! The GDAL, GEOS and PROJ binaries and BUILD_WITH_GEO_LIBRARIES functonality are now deprecated. remote: ! An alternative buildpack to enable GDAL, GEOS and PROJ use is available here - https://github.com/heroku/heroku-geo-buildpack remote: ### WARNING: THIS BUILDPACK HAS BEEN DEPRECATED remote: Please check https://git.io/fj5QW These are the build packs I now have. I want to add map functionality to my site. settings.py import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal300.dll' import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = ['rossdjangoawesomeapp.herokuapp.com', 'localhost', '127.0.0.1', 'localhost:8000'] INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'django_comments', 'shops', 'django.contrib.gis' ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_project3.urls' … -
DRF nested serializer
im using django rest framework to build apis . i have 2 classes related with onToOne relationship and i want to serialize data of the annonce_demande class , and create a post method in my endpoint , but i got problems with the nested serializer (fiche_annonce class). i think the problem is in the create method of the serializer. plz help me and thanks. class fiche_annonce(models.Model): ville_distination = models.CharField(max_length=50) lieu_depart = models.CharField(max_length=50) lieu_arrive = models.CharField(max_length=50) date_depart = models.DateTimeField(max_length=50,) date_arrive = models.DateTimeField(max_length=50) is_accepted = False visiblty = False class annonce(models.Model): compte = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) num_tele = models.IntegerField() ville = models.CharField(max_length=30) bagages = models.CharField(max_length=12, choices=[x.value for x in type_bagages]) comment = models.TextField(max_length=200) fiche = models.OneToOneField(fiche_annonce, on_delete=models.CASCADE) visiblty = False created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Ad_Serializer(serializers.ModelSerializer): fiche = fiche_Serializer() compte = serializers.PrimaryKeyRelatedField(queryset=user.objects.all().filter(is_active=True), read_only=False, required=False, default=None, allow_null=True) class Meta: model = annonce_demande fields = ['compte', 'num_tele', 'ville', 'bagages', 'comment', 'fiche', 'visiblty', 'get_created_time', 'get_updated_time' ] #def create(self, validated_data): # return annonce_demande.objects.create(**validated_data) #def validate_compte(self, val): # return self.context['request'].user def create(self, validated_data): print(validated_data) fiche_data = validated_data.pop('fiche') #print("---") #print(fiche_data) #print("---") print(validated_data) ad = annonce_demande.objects.create(**validated_data) print(ad) fiche_annonce.objects.create(**fiche_data) return ad class UserLoginView(APIView): #queryset = user.objects.all() permission_classes = [AllowAny] serializer_class = UserLoginSerializer #lookup_field = 'id' def post(self, request): serializer … -
Django Insert User_id as foreignKey in Post entry
I'm trying to save the user_id as a foreign key as the user publishes a new post. In a lot of other articles a suggested solution is: user= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) If I do that, I get: IntegrityError at /createPost/Error: NULL-Value in column »user_id« verletzt Not-Null-ConstraintDETAIL: Failed line contains (13, hhjkjh, hjkhkjhkj, https://www.google.de, 2020-06-06, hhjkjh, null). But the user is logged in. # my models.py from django.db import models from django.conf import settings from django.utils import timezone from slugify import slugify from django.contrib.auth.models import User class UserEntry(models.Model): user= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title= models.CharField(max_length=500) content= models.TextField() link = models.URLField(max_length=200) date_published= models.DateField(default=timezone.now) url= models.SlugField(max_length=500, unique=True, blank=True, editable=False) def save(self, *args, **kwargs): self.url= slugify(self.title) super(UserEntry, self).save(*args, **kwargs) #my forms.py class UserEntryForm(forms.ModelForm): class Meta: model= UserEntry fields= ["title", "content", "link"] #my views.py def userposts_create_view(request): form= UserEntryForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return HttpResponseRedirect("/") context= {'form': form, } return render(request, '../templates/userposts-create-view.html', context) #and my html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in.</p> <p>Go to your page <a href="{{user.username}}">here</a></p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %} <form enctype="multipart/form-data" method="POST" action=""> … -
Required parameter name not set, ValueError at /profile/
I am having an error in my Django app.Whenever I try to access the profile section of my website, it throws 'ValueError at /profile/' Error. I am using S3 buckets to store the profile images. All other pages are working fine but somehow the profile page which shows the image throws this error. I have set the aws access key and secret access in my settings.py file. ValueError at /profile/ Required parameter name not set Request Method: GET Request URL: http://localhost:8000/profile/ Django Version: 3.0.3 Exception Type: ValueError Exception Value: Required parameter name not set Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site- packages\boto3\resources\base.py in __init__, line 118 Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.1 Python Path: ['C:\\Users\\Admin\\Desktop\\Django Projects\\corey_attendance\\ccl_project', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python38\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python38\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python38', 'C:\\Users\\Admin\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\Pythonwin'] Server time: Sat, 6 Jun 2020 17:00:37 +0000 Error during template rendering In template C:\Users\Admin\Desktop\Django Projects\corey_attendance\ccl_project\attendance\templates\attendance\base.html, error at line 6 Required parameter name not set 1 {% load static %} 2 <!DOCTYPE html> 3 <html> 4 <head> 5 <link href="https://fonts.googleapis.com/css?family=Advent Pro" rel="stylesheet" type="text/css"> 6 <link href="https://fonts.googleapis.com/css?family=Tenali Ramakrishna" rel="stylesheet" type="text/css"> 7 <link href="https://fonts.googleapis.com/css?family=Andika" rel="stylesheet" type="text/css"> 8 <!-- Required meta tags --> 9 <meta charset="utf-8"> 10 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 11 12 <!-- Bootstrap CSS --> 13 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" … -
Class based and function based views
Is it recommended to mix both class and functions within the views? I am trying to work on CustomExtendedUser at this moment in time -
Python relative path 2 folders up
I got the following folder structure ProjectX/Data and ProjectX/mysite/core Inside ProjectX/mysite/core is my python script and i want to create a file inside ProjectX/Data. at the moment im using: f = open(f'/var/home/USER/Documents/ProjectX/DATA/{user_name_directory}/data_text.txt','w') if i use f = open(f'~/ProjectX/DATA/{user_name_directory}/data_text.txt','w') it wont work. I also want to run this django project on a windows machine. How can i write relative path from the main ProjectX folder when the script is two folders in? How do i get 2 folders up and then inside DATA? -
django admin permission based on model values
my models.py: class post(models.Model): title=models.CharField(max_length=255) country=models.CharField(max_length=255) I want to add a custom permission in the admin for example: -can edit only posts of uk -can see only posts of fr -can delete only posts of usa -
Django how to distinguish whether the password is wrong or the "user.is_active" is false?
I use user = auth.authenticate(username=username, password=password),but I can't distinguish whether the password is wrong or the user.is_actave is false,because both of them the user is None. -
Running psql on Amazon Django Lightsail
I am trying to run "psql" on Amazon Lightsail, Django instance. psql Password for user bitnami: psql.bin: FATAL: password authentication failed fo r user "bitnami" It doesn't work even though I got bitnami's password through cat bitnami_application_password Upon further review, it seems that there are multiple types of psql installed on the Amazon Lightsail instance. Any suggestions? -
Django filter exact match for multi field
I'm using Django filters in my project. I have the below models, where a composition (work) have an instrumentation field which is a through model. Each instrumentation has several instruments within it. class Work(models.Model): instrumentations = models.ManyToManyField(Instrument, through='Instrumentation', blank=True) class Instrument(models.Model): name = models.CharField(max_length=100) class Instrumentation(models.Model): players = models.IntegerField(validators=[MinValueValidator(1)]) work = models.ForeignKey(Work, on_delete=models.CASCADE) instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE) view.py: import django_filters class WorkFilter(django_filters.FilterSet): instrument = django_filters.ModelMultipleChoiceFilter(field_name="instrumentation__instrument", queryset=Instrument.objects.all()) My filter works fine: it grabs all the pieces where there is the instrument selected by the user in the filter form. Nevertheless, I'd like to also add the possibility of filtering the compositions with that exact instruments. For instance, if a piece contains violin, horn and cello and nothing else, I'd like to get that, and not a piece written for violin, horn, cello, and percussion. Is it possible to achieve that? I'd also like the user to choose, from the interface, whether to perform an exact search or not, but that's a secondary issue for now, I suppose. -
django 3 registration witn confirm email
Задача, как используя базовые библиотеки настроить отправку письма на почту для подтверждения Email, почти все что я нашел касалось django 2, и не сработали нужным образом сейчас у меня есть views.py class SignUp(CreateView): form_class = CreationForm success_url = reverse_lazy('login') template_name = 'signup.html' она подключена к форме в forms.py class CreationForm(UserCreationForm): email = forms.EmailField(required = True ) class Meta(UserCreationForm.Meta): model = User fields = ('first_name', 'last_name', 'username', 'email') все работает, но не отправляет на почту письмо для подтверждения email на почту -
Why does initial value overwrite existing data on django forms?
I'm trying to add an initial value to a form. But the initial value is overwriting the actual form data. class TempForm(forms.ModelForm): initial = {'invoicedate' : datetime.now().date()} def __init__(self, *args, **kwargs): kwargs['initial'] = self.initial super(TempForm, self).__init__(*args, **kwargs) For example Invoice ABC has an actual invoicedate of 1/1/2020 but if I open the page for that invoice right now the field displays 6/6/2020 (today's date). The form is called from an UpdateView's custom get_form_class method. According to the docs the initial value is used "when rendering this Field in an unbound Form". So I'm wondering if my form is unbound perhaps. How do I check if a form is unbound or not? And is there any issue with how I established initial values here? -
manage.py runserver error No module named wsgi
I tried to install a django app. When I run python manage.py runserver, the following error occurred . File "....\Anaconda3\envs\python27\lib\site-packages\django\utils\module_loading.py", line 20, in import_string module = import_module(module_path) File "...\Anaconda3\envs\python27\lib\importlib__init__.py", line 37, in import_module import(name) django.core.exceptions.ImproperlyConfigured: WSGI application 'walkthedinosaur.wsgi.application' could not be loaded; Error importing module: 'No module named wsgi' I looked at those answers relevant to my issue at stackoverflow, django.core.exceptions.ImproperlyConfigured: WSGI application 'application' could not be loaded, django.core.exceptions.ImproperlyConfigured: WSGI application '{project_name}.wsgi.application' could not be loaded; Error importing module, django error: ImproperlyConfigured: WSGI application etc and tried those methods but the error was not solved. I'm a completely new learner of Django. Could you help me? Here is the content of my settings.py import config import os PROJECT_PATH = os.path.dirname(os.path.abspath(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': config.CONFIG_PATH_PREFIX + '/jobs.db', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: USPTO_2005-2013_data 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string … -
How to debug the validation of a form in Django
I have basic model view and form instances which I'd like to push data to the database with (like roughly 20-25 inputs). Now in development it raises the following error: The foo_bar could not be created because the data didnt validate. How can I print the field/data which couln't be validated so I can debug it as easy as possible? forms.py from django import forms from .models import add_foo class fooBar(forms.ModelForm): class Meta: model = add_foo fields = '__all__' models.py from django.db import models class add_foo(models.Model): instrument = models.CharField(max_length=100, blank=False, null=True) sector = models.CharField(max_length=100, blank=True, null=True) [...] [...] class Meta: db_table = 'foo_bar' views.py from django.shortcuts import render, HttpResponse, redirect from .models import add_foo from .forms import fooBar def add_foo(request): if request.method == 'POST': form = fooBar(request.POST) if form.is_valid(): form.save() else: print('form invalid') return redirect('/calculator/') Which prints form invalid accordingly... but obviously can't tell me where the issue occurs. According to the variables assigments each field contains data. So I assume it is about the dataformat or something. -
How to avoid form submission in Django on pressing enter key?
I wish to prevent form submission on pressing enter in django. I have searched over internet, and found jquery/javascript based solution. I have tried to use the below js snippet but it is not working. Can anyone help me out here? I am using Django==2.2 version. <script> document.getElementById('name').addEventListener('keypress', function(event) { if (event.keyCode == 13) { event.preventDefault(); } }); </script> -
Django NoReverseMatch :Reverse for 'blog_detail' with arguments '(1,)' not found
I created a topic as a categories for blog project. I pointed 'topic' as a PK to my model It is successfully to access by the follow path: http://127.0.0.1:8000/django/1 and http://127.0.0.1:8000/IDE/2 django and IDE is the topic of my model from django.shortcuts import render, get_object_or_404 from .models import Blog, Topic from django.views.generic import DetailView def post_list(request, topic_slug=None): topic= None topics = Topic.objects.all() blogs = Blog.objects.filter(available=True) if topic_slug: topic = get_object_or_404(Topic, slug=topic_slug) blogs = blogs.filter(topic=topic) return render(request, 'topiclist.html', {'topics': topics, 'topic':topic, 'blogs': blogs, }) class BlogDetail(DetailView): model = Blog template_name ='detail.html' from django.urls import path from . import views from .views import BlogDetail urlpatterns = [ path('<slug:topic_slug>/', views.post_list, name='post_list'), path('<slug:topic_slug>/<int:pk>/', BlogDetail.as_view(), name='blog_detail'), ] from django.db import models from ckeditor.fields import RichTextField from django.urls import reverse class Topic(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, default='self.name', db_index=True, unique=True) class Meta: verbose_name = 'topic' verbose_name_plural = 'topics' def __str__(self): return self.name def get_absolute_url(self): return reverse('post:topiclist', args=[self.slug]) class Blog(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) content = RichTextField() topic = models.ForeignKey(Topic, default=1, on_delete=models.SET_DEFAULT) available = models.BooleanField(default=True) class Meta: verbose_name = 'post' verbose_name_plural = 'posts' def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) It show the error NoReverseMatch at /django/ Reverse for 'blog_detail' with … -
Confirmation before posting with Django CreateView Template
Is there a simple way to use Django's CreateView Template to ask the user to confirm the new post is valid or show them a preview of the post before actually posting it to the feed? -
How to make OR conditions while filtering Django Models?
I want to make a query like this: Mymodel.objects.filter(description__icontains='something' or title__icontains='something') However using the or statement does not work. Putting a comma makes it an and statement. How do I solve this? -
Django Why is one field created when I apply migrations?
There are models, why after python manage.py makemigrations is created only by 1 field in migrations, how to fix it? I tried doing manage.py migrate --fake zero, and doing the migrations again, but nothing.The app is registered in settings. from django.db import models from django.urls import reverse class Category(models.Model): image = models.ImageField(default='default.png', upload_to='category_image'), title = models.CharField(max_length=50, db_index = True), def __str__(self): return self.title def get_absolute_url(self): return reverse('category_detail_url', kwargs={'title': self.title}) class Provider(models.Model): name = models.CharField(max_length=50, db_index = True), phone_number = models.CharField(max_length=12, db_index = True), address = models.CharField(max_length=50, db_index = True), def __str__(self): return self.name class Product(models.Model): title = models.CharField(max_length=50, db_index = True), receipt_date = models.DateTimeField(auto_now_add=True, blank=True), quantity_stock = models.IntegerField(), quantity_store = models.IntegerField(), purchase_price = models.IntegerField(), image = models.ImageField(default='default.png', upload_to='product_image'), provider = models.ForeignKey(Provider, null = True ,related_name='to_provider',on_delete=models.CASCADE), category = models.ForeignKey(Category, null = True ,related_name='to_category',on_delete=models.CASCADE), def __str__(self): return self.title def get_absolute_url(self): return reverse('product_detail_url', kwargs={'title': self.title}) class Sale(models.Model): product = models.ForeignKey(Product, related_name='to_product',on_delete=models.CASCADE), date_of_sale = models.DateTimeField(auto_now_add=True, blank=True), quantity_goods_sold = models.IntegerField(), retail_price = models.IntegerField(), def __str__(self): return self.id -
how do I fix Background image giving invalid property error in django 3
I'm doing the traversy media django course. I tried a lot of fixes, but due to some reason in my browser inspect tools, the style.css is not what I just edited. I stopped the server, did collectstatic ran it again but in my browser inspect tools the background image just doesn't work. Even the style.css it shows isn't the same. In VSCode and in both my static folders, I can see that the css is edited but just not working....! I am just clueless can anyone help?? Here are the codes for insight: My settings.py in btre: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'btre/static') ] In VSCode #showcase { background: url(/static/img/showcase.jpg) no-repeat top center fixed; background-size: cover cover; position: relative; min-height: 650px; color: #fff; padding-top: 6rem; } In ROOT static folder: #showcase { background: url(/static/img/showcase.jpg) no-repeat top center fixed; background-size: cover cover; position: relative; min-height: 650px; color: #fff; padding-top: 6rem; } In browser inspect: #showcase { background: url(../img/showcase.jpg) no-repeat top center fixed/cover; position: relative; min-height: 650px; color: #fff; padding-top: 6rem; } -
openCV display name
The code was running perfectly. But when I added csv part to create a sheet, the name of a person is not being displayed all the time while recognizing the face. Naming is popping sometimes only. What's the issue. Can anyone help? And I also want to name the file in particular date. def takeAttendance(request): connector = sqlite3.connect('smartAttendance.db') cursor = connector.cursor() file = "face_recognizer/trainedDataset.yml" if not os.path.isfile(file): print("Trained data not found") exit() cascade_Classifier = cv2.CascadeClassifier('E:/Django/smartAttendance/haarcascade_frontalface_default.xml') cam = cv2.VideoCapture(0) Face_recognizer = cv2.face.LBPHFaceRecognizer_create() Face_recognizer.read(file) record = {} while True: ret, photo = cam.read() graying_img = cv2.cvtColor(photo, cv2.COLOR_BGR2GRAY) faces = cascade_Classifier.detectMultiScale(graying_img, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(photo, (x,y), (x+w,y+h), (0,255,255),3) ids, conf = Face_recognizer.predict(graying_img[y:y + h, x:x + w]) if ids in record: continue record[ids] = "Present" cursor.execute("SELECT name FROM students where id = (?);",(ids,)) output = cursor.fetchall() name = output[0][0] if conf < 100: cv2.putText(photo, name, (x+2,y+h-5),cv2.FONT_HERSHEY_COMPLEX, 1, (150,255,0),2) with open('attendance.csv', 'a', newline='') as f: fieldnames = ['Name','Status'] thewriter = csv.DictWriter(f, fieldnames=fieldnames) thewriter.writerow({'Name':name,'Status':"Present"}) else: cv2.putText(photo, 'Unknown', (x+2,y+h-5), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 255), 2) cv2.imshow("Face Recognizer", photo) key = cv2.waitKey(1) if key == ord('s'): break cam.release() cv2.destroyAllWindows() return render(request,'thankyou.html')