Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to change font color in django
I wrote a code in django and I want the html page font color to be red. The following is the html file. {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'blog/css/base.css' %}"> </head> <body> {% if blogs %} {% for blog in blogs %} <ul> <li>{{ blog }}</li> </ul> {% endfor %} {% else %} <p>No Blogs are available.</p> {% endif %} </body> </html> The following is the css file li { color: red; } The following is the output I am getting- I am new to django and some help will be appreciated. -
Django forms - error messages displayed twice in template
As above, my template displays validation errors twice. I need to disable messages that appear below the fields by default (the one with font-weight) img -> https://i.imgur.com/RjQzgA2.jpg template <div class="container"> <form method="post">{% csrf_token %} {% for field in form %} {{field|as_crispy_field}} {% if field.errors %} <div class="alert alert-danger">{{ field.errors|striptags }}</div> {{ form.name_of_field.errors }} {% endif %} {% endfor %} <br> <input type="submit" value="Register"> </form> </div> forms class UserRegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) repassword = forms.CharField(widget=forms.PasswordInput()) class Meta: model = ForumUser fields = ["username", "email", "password", "repassword"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields: new_data = { "placeholder": f"Provide {field}", "class": "form-control" } self.fields.get(field).widget.attrs.update(new_data) self.fields.get(field).help_text = "" def clean(self): cleaned_data = super(UserRegisterForm, self).clean() return cleaned_data def clean_repassword(self): password = self.cleaned_data.get("password") repassword = self.cleaned_data.get("repassword") if repassword != password: raise ValidationError("Passwords do not match") -
Django reference multiple image in template
Hi I am letting the user upload multiple images per project but so far the images are not displayed. In projects.html all projects should be displayed and the title and the describtion work so far. But the main-image doesn´t show up. In single-project all images should be displayed. What do I have to change in my models.py? Thanks in forward models.py class Project(models.Model): title = models.CharField(max_length=200) describtion = models.TextField(null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class ProjectImage(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) featured_images = models.FileField() forms.py class ProjectForm(ModelForm): featured_images = forms.ImageField(widget=ClearableFileInput(attrs={'multiple':True})) class Meta: model = Project fields = ['title', 'describtion', 'featured_images'] views.py def createProject(request): form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST) images = request.FILES.getlist('image') if form.is_valid(): project = form.save() for i in images: ProjectImage(project=project, image=i).save() context = {'form':form} return render(request, 'projects/project_form.html', context) def projects(request): projects = Project.objects.all() context = {"projects":projects} return render(request, 'projects/projects.html', context) def project(request, pk): projectObj = Project.objects.get(id=pk) return render(request, 'projects/single-project.html', {'project':projectObj}) projects.html {% for project in projects %} <div class="column"> <div class="card project"> <a href="{% url 'project' project.id %}" class="project"> <img class="project__thumbnail" src="{{project.featured_images.url}}" alt="project thumbnail" /> <div class="card__body"> <h3 class="project__title">{{project.title}}</h3> <h3 class="project__title">{{project.price}} €</h3> </div> </a> </div> </div> {% endfor %} single-project.html <h3 class="project__title">{{project.title}}</h3> <h3 … -
How to handle error for invalid date format
class CentreCreateFromFile(APIView): permission_classes = [IsAuthenticated, ] def post(self, request, *args, **kwargs): upload_file = request.FILES.get('centre_file') file = upload_file.read().decode('utf-8') reader = csv.DictReader(io.StringIO(file)) data = [line for line in reader] for item in data: center_code = item['Centre Code'] name = item['Centre Name'] center_type = item['Centre Type'] contract_start_date = item['contract date'] contract_end_date = item['expiry date'] identity_proof = item['identity proof'] mobile = item['mobile number'] email = item['email id'] sales_manager = item['sales manager'] address = item['centre address'] ratelist = item['service rate category'] #location = item['pincode'] owner_salutation = item['salutation'] owner_name = item['name'] owner_phone = item['mobile number'] min_amnt_for_notification = item['Min Amount for Notification'] check_centre_name = center_models.Centers.objects.filter(name=name) if check_centre_name: raise ParseError(f'Centre Name {name} already exists') check_centre_code = center_models.Centers.objects.filter(center_code=center_code) if check_centre_code: raise ParseError(f'Centre Code {center_code} already exists') identity_proof_id = IdentityProof.objects.filter(name__iexact=identity_proof).first() if identity_proof_id: identity_proof_id = identity_proof_id.id else: raise ParseError(f'Invalid Identity Proof for centre {name}') ratelist_id = center_models.RateList.objects.filter(name__iexact=ratelist).first() if ratelist_id: ratelist_id = ratelist_id.id else: raise ParseError(f'{ratelist} does not exist') sales_manager_id = panel_models.PanelUser.objects.filter(user__username__iexact=sales_manager).first() if sales_manager_id: sales_manager_id = sales_manager_id.id else: raise ParseError(f'{sales_manager} does not exist') centre = center_models.Centers() centre.center_code = center_code centre.name = name centre.center_type = center_type centre.contract_start_date = contract_start_date centre.contract_end_date = contract_end_date centre.identity_proof_id = identity_proof_id centre.mobile = mobile centre.email = email centre.sales_manager_id = sales_manager_id centre.address = address #centre.location.pincode = location centre.owner_salutation = owner_salutation … -
Reverse image search using Django
I wanted to add image search in Django admin. Instead of search using name and id, i have to give an profile image and then search for all users with particular image in Django admin. -
I want to categorize by slug in Django
I want the products with true bestseller to appear in product.html when the slug is "cox-satanlar" How can I do that? models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey # Create your models here. class Category(MPTTModel): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return '>>'.join(full_path[::-1]) class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) main_image = models.ImageField(upload_to='static/product_images/%Y/%m/%d/') detail = models.TextField() keywords = models.CharField(max_length=50) description = models.CharField(max_length=100) price = models.FloatField() sale = models.IntegerField(blank=True, null=True, verbose_name="Sale (%)") bestseller = models.BooleanField(default=False) amount = models.IntegerField(blank=True, null=True) available = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name @property def discount(self): dis = float(self.price - (self.price * self.sale) / 100) ln = '' if len(str(dis)) > 3: for i in str(dis): ln += i dis = float(ln) if len(ln) > 3: break return dis views.py def products(request, category_slug): category = Category.objects.all() products = Product.objects.all().filter(category__slug=category_slug) best_products = Product.objects.all().filter(bestseller=True) context = {'category': category, 'products': products, 'best_products': best_products} return render(request, 'products.html', context) urls.py urlpatterns = [ path('', views.index, name='index'), path('register/', views.userRegister, name='register'), path('login/', views.userLogin, name='login'), path('products/<slug:category_slug>/', views.products, name='category_slug'), … -
Django form set css class on selection values
in my django app, i have simple form like this: class ThrowForm(forms.ModelForm): def __init__(self,game,*args,**kwargs): super (ThrowForm,self ).__init__(*args,**kwargs) self.fields['player_id'].queryset = Player.objects.filter(Q(team_id = game.team1_id) | Q(team_id = game.team2_id)) class Meta: model = Throw fields = ['player_id', 'score','game_id'] How can i set an css class on the different values in the player_id field. I imagine that the players of team 1 have a different font color than those of team 2. Is this possible? Thanks -
How to show a certain value instead of None in Django?
I am new to Django and I am passing on object players to my HTML template. I am iterating over this object and showing player.lastName but this value sometimes return None. How can I show a value of my choice if the player.lastName was None. I want to write something like: <td>{{player.lastName 'OR' - }} -
Django - how to access local audio files in different URL paths?
Thanks in advance for reading. I'm working on my final project for CS50W which involves working with a series of local audio files (user cannot upload additional files at this time). The issue occurs when I try to populate an src attribute with the file. I have two URL paths which deal with accessing these files: new/ and edit/int:id. When I access the audio files in new/, it works as intended and I can play the file from the tag. However, when I try to access the files in the edit/int:id path, I get this error: GET http://localhost/edit/8/media/Aminor_Ipi3udk.mp3 net::ERR_ABORTED 404 (Not Found) I am relatively new to coding (just did CS50x and then started CS50w) and I don't understand why I'm getting this error or how I can fix it - I'm doing the same thing for both paths and yet it only works in one of them. I would be grateful if someone could help me to remedy this or at least point me in the direction of understanding why this is happening. For additional context, check out my github gist which contains the relevant python, javascript, and html in my code: https://gist.github.com/bh96/7fe6ef5970ef01bea63c15471f612ae2 -
sentry Does not work when i deploy project on the server
I have a Django project with sentry configurations. when i run project in my local, i can see errors in my sentry panel, but when i push the project on server and run it, i cant see the errors in sentry panel. This is my config code import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.celery import CeleryIntegration sentry_sdk.init( dsn="https://********@****.ingest.sentry.io/*****", integrations=[DjangoIntegration(), CeleryIntegration()], # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, # If you wish to associate users to errors (assuming you are using # django.contrib.auth) you may enable sending PII data. send_default_pii=True ) I also dockerized the project, and I had a problem with Gunicorn that I was able to fix, but it still sentry doesn't work when I run the project on the server. -
django filter price min/max range
Trying to filter price on the site based on min max range. My view def products(request, slug): """ List all products of a category """ category = get_object_or_404(Category, slug=slug) products = Product.objects.filter(category=category) brand_queryset = Brand.objects.filter(products__in=products).distinct('name') # Filter products based on price range if 'min_price' in request.GET: min_price = request.GET['min_price'] max_price = request.GET['max_price'] print("Min price: {}Max price: {}".format(min_price, max_price)) if not max_price: max_price = Product.objects.all().aggregate(Max('price'))['price__max'] products = products.filter(price__range=(min_price, max_price)) context = { 'products': products, 'category': category, 'form': form, 'brand_queryset': brand_queryset, 'title': Product, } return render(request, 'products/products.html', context) Html <div class="card-body"> <div class="form-row"> <div class="form-group col-md-6"> <label>Min</label> <input cass="form-control" name="min_price" value="min_price" placeholder="Kr 0" type="number"> </div> <div class="form-group text-right col-md-6"> <label>Max</label> <input class="form-control" name="max_price" value="max_price" placeholder="Kr 1,0000" type="number"> </div> </div> <button class="btn btn-block btn-primary" type="submit" value="Go">Apply</button> </div> Trying to sort the listing of products based on price range, min and max. Only show the products within the range. However having a hard time getting the view and html working together. -
Django Crispy-Form Input type Customization/validation (Language and Numbers)
I want to Customize my form input in forms.py. I am using crispy form. I want to input 'phone number' with specific length instead of 'username' and also that should be in a specific Language(not English). I also want to input name_ban,fathers_name_bangla,mothers_name_bangla fields in only a specific language text(bengali).How can I do that? How can I implement such a condition in my forms.py? codes are given below. forms.py from django.forms import ModelForm from .models import * from django import forms from django.contrib.auth.forms import UserCreationForm class Add_Applicant(ModelForm): class Meta: model = Applicant fields =[ "course", "session", "name_ban", "name_eng", "fathers_name_bangla", "fathers_name", "mothers_name_bangla", "mothers_name", "marital_status", "present_address", "village", "district", "sub_district", "ps", "post_office", "date_of_birth", "religion", "nid_BC", "education", "phone", "Guardian_phone", "picture"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['sub_district'].queryset = Sub_district.objects.none() if 'district' in self.data: try: district_id = int(self.data.get('district')) self.fields['sub_district'].queryset = Sub_district.objects.filter(district_id=district_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['sub_district'].queryset = self.instance.district.sub_district_set.order_by('name') class Remarks_Applicant(ModelForm): class Meta: model = Applicant fields =["status", "roll_no", ] class Add_Course(ModelForm): class Meta: model = Course fields = '__all__' class Add_Project(ModelForm): class Meta: model = Project fields = '__all__' class Add_Session(ModelForm): class Meta: model = Session fields = '__all__' class Add_Resolution(ModelForm): … -
How to convert ImageField Object into JSON Django
I have this data and want to return using Django JSON, calling this function using Ajax but it gives me error. I have tried everything dups, convert to string and many more but failed. *TypeError: Object of type ImageFieldFile is not JSON serializable * [<ImageFieldFile: photos/E5542982/E5542982.jpg>, <ImageFieldFile: photos/E5542982/E5542982_2.jpg>, <ImageFieldFile: photos/E5542982/E5542982_3.jpg>, <ImageFieldFile: photos/E5542982/E5542982_4.jpg>, <ImageFieldFile: photos/E5542982/E5542982_5.jpg>, <ImageFieldFile: photos/E5542982/E5542982_6.jpg>, <ImageFieldFile: photos/E5542982/E5542982_7.jpg>, <ImageFieldFile: photos/E5542982/E5542982_8.jpg>, <ImageFieldFile: photos/E5542982/E5542982_9.jpg>, <ImageFieldFile: photos/E5542982/E5542982_10.jpg>, <ImageFieldFile: photos/E5542982/E5542982_11.jpg>, <ImageFieldFile: photos/E5542982/E5542982_12.jpg>, <ImageFieldFile: photos/E5542982/E5542982_13.jpg>, <ImageFieldFile: photos/E5542982/E5542982_14.jpg>, <ImageFieldFile: photos/E5542982/E5542982_15.jpg>] I have tried my best to solve but am unable to solve this error. Can anyone help me please? -
Wagtail ChoiceBlock dynamic default value
I have a wagtail ChoiceBlock, thats dynamically loading it's choices from a function. My question is how do I set the default as the first value returned from that function? index = ChoiceBlock( choices=get_blog_index_pages, required=True, help_text='Select a Blog Index to filter dynamic results' default=? ) -
populate Django database my code with Faker library, when I was compiling it did not showing any error, but not populate fake data in admin page
This is my first file which is the script for populating the database: ('fake_data.py') when I run python fake_data.py it showing "populating fake_data populating complated!" This file is 'module.py' But when I am running server the fake data is not in admin page. -
Replace UUID field content back to default null
Using Django==2.2.27, and Postgres I have a Model, with a UUID field: from django.db import models class MyModel(models.Model): uuid_field = models.UUIDField( blank=True, db_index=True, null=True, ) I need to delete the field (column) content for some objects (rows) - but when I try: my_object.uuid_field = None my_object.save() I get this error: ValidationError: ["'None' is not a valid UUID."] ^ That makes sense, since the value is definitely not a UUID: link A bit more explanation: I can create objects without populating the uuid_field so it stays null I will most likely populate the uuid_field I might need to delete the uuid_field content I cannot change the UUIDField to a char field or anything else Is there a way to get the field back to its default null using Django ORM? Thank you! -
Django unit test to see if model is registered to admin page
I have a URL (/admin/) that goes to my Django admin panel (my URL router:url(r'^admin/', admin.site.urls),) This admin panel includes an admin for the Post model. That Post model is being registered by a ModelAdmin class called PostAdmin. admin.py: from .models import Post class PostAdmin(admin.ModelAdmin): list_display = ( 'id', 'slug', 'title', 'author' ) admin.site.register(Post, PostAdmin) Now I want to write a unit test for this admin.py file and I want to check that if you go to the /admin/ URL you see the Post Model. How would you do this? I think it would be something like: response = method_gets_url_content(`/admin/`) assert.response.contains('Tags') == True But I'm not sure how to write a test like this since there is no method to get that URL (/admin). -
Python parse JSON from bytes or string?
I copied code from Django REST framework docs to parse JSON which uses a byte stream. with open(path, 'rb') as file: stream = io.BytesIO(file.read()) return JSONParser().parse(stream) Is there any advantage in using a byte stream over a string? More performant? Less chance on issues with encoding? I'm also wondering why Django Restframework has its own JSONParser and doesn't use the Python standard lib json. Finally, I saw orjson, supposedly the fastest parser. Any experiences with that one? -
How to make a rawSQL query in Django?
A simple question, but I did't find the exact result that I am looking since I am no very familiarized with SQL queries. I have this, which is a pk list corresponding to the countries: countries_list = list(accounts.values_list('country', flat=True)) I am looking for efficiency, so I am trying to do this as a rawSQL query basic_countries = BasicCountry.objects.exclude(country__in=countries_list) Any idea? Thanks in advance! I have tried this: countries_list = tuple(accounts.values_list('country', flat=True)) basic_countries_raw = BasicCountry.objects.raw(f"SELECT * FROM my_table WHERE id IN {countries_list}") -
How to run python function at specific date each year?
I am building a website in Django, where i have to run python function on 1st April every year how can I do that. -
How to make an attribute required(or not) if another attribute(BooleanField) is True in Django?
I want that a field be required for the user when making a blog post just if other field(BooleanField) is True. If it's False, it would be okay if the user doesn't complete anything. How can I do it? Let's say I have this model class Post(models.Model): name = models.CharField(max_lenght=50) is_female = models.BooleanField() age = models.IntegerField() So, I want that the age attribute be required just if the is_female is True Thanks! -
how to create an update form in django without creating new view or page?
I want to create an update form that would track the completion of a tutorial, in the models.py there is a completed = models.BooleanField that the user would need to check in order to make the tutorial as complete, but i do not want to create another page or view for this feature, how can i do this in the tutorialDetail View? views.py def programmingLanguageTutorial(request, prglangcat_slug, prg_slug ): prglangtut = ProgrammingLanguageTutorial.objects.get(slug=prg_slug, prglangcat=prglangcat) # Save Learning Progress/ mark as complete if request.method == "POST": complete_form = MarkTopicAsCompleteForm(request.POST) if complete_form.is_valid(): complete_form.save() return redirect('base:tutorial-page', prglangcat.slug, prglangtut.slug) else: complete_form = MarkTopicAsCompleteForm() context = { 'complete_form': complete_form, } return render(request, 'base/tutorial-page.html', context) urls.py from django.urls import path from base import views app_name = 'base' urlpatterns = [ path('getting-started/<prglangcat_slug>/<prg_slug>/', views.programmingLanguageTutorial, name="tutorial-page"), ] -
How to send email via SendGrid instead of a file-based EmailBackend in Django
I'm using a file-based EmailBackend in Django. I don't want to store emails in a folder, instead, I want to use SendGrid. I'm following this tutorial here: https://learndjango.com/tutorials/django-password-reset-tutorial?msclkid=0c678f63ac0211ec9f8ff2047d0a934e Here's the concerned part of settings.py: EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend" EMAIL_FILE_PATH = BASE_DIR + "/sent_emails" All emails are stored in this folder /sent_emails. I don't want to do this. The tutorial linked above mentions MailGun and SendGrid, but it doesn't detail how to use that there. This is the Python code required to send an email via SendGrid, but because I'm using Django's built-in reset password facility (which I'm trying to do here), I do not think this is going to be of much help alone, not added to some sort of event that Django provides: message = Mail( from_email='jeff@example.com', to_emails='bob@example.com', subject='Greetings in different languages', html_content=" <ul> <li>Spanish: Hola!</li> <li>French: Salut!</li> <li>Japanese: こんにちは!</li> <li>German: Hallo!</li> <li>Italian: Ciao!</li> </ul> ") try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message) The email data above is only an example, and in the app I do not intend to use it (BTW I'm polylingual). Do you know how to do this? -
Django Circular Import Issue
I am having a Circular Import Error, even thought I do not have imports going both ways between apps. Here are the 2 apps models I have, please tell me what am I doing wrong? Also, I was working on some views and suddenly this error appeared, before that I was working just fine with no issues. App 1: from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse from django.template.defaultfilters import slugify from .utils import * from .constants import * class City(models.Model): title = models.CharField(max_length=45) posted = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Ville" verbose_name_plural = "Villes" def __str__(self): return self.title class Account(AbstractUser): phone = models.CharField(max_length=15, null=True, blank=True) phone_verified = models.BooleanField(default=False) email_verified = models.BooleanField(default=False) address = models.TextField(null=True, blank=True) dobd = models.CharField(max_length=2, choices=DAYS, null=True, blank=True) dobm = models.CharField(max_length=9, choices=MONTHS, null=True, blank=True) doby = models.CharField(max_length=4, null=True, blank=True) city = models.ForeignKey(City, on_delete=models.DO_NOTHING, null=True, blank=True) gender = models.CharField(max_length=5, choices=GENDERS, null=True, blank=True) profilepic = models.FileField(upload_to="profile_pics/", null=True, blank=True) points = models.IntegerField(default=0) lat = models.CharField(max_length=50, null=True, blank=True) lon = models.CharField(max_length=50, null=True, blank=True) captcha_score = models.FloatField(default=0.0) updated = models.DateTimeField(auto_now=True) receive_sms = models.BooleanField(default=True) receive_email = models.BooleanField(default=True) new = models.BooleanField(default=True, editable=False) class Meta: verbose_name = "Compte" verbose_name_plural = "Comptes" def __str__(self): return self.username class UserModel(Account): … -
Django heroku push gives could not build wheels for backports.zoneinfo error
I am trying to push a django project to heroku. heroku create worked fine but when trying to push to heroku main I get the following error. ''' Enumerating objects: 5317, done. Counting objects: 100% (5317/5317), done. Delta compression using up to 2 threads Compressing objects: 100% (1852/1852), done. Writing objects: 100% (5317/5317), 72.93 MiB | 134.00 KiB/s, done. Total 5317 (delta 4004), reused 4506 (delta 3415) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.10.4 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.10.4 remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.4.1 remote: Downloading asgiref-3.4.1-py3-none-any.whl (25 kB) remote: Collecting backports.zoneinfo==0.2.1 remote: Downloading backports.zoneinfo-0.2.1.tar.gz (74 kB) remote: Installing build dependencies: started remote: Installing build dependencies: finished with status 'done' remote: Getting requirements to build wheel: started remote: Getting requirements to build wheel: finished with status 'done' remote: Preparing metadata (pyproject.toml): started remote: Preparing metadata (pyproject.toml): finished with status …