Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to clear user specific cache in django?
I am using Django2.2.2 and django_redis for the cache backend. I had implemented cache in my API view according to this gist, and my views are here. from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_headers @method_decorator(cache_page(168 * 3600, key_prefix="posts")) @method_decorator(vary_on_headers("Authorization",)) def list(self, request, *args, **kwargs): return super(PostViewSet, self).list(request, *args, **kwargs) This method will cache the post list on the user basic for 7 days. I had a clear cache like this. from django.core.cache import cache cache.delete_many(keys=cache.keys("*.posts.*")) How can I delete only some specific user cache? I had tried django-clear-cache but it cleared all cache. Is there any technique for clearing the per-user cache? -
Counting many-to-many field returns wrong value (Django)
I have a model class Student: class Student(models.Model): ... and model class Course: class Course(models.Model) students = models.ManyToManyField(Student) I now want to filter Course based on number of Students associated with a course. I tried: Course.objects.annotate(student_count = Count('students')) But for some reason, student_count is always returning one. Let's say I create a course and add two students to it: s1 = Student.objects.create() s2 = Student.objects.create() m1 = Course.objects.create() m1.students.add(s1) m1.students.add(s2) print(Student.objects.all().first().students.count()) print(Student.objects.annotate(student_count = Count('students')).first().student_count Prints 2 1 Why are these two values different? How can I filter courses based on the number of students? -
how to get a variable value from form to python function in django from javascript
I am trying to scan QR code using javascript as shown below. this part is working fine: <title>Django Online Barcode Reader</title> <meta charset="utf-8"> {% csrf_token %} <script src={% static "html5-qrcode.min.js"%}></script> <style> .result{ background-color: green; color:#fff; padding:20px; } .row{ display:flex; } </style> <!--<form action="" method="POST">--> {% csrf_token %} <div class="row"> <div class="col"> <div style="width:500px;" id="reader"></div> </div> <div class="col" style="padding:30px;"> <h4>SCAN RESULT</h4> <!--<div id="result" name="result">Result Here</div>--> <output type="post" id="result" name="resutl" placeholder="qrCodeMessage"> </div> </div> <script type="text/javascript"> function onScanSuccess(qrCodeMessage) { document.getElementById('result').innerHTML = '<span class="result">'+qrCodeMessage+'</span>';} function onScanError(errorMessage) { //handle scan error } var html5QrcodeScanner = new Html5QrcodeScanner( "reader", { fps: 10, qrbox: 250 }); html5QrcodeScanner.render(onScanSuccess, onScanError); </script> But I need to pass the value of result variable to python function as following and print it but did not work. It does not print any! def userspage(request): if request.method == 'POST': result = request.POST.get("result") context = {} print(result) return render(request, 'users.html', context) I need your usual help to fix this. Thanks, -
Django web Deployment Failed. on azure
10:47:19 AM django-face-restore: ERROR: Could not find a version that satisfies the requirement torch==TORCH_VERSION+cpu (from versions: 1.4.0, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.7.1, 1.8.0, 1.8.1, 1.9.0, 1.9.1, 1.10.0, 1.10.1, 1.10.2, 1.11.0) 10:47:19 AM django-face-restore: ERROR: No matching distribution found for torch==TORCH_VERSION+cpu 10:47:19 AM django-face-restore: WARNING: You are using pip version 21.1.1; however, version 22.0.4 is available. 10:47:19 AM django-face-restore: You should consider upgrading via the '/tmp/8da12d59fc3e034/antenv/bin/python -m pip install --upgrade pip' command. 10:47:19 AM django-face-restore: "2022-03-31 07:00:00"|ERROR|Failed pip installation with exit code: 1 10:47:21 AM django-face-restore: /opt/Kudu/Scripts/starter.sh oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform python --platform-version 3.8 -i /tmp/8da12d59fc3e034 --compress-destination-dir -p virtualenv_name=antenv --log-file /tmp/build-debug.log 10:47:21 AM django-face-restore: Deployment Failed -
Django queryset for current year
I have my query written to get some thing from database and display on my website that query is getting all the data from db but what if i want to get the data particular to current year only def get(self, request, *args, **kwargs): filters = self.get_filters() result = Model.objects.all().filter(*filters).distinct().aggregate( t=Sum('t'), b=Sum('b'), ) result2 = Model.objects.all().filter(*filters).distinct().aggregate( past_due=Sum('balance', filter=Q(due_date__lt=timezone.now())) ) zero = Decimal('0.00') total = result['t'] or zero balance = result['b'] or zero past_due = result2['past_due'] or zero amount_received = t - b -
Send disconnect message to WebSocket in Django Channels
I am using Django==3.2.5 and channels==3.0.4. In the consumers.py I am using WebsocketConsumer class. My disconnect() method is executed After disconnecting the socket, which means the disconnect method is unable to send a response to the socket. I found a similar issue in this link but they are using AsyncWebsocketConsumer class. Is there a way to solve it using WebsocketConsumer class? I have the following code: class MeetingStatus_Consumer(WebsocketConsumer): def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["id"] self.room_group_name = 'Booking_id_%s' % self.room_name # Adding room_name and group_name to the channel async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() # accept the request from frontend self.send(text_data=json.dumps({'status': "Websocket Connected"})) # send data to frontend def disconnect(self, *args, **kwargs): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) self.send(text_data=json.dumps({'status': "Websocket disconnected"})) -
Child terminated with exit code 2 for running celeryd service in production
i am using celery version 5.1.2 on Ubuntu 16.04 with python 3.8 and Django 3.0 .In my production i am unable run the schedule tasks. here is my /etc/systemd/celerd.conf # Name of nodes to start # here we have a single node CELERYD_NODES="worker1" # or we could have three nodes: #CELERYD_NODES="w1 w2 w3" CELERY_APP="mcam" # Absolute path to "manage.py" # CELERY_BIN="/home/ravi/deploy/mcam/mcam/server/mcam/manage.py" #CELERY_BIN="/home/ravi/.virtualenvs/lightdegree/bin/python manage.py celery" CELERY_BIN="/home/ravi/.virtualenvs/lightdegree/bin/celery" # How to call manage.py CELERYD_MULTI="celery beat" # Extra command-line arguments to the worker # m3.medium instance has 1 vCPU. Hence the concurrency is limited to 2 CELERYD_OPTS="--time-limit=300 --concurrency=4" # %N will be replaced with the first part of the nodename. CELERYD_LOG_FILE="/var/log/celery/%N.log" CELERYD_PID_FILE="/var/run/celery/%N.pid" this my /etc/systemd/system/celeryd.service [Unit] Description=Celery Beat Service After=network.target Requires=gunicorn.service rabbitmq-server.service [Service] #Type=forking User=ravi Group=ravi EnvironmentFile=/etc/systemd/celeryd.conf WorkingDirectory=/home/ravi/deploy/mcam/server/mcam #ExecStart=/home/ravi/.virtualenvs/lightdegree/bin/python manage.py celery -l debug -A mcam beat ExecStart=/home/ravi/.virtualenvs/lightdegree/bin/celery multi start ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS} #ExecStop=/home/ravi/.virtualenvs/lightdegree/bin/celery ${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ # --pidfile=${CELERYD_PID_FILE} ExecReload=/home/ravi/.virtualenvs/lightdegree/bin/celery ${CELERY_BIN} multi restart ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS} [Install] WantedBy=multi-user.target here are the commands what i used and error what i am getting sudo systemctl daemon-reload sudo systemctl reset-failed celeryd.service sudo systemctl restart celeryd sudo systemctl status celeryd ● celeryd.service - Celery Beat Service Loaded: loaded (/etc/systemd/system/celeryd.service; … -
TypeError: Field 'id' expected a number but got ['database']; ManyToManyField
I'm having a problem adding a set of objects on a ManyToMany field on my Question model, Question.tags. When passing the set of Tag instances on the line that contains question.tags.add(tags) the following error is raised: TypeError: Field 'id' expected a number but got ['database'] Why is adding the list of model instances to the ManyToMany field causing this error? class AskQuestionPage(Page): template_name = "posts/ask.html" extra_context = { 'title': "Ask a public question" } def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = QuestionForm return context def post(self, request): context = self.get_context_data() form = context['form'](request.POST) if form.is_valid(): profile = Profile.objects.get(user=request.user) form.cleaned_data['profile'] = profile tags = form.cleaned_data.pop("tags") question_tags = [] for name in tags: try: tag = Tag.objects.get(name=name) except Tag.DoesNotExist: tag = Tag.objects.create(name=name) finally: question_tags.append(tag) question = form.save() question.tags.add(question_tags) return SeeOtherHTTPRedirect( reverse("posts:question", kwargs={"id": question.id}) ) return self.render_to_response(context) class QuestionForm(ModelForm): title = CharField( min_length=20, max_length=80, widget=TextInput({"class": "question_input_shade fill_block_width"}), error_messages={"max_length": "The title of your question is too long"}, help_text="Concisely describe the issue" ) body = CharField( widget=Textarea(attrs={"class": "question_input_shade fill_block_width adjust_box"}), min_length=50, help_text="Clarify your question with as much detail as possible", error_messages={ 'required': "Elaborate on your question", 'min_length': "Add more info to your question" } ) tags = TagField( widget=MultiTagWidget( attrs={ "min_length": 1, "max_length": 25, … -
Searilizer in Django Rest framework isint working as expected
Following are my searlizers: #This isnt working as expected class ChatSearilizer(serializers.ModelSerializer): messages: MessageSearlizer(many=True) first_participant: serializers.SerializerMethodField() second_participant: serializers.SerializerMethodField( ) def get_first_participant(self, obj): return { "id": obj.first_participant.pk, "name": obj.first_participant.name, "photo": obj.first_participant.photo.file.url, } def get_second_participant(self, obj): return { "id": obj.second_participant.pk, "name": obj.second_participant.name, "photo": obj.second_participant.photo.file.url, } class Meta: model = Chat fields = "__all__" class MessageSearlizer(serializers.ModelSerializer): class Meta: model = Message fields = "__all__" Following are my models: class Chat(models.Model): first_participant = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="first_participant") second_participant = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="second_participant") date_modified = models.DateTimeField(auto_now=True) class Message(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) sender = models.ForeignKey( to=Profile, on_delete=models.CASCADE, related_name="sender", null=True) # This null is temporary will remove it receiver = models.ForeignKey( to=Profile, on_delete=models.CASCADE, related_name="receiver", null=True) # This null is temporary will remove it text = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Meta: ordering = ["timestamp"] Following are the views: class UserChats(generics.ListAPIView): serializer_class = ChatSearilizer # get all the chats in which user is involved def get_queryset(self): return Chat.objects.filter(Q(first_participant=self.request.user.profile) | Q(second_participant=self.request.user.profile)) class ChatDetail(generics.RetrieveAPIView): serializer_class = ChatSearilizer def get_queryset(self): return Chat.objects.filter(pk=self.kwargs.get('pk')) class SendMessageView(generics.CreateAPIView): serializer_class = ChatSearilizer def post(self, request, *args, **kwargs): new_request = request chat_id = new_request.data["chat_id"] text = new_request.data["text"] sender = self.request.user.profile.pk receiver = new_request.data["receiver"] # check if chat_id is present in request body … -
Django query - Database table to slow
I have a complex query that is just taking far too long. I think I have drilled down to the main problem when I execute: Airplay.objects.all().count() The execution time is: 48s The results is: 37428412 The model is: class Radio(Timestamps): name = models.CharField('Name', max_length=255, blank=True) slug = models.CharField('Slug', max_length=255, blank=True) country = CountryField(blank=True) def __str__(self): return '%s - %s' % (self.name, self.country) class Airplay(Timestamps): song = models.ForeignKey(Song, on_delete=models.CASCADE) radio = models.ForeignKey(Radio, on_delete=models.CASCADE) airedAt = models.DateTimeField(blank=True) duration = models.IntegerField() playcount = models.IntegerField(default=1) def __str__(self): return '%s - %s' % (self.song.name, self.radio.name) any ideas how to optimize this? Thanks in advance! -
Make migrations is not detecting many to many field in model
Following are my models: class Message(models.Model): sender = models.ForeignKey( to=Profile, on_delete=models.CASCADE, related_name="sender", null=True) # This null is temporary will remove it receiver = models.ForeignKey( to=Profile, on_delete=models.CASCADE, related_name="receiver", null=True) # This null is temporary will remove it text = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Meta: ordering = ["timestamp"] class Chat(models.Model): conversation: models.ManyToManyField(Message) #---> This field is not being detected. first_participant = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="first_participant") second_participant = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="second_participant") date_modified = models.DateTimeField(auto_now=True) No matter what i do, make migrations is not detecting this many to many field. Can someone please help? -
How to clone the input value when cloning the form in JavaScript
I am trying to save multiple objects in one page using django formset. For example, when I want to input 5 objects in the each form, the "kinds" and "hour" field have different values for all 5 objects, and all 5 objects have the same value for the remaining fields. So I am using the django-formset. So, when cloning a form in django formset, I would like the input value to be cloned as well. After several searches I couldn't find a solution. I read that setting true in the clone method will clone the event handler and even the value, but the entered value will not be cloned. Should I get it in the request.POST method? (For reference, the date field uses the datetimepicker jquery, and the student field uses the chosen jquery that is easy to search in the dropdownlist.) [html] <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer mt-4"> <div class="form-group row"> <label>{{form.date.label}}</label> <div class="input-group"> {{form.date}} </div> </div> <div class="form-group row"> <label>{{form.student.label}}</label> <div class="input-group"> {{form.student}} </div> </div> <div class="form-group row"> <label>{{form.kinds.label}}</label> <div class="input-group"> {{form.kinds}} </div> </div> <div class="form-group row"> <label>{{form.hour.label}}</label> <div class="input-group"> {{form.hour}} </div> </div> … -
Need help: whitenoise seems to be preventing a Django app running on heroku
Please point me to the right direction with a Django app that I am trying to put on Heroku. The app runs locally (both with python manage.py run server and heroku local), but doesn't run on heroku. It seems the root problem stems from whitenoise and I get errors doing collectstatic. BTW, whitenoise setup was done following the steps here for using whitenoise with Django. (app repo is here.) Through various searches I found this that suggests setting the Node version on Heroku to use the same one used locally, but I am not using npm nor node. I tried the kill process tip from here, but that didn't help. Neither did heroku restart. Doing python manage.py collectstatic --noinput got me these error messages: Traceback (most recent call last): File "/Volumes/Volume2/dev/student_manage_csp/manage.py", line 22, in <module> main() File "/Volumes/Volume2/dev/student_manage_csp/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Volumes/Volume2/dev/student_manage_csp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/Volumes/Volume2/dev/student_manage_csp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Volumes/Volume2/dev/student_manage_csp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/Volumes/Volume2/dev/student_manage_csp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/Volumes/Volume2/dev/student_manage_csp/venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/Volumes/Volume2/dev/student_manage_csp/venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 134, in collect raise processed whitenoise.storage.MissingFileError: The file 'admin-lte/plugins/pdfmake/FileSaver.min.js.map' could not be found … -
Why i am getting this error AttributeError: module 'collections' has no attribute 'Iterator while creating django project in django version 2.0.7?
Hi i am learning Django from this youtube video Python Django Web Framework - Full Course for Beginners from freecodecamp when i tried to create a project using Django 2.0.7 in virtual environment. i am getting this error AttributeError: module 'collections' has no attribute 'Iterator dont know why please help me to fix this. I am doing exactly what was shown in that tutorial like i created virualenvironment then i installed django 2.0.7 then i ran command django-admin startproject trydjango . But i am getting this error.please tell me how to fix this i tried with creating another virtual environment and even tried with othernames for project but i am keep on getting this error and i even tried to create it without . at end of the line like django-admin startproject trydjango instead of django-admin startproject trydjango . Then it gives same error with a empty trydjango folder (venv) C:\Users\chirag\Dev\trydjango>django-admin startproject trydjango . Traceback (most recent call last): File "C:\Program Files\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Program Files\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\chirag\Dev\trydjango\venv\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "C:\Users\chirag\Dev\trydjango\venv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\chirag\Dev\trydjango\venv\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File … -
how to get django to run multi task operation with django_eventstream send_event
I noticed that while working with django_eventstream send_event it prevents other activities from continuing even the loading of a new page. How can i get the django_eventstream to respond to other activities while performing a specific operation -
How can I unit test saving user input in Django?
I am working on a small project and I want to be able to test the post methods, saving to the database if the email does not exist, and rendering to index.html for the view below. I've looked at YouTube videos and blog tutorials and I can't seem to find the answer that I am looking for. I have included the Model, View, and my current tests. Model: class EmailList(models.Model): email = models.TextField(unique=True) View: def home(request): # Join Email List if request.method == 'POST': if request.POST.get('email'): email = request.POST.get('email') if not EmailList.objects.filter(email=email).exists(): emailInput = EmailList() emailInput.email = email emailInput.save() return render(request, 'email/index.html', {}) else: return render(request, 'email/index.html', {}) Test I have so far: from django.test import TestCase from tasckq.models import EmailList class HomeViewTest(TestCase): @classmethod def setUpTestData(cls): # Create a new email to test EmailList.objects.create(email="test1@example.com") def test_home_view_url_exists_at_desired_location(self): response = self.client.get('') self.assertEqual(response.status_code, 200) def test_home_view_post_request_method(self): response = self.client.post('', {'email' : 'test1@example.com'}) self.assertEqual(response.status_code, 200) def test_home_view_save_email(self): self.assertEqual(EmailList.objects.count(), 1) -
how to populate two different columns with one for loop
I have an object, I want to loop through the object and populate a page with two columns I don't know how to seperate the object into two columns. if I make a div in a loop for each item they just go under each other. -
How to change the field name of Serialzed User Model on frontend in Django Rest Framework?
I am making a simple Login/Logout App using REST API in Django DRF. I am using the default User model for this behavior. In the Login API, I wanted to authenticate the user with email, hence I wrote the custom authentication using ModelBackend. Everything works fine. But, I want to change the word username to email in the front of the Login API. I tried using the source attribute, but it does not change. Is there any easy way to do it? I am looking for something like verbose_name, that is used in Django Models. My serializers.py is: class LoginSerializer(serializers.Serializer): username = serializers.CharField(source='Email') password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError('Incorrect Credentials Passed.') Again, I am using the default User Model, and I don't want to overwrite/override/extend the User Model. I just want to change the name of the field username on the frontend to be shown as email. Any help will surely be appreciated. -
Passing a Dictionary from Django view to a Django template
I am trying to pass the following context from views.py to a Django Template: views.py: def home(request): context = { 'dict_1': {'key_1': ['val_11', 'val_12'], 'key_2': ['val_21', 'val_22']} } return render(request, 'app/home.html', context) home.html: <script type="text/javascript"> var java_dict = {{ dict_1 }}; console.log(java_dict); </script> This throws an error: Uncaught SyntaxError: Unexpected token '&' Upon investigating, I see that the dictionary in javascript is read as follows: {&#39;key_1&#39;: [&#39;val_11&#39;, &#39;val_12&#39;], &#39;key_2&#39;: [&#39;val_21&#39;, &#39;val_22&#39;]} which probably means that the quotes-character (') is read incorrectly. How do I fix this issue? -
How to fix python manage.py error messages
I'm just getting started with Django, and earlier today, I watched a YT video on how to set it up in pycharm. I ran the python manage.py runserver in the pycharm terminal afterwards and it worked, the development server worked. I wrote some url code, and tried running it again and it still shows the link, but when I click on it, it takes me to a page that says your internet access is blocked... Back in the terminal, after the Quit the server with CTRL-BREAK line, it says there is an exception in thread django-main thread, and a bunch of error messages and missing flies list pops up -
Django- Incorporate django-sites with multiple models
I am trying to build a white labled product and I am thinking to use django-sites module. I have multiple models of a particular site. I have found an example like add foreign key of a Site model to a single model. but adding foreign key of Site model to each and every model in every api call, I don't think is a best practice. Is there any other way to define once and it will add automatically Site id like we use abstract classes for created_at and so on. Thanks. -
How can I implement an edit profile page?
I'm trying to make my view for edit profile, but it doesn't work when saving data, I don't know what I'm doing wrong if it should work like a normal form, right? The form can be seen in my template, the problem is when saving, it doesn't save anything views.py def EditProfilePageView(request): if request.method == 'POST': # dictionary for initial data with # field names as keys context = {} # add the dictionary during initialization form = RegisterForm(request.POST or None) if form.is_valid(): form.save() return redirect('profile') context['form'] = form return render(request, 'Usuarios/edit-profile.html', context) form.py class RegisterForm(UserCreationForm): username=forms.CharField(label="Usuario",widget=forms.TextInput(attrs={'class': 'form-control'})) email=forms.EmailField(widget=forms.TextInput(attrs={'class': 'form-control'})) phone1=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) phone2=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) fax = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) website = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) socialMedia1 = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) socialMedia2 = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) socialMedia3 = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) alternativeContact = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) country = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) address = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) city = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) state = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) zip = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) password1 = forms.CharField( label="Contraseña", widget=forms.PasswordInput(attrs={'class':'form-control', 'type':'password', 'align':'center'}), ) password2 = forms.CharField( label="Confirma Contraseña", widget=forms.PasswordInput(attrs={'class':'form-control', 'type':'password', 'align':'center'}), ) class Meta: model=User fields=['phone1','phone2','fax','email','website','socialMedia1','socialMedia2', 'alternativeContact','country','address','city','state','zip'] widgets = { 'password': forms.TextInput(attrs={'class': 'form-control'}), } -
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 …