Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to modify Django template variable with JS and return it changes on it
I would like to pass a list of ids to a view when i click on a link: <a href="{% url 'app:manage_ids' %}?ids={{ids}}"> So i have created a template var and pass it to js: {% with ids="" %} <script type="text/javascript"> window.ids = "{{ ids }}"; </script> {% endwith %} I manage object ids when click on checkbox, adding or removing it to a list: $('.checkbox').change(function() { var id = $(this).val(); // if django template var is empty var list_ids = []; // else var list_ids = window.ids; if ($(this).is(':checked')) { list_ids.push(id); // here i have to save it on a django template var to use it on the click link } else { const index = list_ids.indexOf(id); if (index > -1) { list_ids.splice(index, 1); // here i have to save it on a django template var to use it on the click link } } }); Anybody could help me about how to do it ? Thanks you so much. -
Update ImageField without forms in django
I am trying to update an image field in django model from an html form. Update goes fine except for the image field. Please, tell what's wrong in my code. That's my views.py file: ''' def update_product(request, product_id): if request.method=="POST" model_name=request.POST['model_name'] image = request.FILES ['image'] Product.objects.filter(id=product_id).update(model_name=model_name, image=image) return redirect ('listing) ''' That's my html file: ''' <form action={% url update_product product.id %} method ="POST enctype='multipart/form-data'> {% csrf_token %} <input type='text' name='model_name'> <input type='file' name='image'> <button type='submit'> Update </button> </form> -
Can't backup my PostgreSQL database [ peer authentication failed for user "USER" ]
sql file that I backedup a long time ago of my website database and now I'm trying to use it but everytime I use: psql -U <username> -d --password <dbname> -1 -f <filename>.sql it gives me this error peer authentication failed for user "USER" I tried to edit the pg_hba.conf but that did nothing. how can I do it ? -
Missing DIV in admin header in Django on another page
I've modified in admin/base.html of Django the header to include an icon to click to display the dropdown menu but when I'm going to Change Password page, I'm seeing the old default navigation links. How can I modify the Change Password page to include the div with class "dropown" which is present in base.html but not in password_change page? Why is missing here? Thank you for any advice given! Below is the header modified by me to include a dropdown: <!-- Header --> <div id="header"> <div id="branding"> {% block branding %}{% endblock %} </div> {% block usertools %} {% if has_permission %} <div id="user-tools"> <div class="back-ground"> {% block welcome-msg %} {% trans 'Welcome,' %} <strong>{% firstof user.get_short_name user.get_username %} !</strong> {% endblock %} {% block userlinks %} {# {% if site_url %}#} {# <a href="{{ site_url }}">{% trans 'View site' %}</a> /#} {# {% endif %}#} {% if user.is_active and user.is_staff %} {% url 'django-admindocs-docroot' as docsroot %} {% if docsroot %} <a href="{{ docsroot }}">{% trans 'Documentation' %}</a> / {% endif %} {% endif %} </div> <div class="dropdown"> <button onclick="openDropdown()" class="dropbtn"><img src="{% static "admin/img/user.svg"%}" alt="User Menu" style="height: 30px;"></button> <div id="myDropdown" class="dropdown-content"> {% if user.has_usable_password %} <a href="{% url 'admin:password_change' … -
Django, how to extract values list montly from DateField?
I have the following models: class Materiale(models.Model): sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True) quantita=models.DecimalField(') prezzo=models.DecimalField() data=models.DateField(default="GG/MM/YYYY") I wanna calculate the value given by the following expressions PREZZO*QUANTIA in a monthly's view, but my code does not work: Monthly_views=Materiale.objects.filter(data__year='2020').values_list('month').annotate(totale_mensile=F(('quantita')*F('prezzo'))) -
Is Django 2.2 compatible with Django 3.0
I am using Django version 2.2. Is it possible to use Django 3.0 format on my project without any problems? -
Django 3.0 Reverse for slug based name in urls.py cannot be called in template
I am using Django 3.0 to create a basic website and I am obviously still new. My issue is that I am not able to dynamically call the DetailView using the {% url 'my_page' %} format. I set up an About Us section for which the slug is about-us, and my ulrs.py has name="<-slug:slug>" (I figured this isn't right), and get NoReverseMatch at /, Reverse for 'about-us' not found. 'about-us' is not a valid view function or pattern name. I have a Section model set up as follows in models.py: from django.utils.text import slugify class Section(models.Model): section_title = models.CharField(max_length=200, unique=True) section_bg = models.ImageField(upload_to='section-bg') slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.section_title) super(Section, self).save(*args, **kwargs) def __str__(self): return self.section_title The relevant views.py view: from django.views.generic.detail import DetailView from . import models class SectionView(DetailView): template_name = "home/section.html" model = models.Section def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context And finally, in urls.py: urlpatterns = [ ... path(r'home/<slug:slug>/', views.SectionView.as_view(), name='<slug:slug>'), ... ] Thanks in advance for the help! -
Overlapping div in HTML
I am making a Checkout page using Django and the end result doesn't show the street name as attached. Here is the form for the HTML <div class="md-form mb-5"> {% comment %} <input type="text" id="address" class="form-control" placeholder="1234 Main St"> {% endcomment %} {{ form.street_address }} <label for="address" class="">Street Address</label> </div> <!--address-2--> <div class="md-form mb-5"> {% comment %} <input type="text" id="address-2" class="form-control" placeholder="Apartment or suite"> {% endcomment %} {{ form.apartment_address }} <label for="address-2" class="">Apartment_address (optional)</label> </div> and here is the form.py class CheckoutForm(forms.Form): stree_address = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': '1234 Main St', 'class': 'form-control' })) apartment_address = forms.CharField(required=False, widget=forms.TextInput(attrs={ 'placeholder': 'Apartment or suite', 'class': 'form-control' })) and here is the result attached -
Django Pass Custom Parameters to Formset
I am using formsets to make multiple forms and display them. I have a subform class Ent_Annotator(forms.Form): ent_cat = forms.ChoiceField(choices=ent_cats) And a form with a custom parameter, name class Ent_Annotation_Form(Ent_Annotator): def __init__ (self,*args,name,**kwargs): self.name = name super().__init__(*args,**kwargs) In my view, I want to create several of these forms in a formset by iterating through a list of names. I know how to pass kwargs with form_kwargs={'name':name}, but I can only pass a single value per kwarg. A method to pass multiple values or another way to display multiple forms on a page with so much variable information would be appreciated. -
Getting 404 error after running Django Project. Bootstrap is also not loading
This is the link of my project. I checked other questions for the same issue but did not find a solution for this issue. This is my project link. -
Reverse with " " no argument Not Found. Django (NoReverseMatchError
I am a beginner in django. I have a problem with class based delete view as its returning a no reverse match error. A dollar symbol is there at the end of the url which I didn't provide. This is the error: NoReverseMatch at /posts/myhome/ Reverse for 'delete_post' with no arguments not found. 1 pattern(s) tried: ['posts/(?P<slug>[^/]+)/delete$'] views.py class DeletePostView(BSModalDeleteView, LoginRequiredMixin, UserPassesTestMixin): model = Post success_url = reverse_lazy('posts:myhome') template_name = 'posts/delete_post.html' def test_func(self): post = self.get_object() if self.request.user == post.user: return True return False html code: <div class="content-section"> <form method="POST"> {% csrf_token %} <div class="modal-body"> <fieldset class="form-group"> <legend class="border-bottom mb-4" style="text-align: center;">Delete Post</legend> <h4 style="text-align: center;">Are you sure you want to delete this post?</h4> </fieldset> <div class="form-group" style="text-align: center;"> <button class="btn btn-sm btn-outline-danger" type="submit">Yes, Delete</button> %}">Cancel</a> --> </div> </div> </form> </div> urls.py urlpatterns = [ path('myhome/', HomePostListView.as_view(), name='myhome'), path('create/', CreatePostView.as_view(), name='create_post'), path('<slug>/', views.detail_post, name='detail_post'), path('<slug>/update', views.update_post, name='update_post'), path('<slug>/delete', views.delete_post, name='delete_post'),] -
Errno 13 Permission denied: '/static' Django file upload issue
I recently deployed my django wesite on apache using mod_wsgi. I was testing everything to make sure i can work on more important things without having to go back and fix something. I was uploading a .xlsx file on the django admin and this error came up: [Errno 13] Permission denied: '/static' This is my settings.py STATIC_ROOT and STATIC_URL line: STATIC_URL = /static/ #STATIC_ROOT = home/alexholst/excelsite/static STATIC_ROOT = os.path.join(BASE_DIR, "..", "static") #STATIFILES_DIR = [ # os.path.join(BASE_DIR, "static") #] Ive serched online for the past 2 hours to no avail. What could this be? -
Django TabularInline raise ValidationError on a specific row
before posting the question here I have checked Raise validation error in inline field Django. But this still does not answer my question, because the error thrown is in the form but not on the exact row. In MyModel.clean function if I raise Validation error I can specify the field which is bad. But how can I raise an error on the bad row of a TabularInline? class MyBaseFormSet(BaseInlineFormSet): def clean(self): super(MyBaseFormSet, self).clean() for index, form in enumerate(self.forms): if form.cleaned_data and not form.cleaned_data.get('DELETE', False): raise ValidationError('test') class MyInline(admin.TabularInline): model = MyModel formset = MyBaseFormSet -
Render dictionary in django template
I have groupby clause built in a django view and then I intend to display the dictionary created in a template. The problem here is that the template instead of displaying values, displays the header fields repeated (screenshot attached so it makes more sense). Any assistance will be appreciated ! Here is the view def did_count_region_groupby(request): region_carrier_groupby = DID_Definition_Model.objects.all().values('region_carrier').annotate(DID_Count=Count('region_carrier')).order_by('DID_Count') region_carrier_groupby_dict = {'region_carrier_groupby' : region_carrier_groupby} return render(request, 'MASTERHANDLER/did_count_region_groupby.html', region_carrier_groupby_dict) and here is the template {% for key, value in region_carrier_groupby %} <tr> <td> {{key}}</td> <td>{{value}}</td> </tr> {% endfor %} -
update a model's field from another model in django
my models.py is : class clients(models.Model): client_id = models.IntegerField(unique=True, primary_key=True ) ' ' money = models.DecimalField(max_digits=10, decimal_places=2,default=0) class transfermoney(models.Model): first_client_id = models.IntegerField() second_client_id = models.IntegerField() amountofmoney = models.PositiveIntegerField() time = models.TimeField(auto_now=True) date = models.DateField(auto_now=True) my serializers.py is : class moneytransfer(serializers.ModelSerializer): def validate(self, data): try: clients.objects.get(client_id = data['first_client_id']) clients.objects.get(client_id = data['second_client_id']) except clients.DoesNotExist: raise serializers.ValidationError("One of the clients does not exist") return data class Meta: model = transfermoney fields = ('__all__') read_only_fields = ('time','date',) my views.py is : class transferingmoney(APIView): def post(self,request): serializer = moneytransfer(data=request.data) if serializer.is_valid(): serializer.save() def update(self,data): client_1 = clients.objects.get(client_id=data['first_client_id']) client_2 = clients.objects.get(client_id=data['second_client_id']) client_1.money -= data['amountofmoney'] client_2.money += data['amountofmoney'] client_1.save() client_2.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i'm using django rest framework, when i made a post request to "transferingmoney" , it made a record into the "transfermoney" model table ,, but it did not update the "money" field for client_1 or client_2 in the "clients" model please can you help me, what should i do ? -
How to display custom HTML in an autocomplete field in Django admin?
I want to open the related object popup when the user clicks on a selected value in a Django admin autocomplete multi-select field. This requires adding custom HTML to selected values. I did not find any straightforward way to add custom HTML to Django admin built-in autocomplete field, so I'm using the ModelSelect2Multiple field from django-autocomplete-light. So far I haven't found any better way than to stick the HTML into model __str__() and mark it safe. This is admittedly a hack, but works well with ModelSelect2Multiple data-html attribute when making new selections. However, it does not work with saved selections. The models are as follows: class Author(models.Model): name = models.CharField(_('name'), max_length=160) profession = models.CharField(_('profession'), max_length=100) phone = models.CharField(_('phone'), max_length=20, blank=True) email = models.EmailField(_('email'), blank=True) def __str__(self): change_url = reverse('admin:books_author_change', kwargs={'object_id': self.id}) return mark_safe('<span onclick="showRelatedObjectPopup(' f"{{href: '{change_url}?_popup=1', id: 'change_id_authors'}})" f'">{self.name} – {self.profession}</span>') class Book(models.Model): authors = models.ManyToManyField(Author, verbose_name=_('authors'), blank=True) ... The admin configuration is as follows: from dal import autocomplete @admin.register(Book) class BookAdmin(admin.ModelAdmin): def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == 'authors': return forms.ModelMultipleChoiceField( required=False, label=Author._meta.verbose_name_plural.title(), queryset=Author.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='author-autocomplete', attrs={'data-html': True})) return super().formfield_for_foreignkey(db_field, request, **kwargs) When adding an author to the Authors field in the Book change view, the HTML element … -
Migrations Are Not Taking Effect (Django - Python)
I think I have followed the correct process for getting migrations to work but the changes have not seem to have taken effect. I am trying to add a slug field to my Comments class field=models.SlugField(blank=True, max_length=500). Schema sqlite> .schema blog_Comment CREATE TABLE IF NOT EXISTS "blog_comment" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(80) NOT NULL, "email" varchar(254) NOT NULL, "body" text NOT NULL, "created_on" datetime NOT NULL, "active" bool NOT NULL, "post_id" integer NOT NULL REFERENCES "blog_post" ("id") DEFERRABLE INITIALLY DEFERRED); CREATE INDEX "blog_comment_post_id_580e96ef" ON "blog_comment" ("post_id"); sqlite> 0017_auto_20200426_2137.py # Generated by Django 2.2.6 on 2020-04-26 14:37 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('blog', '0016_auto_20200426_0209'), ] operations = [ migrations.AlterField( model_name='comment', name='created_on', field=models.DateTimeField(default=datetime.datetime(2020, 4, 26, 14, 37, 27, 23071, tzinfo=utc)), ), migrations.AlterField( model_name='comment', name='url', field=models.SlugField(blank=True, max_length=500), ), migrations.AlterField( model_name='post', name='date_posted', field=models.DateTimeField(default=datetime.datetime(2020, 4, 26, 14, 37, 27, 23071, tzinfo=utc)), ), ] class Comment(models.Model): class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on= models.DateTimeField(default = timezone.now()) active = models.BooleanField(default=False) url= models.SlugField(max_length=500, blank=True) -
How to do pip install with subprocess in Django Gunicorn server
I need to install a pip package according to given name. I am trying to install package via subprocess.run(). In Django runserver (its called dev. server I guess), everything works fine but in production environment where we have gunicorn, program just freezes after subprocess.run() What am I doing wrong? Can someone points me the problem ? I see subprocess start but I never see subprocess end line in the log file. I tried to put something like ls -la to the command variable. It also works like that way def install(path): try: command = r"pip install {} --disable-pip-version-check".format(path) logger.info("subprocess start") process = subprocess.run(command, shell=True, check=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) logger.info("subprocess end") if(process.stdout): logger.info("Package Installation Output: {}".format(process.stdout)) if(process.stderr): logger.error("Package Installation Error - Return 0 : {}".format(process.stderr)) except Exception as err: logger.error("Package installation error: {}".format(err)) -
How can i define user detail view in multiuser blog app?
I'm building a blog app with multi users and i'd like to have this ability that every logged user could click on every username (post author) and see details of this profile my current function gives me only details for current logged in user no mattew what user i click. i have similar CBV function working for post list view that shows me all the posts for each user and i've tried to do the same but it didn't worked.. Please help ;) view > @login_required def profile_detail(request): context = { 'profile': Profile.objects.all() } return render(request, 'users/user_detail.html', context) model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args,**kwargs): super().save(*args,**kwargs) img = Image.open(self.image.path) if img.height >300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) url pattern path('profile-detail/', user_views.profile_detail, name='user_detail'), link <a class="mr-2" href="{% url 'user_detail' %}">{{ post.author }}</a> -
get_or_create not creating my object with attributes that I need
So I am attempting to get_or_create a conversation object. Now, if the object is already created, the code works fine. But if it's not created, it will create the conversation object, BUT not with the members that I am trying to pass. An empty conversation object. members is a manytomany field to User. What am I doing wrong here? views/message def message (request, profile_id): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): form.save() return redirect('dating_app:messages', profile_id) else: conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create(members= members.set(profile_id)) other_user = conversation.members.filter(id=profile_id).get() form = MessageForm({'sender': request.user, 'conversation': conversation}) context = {'form' : form, 'other_user': other_user } return render(request, 'dating_app/message.html', context) models.py/Conversation class Conversation(models.Model): members = models.ManyToManyField(settings.AUTH_USER_MODEL) -
Django 3 how to show block content? the content block went invisible in templates when extended base html
Django 3 the content block went invisible in templates when extended base html The index.html page used to displays a bunch of articles then there are single pages of them single.html they both page type extend from base.html. After I added pagination only the pagination part displays. I am not getting any errors in the vs code problems section. Missing the main content block in both index.html and single pages index.html this is supposed to extend from base.html and load block content of the cards {% extends "base.html" %} {% block title %}Meteorite Collection{% endblock title %} {% block content %} {% for article in articles %} <div> <li class="card m2 p-3 card-body" style="width: 18rem;"> <img class="card-img-top" src="{{article.image.url}}" alt="{{article.title}}"> <a href="{% url 'single' article.id%}"><h2>{{article.title}}</h2></a> <img class="card-img-top" src="{% url 'single' article.id%}" alt="{{article.title}}"> <p class="card-text">{{ article.content | truncatewords:50 }}</p> <p>Posted in: {{article.category}}, Posted by: {{article.author}}</p> <a href="{% url 'single' article.id%}" class="btn btn-primary">Goto {{article.title}} Details</a> </li> </div> {% endblock content %} base.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>{% block title %}{% endblock title %}</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> … -
Django3 - manage.py commands stuck
I have a big problem wih Django3: basically, whenever I type a command for manage.py, the prompt gets stuck and never carries on the command without even crashing. I tried several times the commands "runserver" and "startapp" and waited beetween 10 minutes and an hour, but I never managed to run the server or create an app because I launch the command and the prompt gets stuck. Strangely enough, to test things out, I created a project, an app and run the server immediately after I installed Django3 and everything worked fine, I even have that project on github. Then I shut down the computer and now nothing works. Also, I noticed in the Windows resource monitor that whenever I try to lauch a command suddenly Python processes start to appear and disappear uncontrollably, and since I never had an issue like this I'm absolutely clueless about everything. So... What's happening? Did someone have the same problem? I have the lastest Windows update, the latest Python3 (I got it via Windows Store) and the Latest Django3 (I got it via pip). I'd include a stacktrace or some sort of log but, since nothing crashes, I suppose no log gets done: … -
How can I using my LWS host SMTP mail service in my Django project?
I discovered Django framework, and I used it to develop my website. The development is finished but I need to improve a mail form in "Contact" section to visitors can contact me. I will host my website at LWS hoster. I've created an email account and I want to use it. This is my setting.py mail configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.****.io' EMAIL_HOST_USER = 'contact@*****.io' EMAIL_HOST_PASSWORD = '****' EMAIL_PORT = 465 Unfortunately, it's not working. When I confirm the contact form, my page wait endlessly and finished with "SMTPServerDisconnected". If anybody host a Django website at LWS and use their mail service... Or maybe anyone has an idea? Thanks for your help. -
is_valid() function returning false based in the traceback from a IntergerField in forms
is_valid() function returning false based in the traceback from a IntergerField in forms. I am probably missing out on something in the is_valid() line of code. Any input is appreciated. traceback [27/Apr/2020 02:23:07] "GET / HTTP/1.1" 200 10413 5 <bound method BaseForm.is_valid of <IdForm bound=True, valid=Unknown, fields=(id)>> <tr><th><label for="id_id">Song ID:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="id" required id="id_id"></td></tr> <tr><th><label for="id_id">Song ID:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="id" required id="id_id"></td></tr> <bound method BaseForm.is_valid of <IdForm bound=False, valid=Unknown, fields=(id)>> [27/Apr/2020 02:23:09] "POST /playlist/add/5/ HTTP/1.1" 200 4406 forms.py class IdForm(forms.Form): id = forms.CharField(label='Song ID', required=True) template <form action="{% url 'playlist_add' P_id=p.id %}" method="POST" enctype="multipart/form-data" value="{{request.post.id}}"> {% csrf_token %} {%for field in form%} {{field.errors}} {{field}} {%endfor%} <button type="submit">Add Song</button> </form> views.py class PlaylistAddFormFunction(View): form_class = IdForm #determine fields template = 'homepage_list.html' def get(self, request): form = self.form_class(None) print('soo') return render(request, self.template, {'form':form}) @method_decorator(login_required) def post(self, request, P_id): print(P_id) form = IdForm(request.POST) print(form.is_valid) print(form) if form.is_valid(): print('xoo') id = form.cleaned_data['id'] song = Song.objects.get(id=id) playlist, created = Playlist.objects.get_or_create(id=P_id) playlist.song.add(song) return redirect('home') else: print(form) form = self.form_class(None) print(form.is_valid) return render(request, self.template, {'form':form}) -
Django - Message translation in template still show original language version
Translations in the same function for form.error work and messages are displayed in a different language, but for "messages" the text is still displayed in English in the template views.py from django.utils.translation import ugettext_lazy as _ form.errors['__all__'] = form.error_class([_('Bad pin')]) Works, i see translated version in my language messages.add_message(self.request, messages.INFO, _('Bad pin')) Didn't work, in the template after entering {{message}}, I see the English oryginal version Settings.py 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "account.middleware.LocaleMiddleware", 'django.middleware.common.CommonMiddleware', "account.middleware.TimezoneMiddleware",