Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /signup/ - Reverse for '<WSGIRequest: POST '/signup/'>' not found
The porject I am working on is the blogging website and I am stuck at this signup process, I want it to function like after signup, the user lands on the home page, but instead this is showing me the above error views.py: def handleSignup(request): if request.method == 'POST': username = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # creating users myuser = User.objects.create_user(username, email, pass1) myuser.first_name = fname myuser.last_name = lname myuser.save() messages.success(request, 'your account have been successfully created!') return redirect(request, "/home.html") else: return HttpResponse("error 404 not found") urls.py: urlpatterns = [ path("", views.home, name="home"), path("contact/", views.contact, name="contact"), path("about", views.about, name="about"), path("signup/", views.handleSignup, name="handleSignup"), ] forms in base.html: <form action="/signup/" method="post"> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" name = 'username' placeholder="choose a unique username"> </div> <div class="form-group"> <label for="fname">Firstname</label> <input type="text" class="form-control" id="fname" name = 'fname' placeholder="First Name"> </div> <div class="form-group"> <label for="lname">Lastname</label> <input type="text" class="form-control" id="lname" name= 'lname' placeholder="Last Name"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" id="email" name = 'email' placeholder="email@example.com"> </div> <div class="form-group"> <label for="pass1">Choose Password</label> <input type="password" class="form-control" name = 'pass1' id="pass1"> </div> <div class="form-group"> <label for="pass2">Confirm password</label> <input type="password" class="form-control" name = … -
How to change CSS properties from within django HTML template logic
Newbie question I presume: How do I change some CSS property (// change background image of parent div) of the parent element from within the logic in the HTML template? Do I really need to implement JS for this? <div class="exercise-items-wrapper"> {% if error %} {{ error }} {% else %} {% for x in exercise %} <div class="exercise-item"> {{x.name}} {% if x.primary_focus == 'CO' %} // change background image of parent div {% endif %} {% if x.friend_verified %} <img src="{% static 'main/images/fv.svg' %}" height="14px"> {% endif %} <p id="exercise-level" class="exercise-level">lv. VII</p> {% if x.video_verified %} <img src="{% static 'main/images/vv.svg' %}" height="14px"> {% endif %} </div> {% endfor %} {% endif %} </div> -
Django templates - How to expand related record data instead of record id when assigning to JS variable?
Some code: models.py class User(models.Model): name = models.CharField(max_length=60) group = models.ForeignKey(Group, on_delete=models.CASCADE) views.py users = User.objects.all() # sent to template template.html let users = jQuery.parseJSON('{{ users|jsonify|safe }}') tags.py @register.filter(is_safe=True) def jsonify(obj): if isinstance(obj, QuerySet): return serialize('json', obj) return json.dumps(obj) This going to assign objects where group field is id number of record in Group model. I need to get all data of this record. How to expand this data? -
Display multiple dynamic object with for loops in templates
So to summary, my database structure is like this: test |_ question |_ choice |_ choice |_ choice |_ question |_ choice |_ choice |_ choice Now I want to display all of the choices of each question on a single page. My views.py: def index(request): data = { 'greeting': 'Welcome User!', 'form_test': forms.TestForm, 'form_question': forms.QuestionForm, 'form_choice': forms.ChoiceForm, 'test': models.Test.objects.get(pk=1), 'questions': models.Question.objects.filter(test_id__exact=1), } questions = models.Question.objects.filter(test_id=1) for question in questions: data['choices_{}'.format(question.id)] = models.Choice.objects.filter(question_id=question.id) print(data) return render(request, 'et_app/index.html', context=data) So technically if I have 2 questions, my data would look something like this: { ... 'choices_1': ... 'choices_2': ... ... } Now, my problem is on displaying these choices on the templates. I tried: {% for question in questions %} <h4>Q: {{ question.content }}</h4> <p>Choices:</p> <ul class="list-group"> {% for choice in 'choices_{}'.format(question.id) %} <li class="list-group-item">{{ choice.content }}</li> {% endfor %} </ul> {% endfor %} It just broke the whole thing. I'm relatively new to Django so forgive my naiveness. How can I fix this? Thanks a lot! -
Use a scan device with django
How is the best native way to scan an image using a device? Im working on web project with Django. I just googled and as far as i know there is a way to get this done with html5 and getusermedia() api. Thanks in Advance, -
Django Page not found with post request
So I am new to Django and I'm trying to create a HTML form (just following the tutorial for the name input) and I can input the name but can't direct to the /thanks.html page. $ views.py from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import NameForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) print(form) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/polls/thanks.html') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'name.html', {'form': form}) $ name.html <html> <form action="/polls/thanks.html" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> <html> $ /mysite/urls from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] $ mysite/polls/urls.py from django.urls import path from polls import views urlpatterns = [ path('', views.get_name, name='index'), ] When I go to to the page, I can enter my name fine but … -
Django form is not showing is not generating in html template
I am using django.contrib.auth.views.LoginView for views and here are my files html <form method="GET"> {% csrf_token %} {{ formlog|crispy }} </form> views.py def index(request): formlog = auth_views.LoginView.as_view() if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.supervalid() form.save() username = form.cleaned_data.get('username') messages.success(request, f'Dear {username} you have been created a new accound!') return redirect('main') else: form = UserRegisterForm() return render(request, 'main/index.html', {'form': form, 'formlog': formlog}) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() name_and_surname = forms.CharField(min_length=5, max_length=30) def supervalid(self): expr_a = User.objects.filter(name_and_surname=self.cleaned_data['name_and_surname']).exists() expr_b = User.objects.filter(email=self.cleaned_data['email']).exists() if expr_b: raise ValidatioError(f'There already exists user with that email, use another one ;)') if expr_a: raise ValidatioError(f'This name is already used, sorry') class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] please help istead of talking about things that dont metter. Thanks for help ;) -
Django doesn't load static file and throws error although syntax is correct - is VS Code the culprit?
I have been working with Django for a few days and I'm trying to get the hang of static files and how to integrate them in my project. I have the following code: <div class="background_image" style="background-image: url({% static 'images/home_slider.jpg' %});"> </div> And Python throws this error for this specific block of code: I have more than 30 cases in the same file where I used this pattern {% static 'something' %} and it works in all cases. The only difference between these cases in the one above (that's not working) is that the one above is the only one where I apply the style directly on the HTML tag. I am am my wits' end. From what I researched, the syntax seems to be correct for adding a background image directly in HTML so I'm starting to believe that the error is caused by the fact that VS code is formatting my code in a super weird way when saving and I get something like: <div class="background_image" style=" background-image: url({%static'images/home_slider.jpg'%}); " ></div> Any suggestion would be appreciated. Thank you. -
ValueError at /signup/ The given username must be set
so basically I have been building this blogging website and now I am stuck at this point of the Signup process, the whole work is done using django views.py: def handleSignup(request): if request.method == 'POST': # getting user parameters username = request.POST.get('username') fname = request.POST.get('fname') lname = request.POST.get('lname') email = request.POST.get('email') pass1 = request.POST.get('pass1') pass2 = request.POST.get('pass2') # fname = request.POST['fname'] # lname = request.POST['lname'] # email = request.POST['email'] # pass1 = request.POST['pass1'] # pass2 = request.POST['pass2'] # creating users myuser = User.objects.create_user(username = username, email = email, password = pass1) myuser.first_name = fname myuser.last_name = lname myuser.save() messages.success(request, 'your account have been successfully created!') return redirect(request, 'home') else: return HttpResponse("error 404 not found") form in base.html: <form action="/signup/" method="post"> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" placeholder="choose a unique username"> </div> <div class="form-group"> <label for="fname">Firstname</label> <input type="text" class="form-control" id="fname" placeholder="First Name"> </div> <div class="form-group"> <label for="lname">Lastname</label> <input type="text" class="form-control" id="lname" placeholder="Last Name"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" id="email" placeholder="email@example.com"> </div> <div class="form-group"> <label for="pass1">Choose Password</label> <input type="password" class="form-control" id="pass1"> </div> <div class="form-group"> <label for="pass2">Confirm password</label> <input type="password" class="form-control" id="pass2"> </div> {% csrf_token %} <button type="submit" class="btn btn-primary">Submit</button> </form> now I am getting this error: ValueError … -
Django path in admin absolute instead relative
In my admin project i have a situation like this: settings.py: STATIC_URL = '/myproject/static/' models.py: class v_candidatura(models.Model): ... c_cv = models.FileField(upload_to='myproject/static/docs', max_length=254, validators=[FileExtensionValidator(['pdf']),validate_fsize], verbose_name="CV") .... admin.py: class vcandidaturaAdmin(admin.ModelAdmin): list_filter = ('c_mansione',) list_display = ('c_data', 'c_sur', 'c_name', 'c_dob', 'c_en', 'c_de', 'c_cv') ordering = ('-c_data',) admin.site.register(v_candidatura, vcandidaturaAdmin) Now if i log into admin site and go to the 127.0.0.1:8000/admin/myapp/v_candidatura/ and click on c_cv link Django atach begore c_cv link the wole path 127.0.0.1:8000/admin/myapp/v_candidatura/, how can i define my href link for ahref in django admin site? for example i would clicking on my c_cv django admin list field open 127.0.0.1:8000/<c_cv path> So many thanks in advance admin.py -
django ecommerce communication
I am building an e-commerce app for fast food company using Django. There will be a dash-board based on Django admin that will give the vendor control over activating offers or closing shop etc. What I am trying to implement is that once the customer places the order and a message flashes for the vendor to accept or reject. I am not sure what I will need to use to implement that two-way communication between the customer and the vendor admin. Any ideas or alternatives will be very helpful. Thanks -
How to setup carousel slider in Django with records?
I am trying to implement carousel slider in my website, I have ForeignKey relation between Project and Image, I have multiple image store in Image model. It Means that a project can have multiple images, and i want to display those project images in slider, Please let me know how I can display the images in slider, Because currently my images are coming in vertical format. Here is my index.html code, here i am trying to display all images in slider, but it's not working, Please check my code and solve my issue. <div id="carousel-thumb" class="carousel slide carousel-fade carousel-thumbnails list-gallery pt-2" data-ride="carousel"> <!--Slides--> <div class="carousel-inner" role="listbox"> {% for i in project.projectimage.all %} <div class="carousel-item active"> <img class="d-block w-100" src="{{i.project_image.url}}" alt="slide" style="height: 420px;"> </div> {% endfor %} </div> <!--Controls starts--> <a class="carousel-control-prev" href="#carousel-thumb" role="button" data-slide="prev"> <span class="lnr lnr-arrow-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carousel-thumb" role="button" data-slide="next"> <span class="lnr lnr-arrow-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> -
django rest framework defaultRouter without models
I am new to Python and Django (rest framework) and I love the DefaultRouter feature, by also giving an "API ROOT" page. But, I can only use the defaultrouter.register() method with viewsets. How to make a custom route without a model? For example I will have a "POST" route that multiplies 2 values from the body. (so body is something like {"value1":123, "value2":456} Is it good practice to use viewsets for everything? How should I implement a custom (multiply) function? I will have a serializer with the 2 params? And where to implement the code? Am I doing things right? -
Load data in memory during server startup in Django app
I am creating a Django app wherein I need to load and keep some data in memory when the server starts for quick access. To achieve this I am using Django's AppConfig class. The code looks something like this : from django.core.cache import cache class myAppConfig(AppConfig): name = 'myapp' def ready(self): data = myModel.objects.values('A','B','C') cache.set('mykey', data) The problem is that this data in cache will expire after sometime. One alternative is to increase the TIMEOUT value. But I want this to be available in memory all the time. Is there some other configuration or approach which I can use to achieve this ? -
Using Q object with variable
I'd like to use the django.db.models.Q object in a way that the query term is coming from a variable. What i'd like to achieve is identical to this: q = Q(some_field__icontains='sth') Obj.objects.filter(q) , but the some_field value should come from a variable: field_name='some_field' q = Q('%s__icontains=sth' % field_name) Obj.objects.filter(q) , but this solution does not give me the correct result of course. I also tried to use dictionary this way: dt = {'%s__icontains' % field_name: 'sth'} q = Q(**dt) Obj.objects.filter(q) , but this also fails on the result. How could I use the Q object using variables as query term? Thanks. -
Django edit form won't validate on form.save() with user field
I recently added a "user" field to my Game model. I can create a new game that works fine; it's when I want to allow a user to edit the instance of a game where I am running into problems. My view is calling the form = GameForm(request.POST, instance=game) where game = Game.objects.get(pk=id). The form is pre-populated with the correct data, but when it's submitted, whether there are updates or not, the form is not validating. It sees it as a POST, but cannot get inside the if form.is_valid() conditional. And this is ever since I added the user field. I am using the default Django User model, and the field name is called "owner." It is set up as a ManyToManyField(User, blank=True) as users can own many games, and games can be owned by many users. Django forms the Many-To-Many "through" table, but I don't want the user to be able to change who owns what. I have it as a hidden field in my forms.py so a user can't change it. Model class Game(models.Model): game_title = models.CharField(max_length=100, verbose_name='Game Title', db_column='game', blank=False, null=False, unique=True) game_developer = models.CharField(max_length=100, verbose_name='Developer', db_column='developer', blank=True, null=True) game_release = models.DateField(max_length=50, verbose_name='Release Date', db_column='release_date', blank=False, null=True) … -
Django: GenericInline combined with ModelMultipleChoiceField
Hi I'm working on an adminform which allows either selecting an existing object or add a new one in an inline of a GenericRelation. See the following example Models: from stdimage class Photograph(DeepZoom): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(default=0) profile = GenericForeignKey("content_type", "object_id") img = JPEGField(...) img_alt = models.Charfield(max_lenght=300) ... and class MyProfile(models.Model): name = models.CharField(max_length=200, default="") photos = GenericRelation(Photograph, null=True) To achieve "select existing" I wrote a custom form for the admin site class SomeForm(forms.ModelForm): choose_img = forms.ModelMultipleChoiceField(queryset=Photograph.objects.all(), required=False) def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) self.initial.update({"choose_img": self.instance.photos.all()}) def save(self, commit=True): chosen_imgs = set(self.cleaned_data.pop("choose_img")) instance = super(SomeForm, self).save(False) if commit: instance.save() current_imgs = set(instance.photos.all()) for img in chosen_imgs - current_imgs: instance.photos.add(img) for old_img in current_imgs - chosen_imgs: old_img.profile = None old_img.object_id = 0 old_img.save() return instance and add it with the PhotographInline (basically just an instance of GenericTabularInline) to the admin site class MyProfileAdmin(admin.ModelAdmin): form = SomeForm inlines = [ PhotographInline, ] So far so good. The new save method does what i expect when selecting Photograph's in the choose_img field. If I deselect a Photograph it still works but it redirects me to the admin change form displaying "Please correct the errors below." and marking the … -
How to fix compatibility between libraries
Im trying to perform some actions with jwt token. Im working with Django-rest-jwt, wich requires PyJWT and jwt. The problem is - I made fork to PyJWT cause I need some code working another way, and when I try to use Django-rest-jwt, it says that he can't find jwt, also pip3 gives me this, when I install my fork. pic , btw fork works correctly. So, how can I make Django-rest-jwt use my fork instead of PyJWT? I tried to fork it and change requirements, but didn't find PyJWT at all -
Gunicorn "error: unrecognized arguments: --log-file--"
I am trying to deploy my django application to heroku, but every single time I try, I see this error in my logs: gunicorn: error: unrecognized arguments: --log-file-- But my Procfile looks like this (I haven't forgotten to save it or anything) web: gunicorn post_project.wsgi --log-file - I can't really put my eye on anything that may be a cause of that error except these few lines at Heroku This app is using free dynos web gunicorn post_project.wsgi --log-file-- -
Problem with sending a POST request with axios in reactjs
Hi every body I am using reactjs and redux for frontend and I want to create new articles so I created CreateArticle.js as below import { useDispatch, useSelector } from 'react-redux' import { unwrapResult } from '@reduxjs/toolkit' import { addNewArticle } from './managementSlice' import { selectAccessToken, selectUser } from '../authentications/authenticationsSlice' import './CreateArticle.scss'; import { selectAllSubjects, fetchSubjects } from '../subjects/subjectsSlice'; import { selectAllTags, fetchTags } from '../tags/tagsSlice'; export const CreateArticle = () => { const [title, setTitle] = useState('') const [body, setBody] = useState('') const [slug, setSlug] = useState('') const [subjectId, setSubjectId] = useState(0) const [tags, setTags] = useState([]) const [addRequestStatus, setAddRequestStatus] = useState('idle') const user = useSelector(selectUser); const subjects = useSelector(selectAllSubjects) const allTags = useSelector(selectAllTags) const subjectStatus = useSelector((state) => state.subjects.status) const tagStatus = useSelector( (state) => state.tags.status) const dispatch = useDispatch() // const onSubjectChanged = (e) => setSubjectId(parseInt(e.target.value)) const onSubjectChanged = (e) => setSubjectId(e.target.value) const onTitleChanged = (e) => { setTitle(e.target.value) setSlug(e.target.value.toLowerCase())} const onBodyChanged = (e) => { setBody(e.target.value) console.log(e.target.value); } const onTagsChanged = (e) => { const selectedOptions = [...e.target.selectedOptions].map(o => parseInt(o.value)) setTags(selectedOptions) } const onSaveArticleClicked = async () => { let article = { Subject:subjectId, Title: title, Body:body, Tags:tags, Slug:slug } if (user){ try { setAddRequestStatus('pending') console.log('addRequestStatus:', … -
How to import all the classes in a module as a list?
In django, to display models on admin page, we have to first register all the models in admin.py. If there are so many models to register, we have to write admin.site.register(model_name) so many times. Its kind of a boring task. So I was wondering if there is any way in python to import all the classes in module as list. for instance, admin.py, from django.contrib import admin from .models import * as list_name #like this is there any way we can get all things inside * in list ? for i in list_name: admin.site.register(i) #so that this way I have to write only one line of code to register all classes. Is there any way to save writing lot of lines here ? -
django - how to save form fields from multiple lines of input?
I want to add mutliple values from user input to a form field into one variable. These values are ManyToMany field in my model. User selects them from a list and adds into that field. I send {{form.product}} to template, I can gather one value from here but i want to add more lines (which i can with JS) and save those lines into same (forms.product) field. My model contains product,product_group. I want to add products with product group as well, which will be different in every line. E.g.: prod1,1 / prod1,2 / prod,3 etc. Second value will be that line index that i want to add. My template html looks like this: {{ form.product}} <ul>Products:</ul> <div id="productcon"> </div> <div id="add" onclick="add()">add interest</div> And my javascript is like this: function add(){ let index = $('#productcon')[0].childElementCount +1; $('#productcon').append(`<input type="text" name="product${index}" value="??"/> `); } This add new lines but I can't save them except my first value. This JS part confused me. Or i focused on JS and missing something else. I hope I could explain my problem. Thank you. -
get highest number of order on a single date
My model is like class Order(models.Model): user=models.ForeginKey(User) completion_date_time = models.DateTimeField(blank=True, null=True) I want to get date on which max number of order placed with count of order -
Return multiple user in Django
My tests are failing saying get() returned more than one permissions -- it returned 2! However I want to return more than one permission, but I could not get the list. I'm using ajax to display those list on modal. My problem is I want to display all usertype name base on idd below. If any expert could help please share some solution thanks in advance. returned more than one permissions -- it returned 2! views.py def ajax(request): idd = request.GET.get('id') app_permission_tbl_usid = permissions.objects.get(user_id=idd) app_permission_tbl_permid = app_permission_tbl_usid.permission_id datas = usertypes.objects.get(id=app_permission_tbl_permid) list_of_permission = datas.usertype return JsonResponse({"result": list_of_permission}) -
Render a different form inside view Django
I'd like to use the same page, but render a different form according to which button I press. Is there a way of doing it? Here it goes my HTML and VIEW code _adm.html <div class="btn-group btn-group-lg" role="group"> <div class="col-md-12 text-center"> <form action="" method="POST"> <a role="button" type="submit" href="{% url 'administrativo' user.username %}" name="senha" class="btn btn-green text-white">Alterar Senha</a> <a role="button" type="submit" href="{% url 'administrativo' user.username %}" name="nome" class="btn btn-green text-white">Alterar Nome</a> </form> </div> adm.html {% extends 'base.html' %} {% load static %} {% block content %} {% include 'partials/_header.html' %} {% include 'partials/_adm.html' %} <div class="container"> {{ form }} </div> {% include 'partials/_footer.html' %} {% endblock %} view.py def alterar_senha(request, user_username): usuario = User.objects.get(username=user_username) form = AlterarSenha(instance=usuario) context = { 'form': form } return render(request, 'usuarios/administrativo.html', context) def editar_usuario(request, user_username): usuario = User.objects.get(username=user_username) form = EditarUsuario(instance=usuario) context = { 'form': form } return render(request, 'usuarios/administrativo.html', context) def administrativo(request, user_username): if request.method == 'POST' and 'senha' in request.POST: return redirect('alterar_senha', user_username) elif request.method == 'POST' and 'nome' in request.POST: return redirect('editar_usuario', user_username) return render(request, 'usuarios/administrativo.html') I have no idea if it is possible to do such a thing. Otherwise, I'll have to render 3 different pages.