Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use django widget tweaks and combine template class string and widget attr attributes string name
I am trying to customise a django form for use with bootstrap 4, custom html layout & per field class or id names on the FormModel defintion I have the following html {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} And the following form defintion: class DocumentForm(forms.ModelForm): field1 = PartLookupField(required=True, widget=forms.TextInput(attrs={'class': 'field1-choice-ajax'})) field2 = forms.CharField(required=True, widget=forms.TextInput(attrs={'id': 'field2-field'})) form_lines = forms.CharField(widget=forms.HiddenInput()) class Meta: model = Document fields = ("field1", "field2", "form_lines") So essentially, I need to get the per field definition of id or class, from the widget on the model, and combine that … -
(550, b'Incorrect sender header (LOCAL)')
I try to build contact email form in django using send_mail() function. It works fine in test environment but not in production. On submitting the form I get Server Error (500) in the browser. I receive django error reporting email with the below: Exception Type: SMTPDataError Exception Value: (550, b'Incorrect sender header (LOCAL)') In settings I am using same email address for error reporting and for email form so it works in one case but not in the other. What does the above error mean? Any idea how to fix it? -
django user login error using User authentication()
I have a basic login, sign up html page in my Django project: The login page redirects to the user_login function in views.py as follows: <form action="{% url 'user_login' %}" method="POST">. //rest of the code In urls.py the request is getting forwaded correctly: .......#beginnning code path('user_login', views.user_login, name='user_login'), path('portfolio', views.portfolio, name='portfolio'), ...... In views.py this is my user_login code to authenticate the user and redirect the user to a 'portfolio.html' page if the user credentials are correct. I have imported User, Login class as follows: from django.http import HttpResponseRedirect from django.shortcuts import render from .models import Profile from django.contrib.auth.models import User from django.contrib.auth import authenticate, login # Create your views here. def index(request): return render(request, 'mysite/index.html') def user_login(request): if request.method == 'POST': name_r = request.POST.get('name') password_r = request.POST.get('password') user = authenticate(username=name_r, password=password_r) if user: login(request, user) #below line might be incorrect return HttpResponseRedirect('mysite/portfolio.html') else: return render(request, 'mysite/login.html') #rest of the code for signup which is working perfectly. Whenever i click on Login page, the login page never loads in the first place, let alone checking whether authentication is taking place or not. The error occurring is as follows: I am not sure exactly where the error is occuring and what … -
Django authentication with multiple databases
I want to create an App for Customers where every customer has its own DB. So as Login information they need to enter three different fields: customernumber, username, password. The username and password should do the normal authentication stuff and the customernumber is there to go to the right database user table for authentication i can go to other databases through the using() function. class CustomAuthBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): user = CustomUser.objects.using(request.POST['kundennr']).get(username=username) if user.check_password(password) and self.user_can_authenticate(user) : try: user = CustomUser.objects.using(request.POST['kundennr']).get(username=username) return user except User.DoesNotExist: return None def get_user(self, user_id): try: return CustomUser.objects.get(pk=user_id) except User.DoesNotExist: return None The authentication function works fine that way the problem i have is the get_user function i guess because the get_user function has no request where i can define which database it should call on. because everytime i call {% if user.is_authenticated %} it goes to the default database and says user is Anonymous. I dont know the right way to solve this problem is my solution just wrong? -
regular expression not recognized by django
I'm new to Django and I'm trying to create a simple path to later link it to the database, for now: I created this URL path in my music app: urlpatterns = [ # /music/ path('', views.index, name='index'), # /music/*****/ path(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'), ] And I added this to the views.py: def detail(request, album_id): return HttpResponse("<h2>Details for Album id: " + str(album_id) + "</h2>") But it doesn't work, every time I ask for this url: http://localhost:8000/music/2 I got "Page not found" Please help. Thanks. -
Does select_related on an already queryed field perform an SQL query?
Let's assume that Car has multiple wheels and a wheel has one color. Does the third line performs an SQL query ? cars = Car.objects.prefetch_related('wheel_set__color') for car in cars: print(car.wheel_set.color) -
Dynamic value change in for loop in django
Hi how to pass dynamic value in for loop. in value={{ product.size.0.size }} instead of 0 i want to pass index value {% for no_of in product.size %} {{ forloop.counter }} <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label or="">Product Size</label> <input class="form-control" placeholder="Alpha-Numeric characters" required="required" type="text" name="product_size" id="product_size" value="{{ product.size.0.size }}"> <div class="help-block form-text with-errors form-control-feedback"></div> </div> </div> </div> -
missing 1 required positional argument: 'request' django restframework
I was using routers for creating urls now i want to make urls for my api, but problem is, i am getting error createuser() missing 1 required positional argument: 'request'missing 1 required positional argument: 'request',iam getting same error for all my methods inside UserAuthAPIView class, i have already read solutions on stackoverflow but they are not working i my case. I have many methods in UserAuthAPIView class and i want to create urls for all of those. for eg 127.0.0.1:8000/api 127.0.0.1:8000/api/createuser 127.0.0.1:8000/api/login 127.0.0.1:8000/api/<pk>/viewuser urls.py from django.conf.urls import url from UserAPI.api import views from UserAPI.api.views import UserAuthAPIView urlpatterns = [ url(r'^$', UserAuthAPIView.as_view({'get': 'list'}), name='user-list'), url(r'createuser/$', views.UserAuthAPIView.createuser, name='user-create'), #url(r'userlogin/$', views.UserAuthAPIView.userlogin, name='user-login'), ] views.py class UserAuthAPIView(ModelViewSet): queryset = UserModel.objects.all() serializer_class = ListViewSerializer def get_object(self, queryset=None): return self.request.user @action(methods=['post'], detail=False, permission_classes=[AllowAny], serializer_class=UserSerializer) def createuser(self, request, *args, **kwargs): data = request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({ "status" : "user created successfully"}, status=HTTP_201_CREATED) -
How break cycle for with if else statement in django template
I read if else statement in Django docs but i don't understand my case. I have photos list, i want render image if is COVER else i want render static image. This my code {% for x in listing.photos.all %} {% if x.photo_tipo == 'COVER' %} <img src="{{ x.get_thumb }}" alt=""> {% else %} <img src="{% static 'images/about/1.jpg' %}" alt=""> {% endif %} {% endfor %} Result is: an image if x.photo == 'COVER' and a static image for every other photo in the list. I would like to get only one result if the declaration is true or only one static image if it is false -
Aggregate 2 fields in django to count difference between hours
I try to calcul the difference between 2 DateTimeField to know the total work (only hours) per week and I want the same function for days only. Following another Stackoverflow question, I find a aggregation like that: total_hours_per_week = (Timesheet.objects.filter( owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1] ) .annotate( total_hours_per_week=Func(F('end'), F('start'), operator='+', function='age') )) Currently, i don't have the function for days (if you can help me too for her), but this previous agregation return me this error: "no such function: age" you can read bellow my models: class Timesheet(models.Model): owner = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 64, verbose_name = _("Title")) start = models.DateTimeField(verbose_name = _("Start time")) end = models.DateTimeField(verbose_name = _("End time")) allDay = models.BooleanField(blank = True, default = False, verbose_name = _("All day"), help_text = _("If it's a full day work, just click 'Now' for start/end")) week = models.IntegerField(verbose_name = "working week") def __str__(self): return "{}".format(self.title) def save(self, *args, **kwargs): if not self.pk: self.week = datetime.datetime.now().isocalendar()[1] if self.allDay: self.start = datetime.datetime(year = datetime.datetime.today().year, month = datetime.datetime.today().month, day = datetime.datetime.today().day, hour=8, minute=00) self.end = datetime.datetime(year = datetime.datetime.today().year, month = datetime.datetime.today().month, day = datetime.datetime.today().day, hour=17, minute=30) super(Timesheet, self).save(*args, **kwargs) I hope you can help me to solve my … -
in python 3.X I have error with django-admin
I have error with django-admin on IOS by the following I did this steps: 1. conda create --name DjangoProject django 2. y 3. conda info --envs 4. source activate _DjangoProject_ 5. conda install django 6. python 7. 'django-admin.py' startproject `first_project` the last line (7) gave me a message says: (DjangoProject) MacBook-Air:~ ali$ 'django-admin' startproject first_project CommandError: '/Users/al/first_project' already exists My path is: /Users/al/anaconda3/envs/DjangoProject How can I put the project (first_project) on a correct path -
Django div reload - ajax GET after POST does not get latest database model instances
In a chat-like app, I'm using ajax calls to POST a new message and update the messages displayed on the page without reloading the entire page. My ajax call for posting works - a new message instance is created in the database. However, afterwards when I make an ajax call to GET all messages, the new message is missing from the resulting query set. If I refresh the page fully, I can see all the messages, but that's not what I'm after. HTML messages template: {% for message in messages %} <p> {{ message.content }} </p> {% endfor %} HTML chat template: <div id="chat"> {% include "messages.html" %} </div> <form id="post-message-form", method="post" enctype="multipart/form-data"> [my form goes here] </form> JavaScript: $('#post-message-form').on('submit', function(event){ event.preventDefault(); $form = $(this); var data = new FormData($form.get(0)); $.ajax({ url: '/post/a/new/message/', type: 'POST', data: data, success: refresh_div, cache: false, contentType: false, processData: false }) return false; } function refresh_chat(){ $.ajax({ url: '/get/all/messages/, type: 'GET', success: function(json) { $('#chat').html(json['data']); } }) return false; } Views: import json from django.template import loader from .forms import MessageForm # /post/a/new/message/ def post_message(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): message = form.save() return HttpResponse( json.dumps({'status': 1, 'message': 'Message posted!'}), content_type='application/json' … -
Can we use angular.js without node?
We are working with Django as a server framework as used JavaScript for client-side scripting? Now we are migrating to Angular4, do we need to run a node.js server with the existing running Django server? -
Using database for forms django
I have an area where teachers can put homeworks for students. Students can see these homeworks and when they click "send homework" button. they can fill a form so Teachers can see the homeworks from admin panel. I have class to post homework. I have 5 fields in class to post homework. Fields = ["student number","Deadline","Lecture","Files"] when students posting their homeworks, I want only use 2 ["student number","files"] fields for the form and I want other fields ["deadline","Lecture"] to be filled automatically from database. What is the best way do it? -
How can I divide a decimalField with a float?
def save(self, *args, **kwargs): self.netto = self.reisepreis / 1.19 self.mwst = self.reisepreis - self.netto super(Assignment, self).save(*args, **kwargs) -
Where is my tasks? (Docker, Celery, Redis)
I have three docker container with Celery, Redis and Django. Celery brocker is redis. When I initialize a task it should be put in redis but when I go to redis-cli and do KEYS * there is nothing. How and Where can I check my queue? -
How to add "+" button in group model (auth_group) in django admin user to add group directly from user add page
Check the image, i tried checking the group admin in django auth.But didnt find anyway. Image-link: https://i.stack.imgur.com/xocVn.png -
Celery shared_task parameters wrong parsing
i'm using celery 4.2.0 with Django to schedule new tasks in rabbitmq and it randomly fails when it comes to parse arguments. My code looks like that: for param in serializer.validated_data['parameters']: run_task.delay(param_name=param) Where parameters is list of int and it is ensured with serializer validation. @shared_task def run_task(param_name: int) -> None: obj= Obj.objects.filter(param=param_name) ... Under UTs when i invoke this run_task with CELERY_TASK_ALWAYS_EAGER=True everything works. On real enviroment this tasks sometimes runs just OK and sometimes it fails with server error: File "/usr/lib/python3.6/site-packages/rest_framework/decorators.py", line 53, in handler return func(*args, **kwargs) File "/opt/app/compliance/jobs/views.py", line 30, in create_task run_task.delay(param_name=param) File "/usr/lib/python3.6/site-packages/celery/app/task.py", line 408, in delay return self.apply_async(args, kwargs) File "/usr/lib/python3.6/site-packages/celery/app/task.py", line 535, in apply_async **options File "/usr/lib/python3.6/site-packages/celery/app/base.py", line 741, in send_task with self.producer_or_acquire(producer) as P: File "/usr/lib/python3.6/site-packages/celery/app/base.py", line 876, in producer_or_acquire producer, self.producer_pool.acquire, block=True, File "/usr/lib/python3.6/site-packages/celery/app/base.py", line 1246, in producer_pool return self.amqp.producer_pool File "/usr/lib/python3.6/site-packages/celery/app/amqp.py", line 612, in producer_pool self.app.connection_for_write()] File "/usr/lib/python3.6/site-packages/kombu/utils/collections.py", line 34, in __getitem__ h = eqhash(key) File "/usr/lib/python3.6/site-packages/kombu/utils/collections.py", line 25, in eqhash return o.__eqhash__() File "/usr/lib/python3.6/site-packages/kombu/connection.py", line 629, in __eqhash__ repr(self.transport_options)) File "/usr/lib/python3.6/site-packages/kombu/utils/collections.py", line 16, in __init__ self.hashvalue = hash(seq) TypeError: unhashable type: 'set' I understand error itself but how come it appears here when I pass only one simple … -
What Query should I make to prefetch my data from first model to get filled when my form for second model opens
models.py class Appname(models.Model): name=models.CharField(max_length=150,blank=False,null=False,help_text='Add your new App') def __str__(self): return self.name def get_absolute_url(self): return reverse("dashapp:view") class Adspace(models.Model): name=models.ForeignKey(Appname,related_name='adspaces', null=True, default=None,on_delete=models.CASCADE) ad_space=models.CharField(max_length=150,blank=False,null=False) def __str__(self): return self.ad_space def get_absolute_url(self): return reverse("dashapp:view") Query to make I create a form using CreateView for both the models. For First model i save the appname and then I create a listview of app names Using ListView and display them. When i click on one of the app from the displayed list it takes me to the next form which is for the next model Adspace . Now I want as my form opens for second model the name section gets autofill with the name of the app with which i clicked to reach on that form.What Query should i make to make it possible.Please Explain it with your answer. -
displaying the field data to django template if a column already exist or dash if the field does not exist in the database
am using an users api to display all user in a django template.what i want to implement is to first check if those users already exist in the local and if they exist display their roles on the other hand if the user Does not exist you save the user and select what role they fall and display to front-end -
Wagtail - passing queryset to inline
I am facing a problem from days, but, no matter how much I keep searching, I could not find any solution here or anywhere in the web. So here it is: I am developing a website for some sort of institution which offers teaching courses. I am using WAGTAIL and I am structuring the classes this way: class Course(Page): ... content_panels = Page.content_panels class Exam(Page): #fields content_panels = Page.content_panels + [ #fields InlinePanel('preparatory_exam', heading='Preparatory Exams'), ] class PreparatoryExam(Orderable): page = ParentalKey('Exam', on_delete=models.CASCADE, related_name = 'preparatory_exams', ) name = models.ForeignKey( Exam, on_delete=models.CASCADE, blank=True, null=True, related_name = 'preparatory_exam', ) I also structured the ADMIN section PAGES this way: \COURSE_1_PAGE \-----------\EXAM_1 \-----------\EXAM_2 \------------------\Prep exam 1 \------------------\Prep exam 2 \-----------\EXAM_3 ... \COURSE_2_PAGE \-----------\EXAM_1 \-----------\EXAM_2 \-----------\EXAM_3 .... So, the problem is: is there any way to pass a custom queryset to the inline dropdown box when choosing the preparatory exams for a certain one? What I want is to restrict the set to the exams present in the same Course. I could do that with a limit_choices_to added to the foreignkey field, but AFAIK, it would be a "static" filter, because it would be related to the model and not to its istances, so it … -
descriptor 'strftime' requires a 'datetime.date' object but received a 'bool'
I have this problem with passing data to excel in python 2.7. I want to allow the specified special characters to be passed in an excel cell, but somehow I can't understand the flow. I have the comment and comment_date fields, the concatenation of which will pas in an excel cell. The comment field contains special characters which I want to be allowed. My code is: str= dataset[id]['actions'][0][7] comment = re.sub('^[a-zA-Z0-9!ËëÇç€%@#$&()\\-_`.+,/\"]*$', '', str) comment_date = dataset[loan_id]['actions'][0][9] if comment : comment = comment + " Commented on: " + datetime.datetime.strftime(comment_date,"%B %d, %Y") print comment except IndexError as e: comment = 'no comment added today' cell = '%s%s' % (get_column_letter(col), row) ws.cell(cell).value = comment -
How to handle the for loop in a django formset?
the problem with my formset is that it does not take into account the amount of the modified article in the for loop, and i would also like to know how can i get the total sales perform. thank you views.py : def post(self, request): vente_formset = self.VenteFormSet(self.request.POST) if vente_formset.is_valid(): for temp in vente_formset: vente = temp.save() article = vente.id_article print('article de départ', article.quantite) entre = article.quantite entre -= vente.quantite_v if entre >= 0: article.quantite -= vente.quantite_v article.save() print('article final', article.quantite) else: vente.delete() messages.warning(request, 'Stock insuffisant pour cette opération!') else: messages.warning(request, 'Formulaire invalide!') return render(request, self.template_name, {'form': self.VenteFormSet()}) in terminal pycharm : -->article debut 15 .article fin 10 -->article debut 15 .article fin 8 what I wish to have : -->article debut 15 .article fin 10 -->article debut 10 .article fin 3 -
django from_db __init__() takes 1 positional argument but 26 were given
The reason mybe I upgrade the wagtail. I try to find the cause, but failed. The Error Page address enter image description here -
Django- ValueError [The User couldn't be created because the data didn't validate]
I used extend user model based on this tutorial.When I submit the registration form this error occurs.This errors shows for both time I use is_active() and is_active in my code. How to resolve this error? Error registration form Here is my code: views.py from django.http import HttpResponse from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login from django.views import generic from django.views.generic import View from .forms import UserForm,ProfileForm class UserFormView(View): user_form_class = UserForm profile_form_class= ProfileForm #display a blank form def get(self , request): user_form = self.user_form_class(None) profile_form = self.profile_form_class(None) return render(request, 'website/registration_form.html',{ 'user_form':user_form, 'profile_form':profile_form }) #process form data def post(self, request): user_form = self.user_form_class(request.POST) profile_form = self.profile_form_class(request.POST) user= user_form.save(commit= False) if user_form.is_valid() and profile_form.is_valid(): password= user_form.cleaned_data['password'] username = user_form.cleaned_data['username'] user.set_password(password) user_form.save() profile_form.save() # auto login user = authenticate(username =username, password = password) if user is not None: if user.is_active(): login(request,user) return redirect('website:index') return render(request, 'website/registration_form.html',{ 'user_form':user_form, 'profile_form':profile_form })