Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Flutter with Python Django RESTFUL API
Need Help I have written a flutter widgets for my application for the User Signup in my application and also an API with Django RESTFUL API. How do I connect or integrate the API routes/URL in python Django with the flutter widgets? Please, I need a sample code. I will appreciate any help. Here is my signup flutter widget: import 'package:flutter/material.dart'; class SignUpPage2 extends StatefulWidget { @override SignUpPage2State createState() => SignUpPage2State(); } class SignUpPage2State extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, leading: IconButton( icon: new Icon(Icons.arrow_back, color:Colors.orange.shade700), onPressed: () { Navigator.pop(context); }, ), title: Text("Create acount", style: TextStyle(color:Colors.orange.shade700)), backgroundColor: Colors.black, ), backgroundColor: Colors.black45, body: Center( child: ListView( shrinkWrap: true, padding: EdgeInsets.only(left: 24.0, right: 24.0), children: <Widget>[ new Center( child: new Text("Welcome", style: new TextStyle( color: Colors.orange.shade700, fontFamily: 'Poppins-Bold', fontSize: 30.0, ), textAlign: TextAlign.center, ), ), SizedBox(height: 10.0), new Center( child: new Text("Please, Introduce Yourself", style: new TextStyle( color: Colors.white, fontFamily: 'Poppins', fontSize: 20.0, ), textAlign: TextAlign.center, ), ), SizedBox(height: 20.0), TextField( keyboardType: TextInputType.text, autofocus: false, decoration: InputDecoration( hintText: 'First Name', filled: true, fillColor: Colors.white, contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(32.0), ), ), ), SizedBox(height: 15.0), TextField( keyboardType: TextInputType.text, autofocus: false, … -
Django Rest Framework: SerializerMethodField and get_queryset
In my database I have two tables - users and user_properties I need to filter output using GET parameter phone. But both that tables has column phone and has different values. I need to do request with GET parameter ex. "?phone=123456789" and search User by phone number using not only user_properties.phone, but user.phone too! I googled and found a way partially to do this using get_queryset(filtering) and SerializerMethodField(to modify output): views.py class UserPropertiesViewSet(viewsets.ModelViewSet): queryset = UserProperties.objects.all() serializer_class = serializers.UserPropertiesSerializer def get_queryset(self): queryset = self.queryset # phone number from GET phone = self.request.query_params.get('phone') # Search users matches in user_properties using by phone number if phone: queryset = UserProperties.objects.all() users = queryset.filter(phone__contains=phone) return users else: return queryset serializers.py class UserPropertiesSerializer(serializers.ModelSerializer): all_phones = serializers.SerializerMethodField() class Meta: model = models.UserProperties fields = ['user_id', 'phone', 'fio', 'url', 'all_phones',] # phone numbers from user and user_properties tables def get_all_phones(self, obj): # search phones in <user> table by user_id user_phones = models.User.objects.filter(id__exact=obj.user_id).values_list('phone', flat=True) # add phones from user_properties table result = [obj.phone,] # add phones from user table for phone in user_phones[0].split(','): result.append(''.join(filter(lambda x: x.isdigit(), phone))) # return list with all phones return set(result) And I get all_phones column in my filtered results: { "count": 1, "next": … -
Removing a user from a group does not remove that group's permissions
I am working with Django Groups & Permissions programatically and getting confused. When I add a user to a group, that group's permissions are also added. But when I remove a user from a group, that group's permissions are not also removed. Here is some code: from django.contrib.auth import get_user_model from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType User = get_user_model() user_ct = ContentType.objects.get_for_model(User) group, _ = Group.objects.get_or_create(name="MyGroup") permission, _ = Permission.objects.get_or_create(content_type=user_ct, codename="my_permission", name="My Permission") permission_name = f"{permission.content_type.app_label}.{permission.codename}" group.permissions.add(permission) group.user_set.add(user) assert group in user.groups.all() # THIS WORKS... assert permission_name in user.get_group_permissions() group.user_set.remove(user) assert group not in user.groups.all() # THIS FAILS... assert permission_name not in user.get_roup_permissions() Although the group has been successfully removed, the associated permission still remains. Any ideas on what I'm dong wrong? -
How to convert pdf to html in django?
I know how to convert html to pdf using python packages and in jquery, but i have a task to perform the opposite, i want exact html from a pdf. How to do so? Is there any jquery or python package or method in which i can do so? -
Django : Set url dynamical with <a> element in template
I'm wondering how I can change in Django this link : <a href="http://localhost:8000{% url 'my-token' token=token %}">{{title}}</a> I would like to set http://localhost:8000 dynamical. If I'm working in local, it will be http://localhost:8000 and if I am on my dev server or production server it could be https://subdomaine.domain.com My idea : I could create different settings file : local.py / dev.py / prod.py and define inside each one : #local.py SITE_URL = "http://localhost:8000" #dev.py SITE_URL = "http://dev.domain.com" #prod.py SITE_URL = "http://prod.domain.com" So how I can handle my <a> link to add SITE_URL ? -
Django login redirect_field_name 'next' forces new session
I'm building an e-commerce website, I enable guest users to add products to their carts saving the cart_id in session and when they proceed to checkout, I redirect them to login as follows inside the checkout view if not request.user.is_authenticated: login_url = reverse('accounts:login') check_out_url = reverse('cart:checkout') redirect_url = "{}?next={}".format(login_url, check_out_url) return redirect(redirect_url) # checkout process here It works, however the cart_id is no longer in the session. If I don't use the next parameter and just redirect to login_url the cart_id stays in session. P.S: Same thing happens with login_required_decorator Is there a way to keep the session data intact ? -
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 …