Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: CreateView object with dynamic form fields not saved
I set up a working CreateView. However, when I made one of my modelform fields ('erlaubte_pruefer') dynamic, the object is not saved anymore. I've tried many solutions suggested in other posts, e.g. - get user variable in get_form_kwargs(), - limit the field choices in get_form() instead of forms.py - don't use CreateView but I just can't make it work. I don't get an error or exception, the form is only rendered again. I would highly appreciate your input. Thank you! forms.py class Checklisten_Reinigung_Form(forms.ModelForm): class Meta: model = Checklisten_Reinigung fields = ['okay', 'raum_verbindung', 'ausfuehrer', 'erlaubte_pruefer' ] # user should only choose from those objects that were created by himself def __init__(self, user, *args, **kwargs): super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs) self.fields['erlaubte_pruefer'].queryset = Pruefer.objects.filter(firmenzugehoerigkeit=user) views.py class Checklisten_Reinigung_Create_View(LoginRequiredMixin, CreateView): template_name = 'checklisten/checklisten_form.html' def get_context_data(self, **kwargs): context = super(Checklisten_Reinigung_Create_View, self).get_context_data(**kwargs) context['mymodel'] = Checklisten_Reinigung() return context # if I leave out get_form() the object is successfully saved # but the user's choice is not limited def get_form(self, form_class=None): form = Checklisten_Reinigung_Form(user=self.request.user) return form def form_valid(self, form): self.object = form.save(commit=False) try: self.object.pruefende_firma = self.request.user self.object.bezeichnung = self.object.bezeichnung self.object.ausfuehrer = form.cleaned_data['ausfuehrer'] self.object.erlaubte_pruefer = form.cleaned_data['erlaubte_pruefer'] self.object.okay = form.cleaned_data['okay'] self.object.raum_verbindung= form.cleaned_data['raum_verbindung'] self.object.save() return HttpResponseRedirect(self.get_success_url()) except: messages.error(self.request, 'Es ist ein Fehler aufgetreten.') return … -
Annotating a DecimalField with F() division - how to round to 2 places?
While annotating a DecimalField() with F() division how do you round to two decimal places? class Product(models.Model): price = models.DecimalField(max_digits=9, decimal_places=2) surcharge = Decimal('1') - (Decimal('2.5') / Decimal('100')) products = Product.objects.all().annotate( surcharge_price=F('price') / surcharge, ) If price = Decimal('9.56') then surcharge_price = Decimal('9.8051282051282051') but the desired value is Decimal('9.81') Tried below but get AttributeError: 'CombinedExpression' object has no attribute 'quantize' surcharge_price=(F('price') / surcharge).quantize(Decimal('.01'), rounding=ROUND_HALF_UP) -
Django: I want to sort posts by last comment / update
I programmed a simple blog after a tutorial and it works so far. But now I would like to sort the post list by last activity in a post. As soon as a new post is published or a new comment is approved, the post should be on the top of the list. (the way it works in a forum..) Here is what I have so far... (It seems that sorting the list by "updated_date" works, but attaching the right datetime to it when approving a comment fails.) Thanks for your help in advance models.py class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.DO_NOTHING,) title = models.CharField(max_length=200) text = RichTextUploadingField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) updated_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post', related_name='comments', on_delete=models.DO_NOTHING,) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True Post.updated_date = timezone.now() self.save() def __str__(self): return self.text def approved_comments(self): return self.comments.filter(approved_comment=True) views.py def post_list(request): posts = post.objects.filter(updated_date__lte=timezone.now()).order_by('-updated_date') return render(request, 'blog/post_list.html', {'posts': posts}) blog.views.post_detail @login_required def post_publish(request, pk): post = get_object_or_404(Post, pk=pk) post.publish() return redirect('post_detail', pk=pk) def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form … -
django crispy forms overriding layout objects templates ignored
I applied this thus I have self.helper.layout = Layout( Field( 'title', template="mytemplate.html" ) , then when I debug in C:\myapp\lib\crispy_forms\layout.py I have, that I see I successfully pass the parameter. However when I step out debugged code to my form RoomForm , I see that field is reset back to default value %s/field.html As result my template is not rendered (C:\myapp\lib\crispy_forms\templatetags\crispy_forms_filters.py): if I modify helper.field_name on debug to mytemplate.html, I see it is rendered with success. Question is what could be reason that my template is ignored? Important note, my form extends: class RoomForm(ModelForm) where ModelForm is as here -
could you please, explain why when i am render django template on ajax success it isn't appeared on the browser
My Html page isn't rendered on ajax success when I use console.log() in the js file, the HTML page is printed out in the browser console but not in the browser itself. kindly check my following code: views.py: def Filter_by_Products(request): if request.is_ajax(): if request.method == 'GET': print("filter by function!") filter_brand = request.GET.get('filter_brand') products_qs, qs_color, qs_size = product.objects.Filter_brand(filter_brand.rstrip(',')) context={ "object_list": products_qs, 'colors': qs_color, 'sizes':qs_size } # print(products_qs) # print(qs_color) # print(qs_size) return render(request,"product/products.html",context) ajax.js: $.ajax({ url:'/cart/api/filterby/', method:'get', data: { 'filter_brand':str, }, success: function (data) { console.log(data) // location.reload() }, error: function (error) { console.log(error) } }) After googling on my question, I found that my problem is that I'm trying to mix the server side with the client side and the solution is to send my HTML template using HttpResponse not render function and then by using javascript, I select the HTML page and change content with the new html. Actually, I didn't understand clearly the problem and why mixing server with client caused that problem and why my code wasn't working from the first time using render, so could you please explain more in details or refer links to me to understand. also, I'm familiar with Django celery and Redis, … -
Include google analytics tag to django admin without changing the template for every page
Is there a way to include the google-analytics javascript snippet easily into the django admin page ? (django 1.10) I would like to do that without creating a custom template for each of the admin page, just insert the script in the all admin. Thank you, -
Looking for example of simple, interactive 2D game developped in Python
I developped the backend of a puzzle game in python and I am looking for ways to put it on a website. I want anyone to be able to play directly in their browser from my site's url. No download or prior installation required. Does anyone have an example of a simple game developped in python that can be played in the browser? I've been to pygame: every 'hope page' link to a download or to a source code. Been to Pyjs: all examples are very basic features. Panda3D seems to be a powerful engine for Steam games. Django seems to be what I'm looking for, but I haven't found example of anything looking near like I want to do: I want to draw the board myself with simple shapes like circles, ellipses, and imported images. I want to change some colors and make text appear/disappear when users hover their mouse over some areas. I want users to trigger actions by clicking on the buttons, and watch the effects. If anything remotely similar been done in Python I haven't found it yet. -
django, How to check some date is in specific term
I have some date data: start_date = "2018-05-22" end_date = "2018-10-11" And using this, How to check some date data is in between those two date. For example: start_date = "2018-05-22" end_date = "2018-10-11" some_true_date = "2018-06-21" # It is in start_date and end_date some_false_date = "2017-03-03" # It is not in start_date and end_date # assuming that I have method 'check_date' that returns boolean type result. if check_date(some_true_date): print("True") # >>> True if check_date(start_date): print("True") # >>> True if check_date(end_date): print("True") # >>> True if not check_date(some_false_date): print("False") # >>> False How can I do this? -
ModuleNotFoundError: No module named , can not find what causes the error in a Django application
I face the following error when I run the python manage.py makemigrations command Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rock_n_roll' I can't seem to find where the error is coming from, any help ? -
How to show the query set result using cursor in the view
I have this function that run a query and pass the result to be showed in the view. def index(request): data = dict() cursor = connection.cursor() cursor.execute('''SELECT user.email, item.id, count(item.author_id) FROM item INNER JOIN user on item.user_id = user.id GROUP BY item.author_id ''') data['item'] = cursor.fetchall(); return render(request, 'ideax/panel.html', data) Example of the queryset result: [('teste@gmail.com', 1, 4), ('admin@gmail.com', 2, 5)] How can I show the result of this query in my panel.html? I tried this one, but it doesn't works: {% for d in item %} {{d.email}} {% endfor %} -
Simulate render form of django rest framework in angular 5
I use django rest as backend, and angular 5 as frontend. my code in backend is like this: for example, I have a model: class Brand(models.Model): name = models.CharField(max_length=20, unique=True) abbreviation = models.CharField(max_length=10, unique=True) serializer class : class BrandSerializer(ModelSerializer): class Meta: model = Brand fields = ('name', 'abbreviation',) view class : class BrandAPIView(CreateAPIView): serializer_class = BrandSerializer queryset = Brand.objects.all() when I see my api in browser for first time, I can see a form for create brand. I do not sent anything for this, and I know generics library handles this action. Now I want to simulate this action for my frontend in angular, I have some idea, but I do not know which one is good. If you have any idea, help me please. -
How to load existing data in a formset
I have a model, DataRow, to which I want to add a field (send_row) and then display all instances of DataRow in a table. I figure formsets are the right approach but cannot get it working. This is the DataRow model: class DataRow(models.Model): dt = models.DateField( default = timezone.now ) school = models.ForeignKey( School, on_delete = models.CASCADE ) subject = models.ForeignKey( Subject, on_delete = models.CASCADE ) contribution = models.CharField( max_length = 255 ) student = models.ForeignKey( Student, on_delete = models.CASCADE ) I've written this formset: class BaseDataRowFormset(forms.BaseFormSet): def add_fields(self, form, index): super().add_fields(form, index) form.fields['send_row'] = forms.BooleanField( widget = forms.CheckboxInput() ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = DataRow.objects.all() DataRowFormset = forms.modelformset_factory( DataRow, formset = BaseDataRowFormset, fields = '__all__' ) I thought I would be initialising the queryset to include all existing records using the self.queryset code within __init__. I'm wrong. And I have this view: class ReportView (LoginRequiredMixin, ListView): model = DataRow form_class = DataRowForm template_name = 'core/datarow_list.html' def get_context_data(self, *args, **kwargs): ctx = super().get_context_data(*args, **kwargs) if self.request.POST: ctx['formset'] = DataRowFormset(self.request.POST) else: ctx['formset'] = DataRowFormset() return ctx How do I get existing rows to be available? -
django How to subtract date from django datetime.date class
I have a model: class DateModel(models.Model): date = models.DateField(default=None, null=True, blank=True) and I made some object and got it: date_obj = GroupDate.objects.all().last() print(date_obj.date) print(type(date_obj.date)) so that It returned this lines: 2018-11-21 <class 'datetime.date'> Here my question, How to get 22 days before date from date 2018-11-21? Like this: date_obj = GroupDate.objects.all().last() some_int = 22 result_date = get_date_from_date(date_obj.date, some_int) # It is just example that I made. print(result_date) # >>>2018-10-30 How can I do this? -
nginx auth_request using original uri
This may be related to this question. I try to provide static files using nginx. However, only registered users with the appropriate rights should be able to download these files. Within the django application I can already authorize users, but since the downloads are not delivered by django, but by nginx, I had some problems with it. Currently I have two locations within my nginx config. location / { uwsgi_pass django; include /usr/share/nginx/uwsgi_params; } location ~ /projects/(.*)/downloads/(.+[^/])$ { auth_request /api/auth; root /usr/share/nginx/downloads; } This configuration works, but I am unable to check if the registered user is allowed to access this download area. It would be enough if I could adjust the second block to a syntax like this. location ~ /projects/(.*)/downloads/(.+[^/])$ { auth_request /projects/$1/downloads/; root /usr/share/nginx/downloads; } But with this configuration not the uri is called, but the given string /projects/my_project/downloads/my_file.txt Is there a simple way to pass the original uri to an auth_request? Thank you in advance -
Celery missing 1 required positional argument on python task
I have a celery beat running under my workspace once per minute. My task is very simple: @task() def capturar_placas(): print('Iniciando Captura de Placas do OpenALPR CLOUD') But each time celery try to execute my task i got the following error: File "/home/ronaldo.lanhellas/workspace/github/safepark/pythonvenv/lib64/python3.6/site-packages/kombu/transport/django/models.py", line 29, in Message queue = models.ForeignKey(Queue, related_name='messages') celery.beat.SchedulingError: Couldn't apply scheduled task Capturar Placas: __init__() missing 1 required positional argument: 'on_delete' Looking at "models.py" from kombu lib i noted that don't exists on_delete argument in FK, but Django 2.x require it. How can i solve that ? Update library maybe ? -
Django intcomma in two places
Using Django humanize I got intcomma which puts the comma after every 3 digits like 4500000 becomes 4,500,000 but I want only the first 3 digits to be separated by the comma then remaining digits separated by a comma after every 2 digits, not 3 digits, like 45,00,000 How can I do this? -
Django modelform override save method
I have a sample model class MyModel(models.Model): user_Account = models.OneToOneField(User, on_delete=models.CASCADE) remark = models.CharField(max_length=64, blank=True, null=True) is_completed_race = models.BooleanField(default=False) is_male = models.BooleanField(default=False) is_winner = models.BooleanField(default=False) is_jamaican = models.BooleanField(default=False) Assume that everything is True in the db for a particular user. **ModelsForm** class MyForm(forms.ModelForm): class Meta: fields = ["remark", "is_male", "is_completed_race", "is_male", "is_winner", "is_jamaican"] template.html <form action="" method="POST"> <csrf_token> <p>{{ form.non_field_errors }}</p> <label>Remark : {{ form.remark }}</label> <label>{{form.is_completed_race}} Is_completed Race</label> <label>{{ form.is_male }} is_Male</label> <label>{{ form.is_winner }} is_winner</label> <label>{{ form.is_jamaican }} is_jamaican</label> <button type="submit" class="btn btn-primary btn-block">Submit</button> </form> By using this modelform i want to mark the mistaken part for that user and which need to be reflect back to the user.By default the checkboxes are unchecked.The problem is i need to mark the correct one to make unaffected( True ) and unmark the mistaken one( False ). what i want is the reverse of the process !. what i need is to mark only the mistaken one to make it false in its db. Any help will be appreciated -
get_object_or_404 does not work on User model
When I use: post = get_object_or_404(Employee, user_id=User.objects.latest('id')) It returns the latest employee, as Employee.user_id is foreign key to User.id When I use: post = get_object_or_404(User, id=User.objects.latest('id')) I would expect to get the latest user, yet now I get the following error: int() argument must be a string, a bytes-like object or a number, not 'User' What am I doing wrong here? -
Django inline formset multiple models
TL;DR: I need a some kind of formset for formsets. I have two different models related to one buisness-entity, and I need to make a form to edit both models like a one form. And I need to create a lot of such forms on the one page like djngo inline formset does. Now I have the following thing: class Parent(models.Model): name = models.Charfield() class FirstChild(models.Model): name = models.Charfield() e_id = models.IntegerField() parent = models.ForeignKey(Parent) class FirstChildForm(django.forms.ModelForm): class Meta: model = Child fields = ('name', 'e_id', 'parent') widgets = {'parent': forms.TextInput} And I render a lot of them usiing inline formsets: formset_class = inlineformset_factory(Parent, FirstChild, form=FirstChildForm, extra=1) But now I have to add second child model and a form for it, and still render it like an one inline form, bit make it form actually edit two models. Like this: class SecondChild(models.Model): name = models.Charfield() e_id = models.IntegerField() parent = models.ForeignKey(Parent) class SecondChildForm(django.forms.ModelForm): class Meta: model = Child fields = ('name', 'e_id', 'parent') widgets = {'parent': forms.TextInput} formset_class = inlineformset_factory(models=[Parent, FirstChild], forms=[FirstChildForm, SecondChildForm], extra=1) As far as I understand, Django formsets cannot work with multiple models right now. So which way should I choose to implement this behaviour and do … -
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)