Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Permissões exceto de um grupo
Na query abaixo, obtenho uma lista de todas permissões. routines = ( Permission.objects.select_related("content_type") .values("id", "name", "content_type__app_label", "content_type__model", ) .order_by("content_type__app_label") ) Retorno da query: accounts | accountsroutine | Can add accounts routine accounts | accountsroutine | Can change accounts routine accounts | accountsroutine | Can delete accounts routine accounts | accountsroutine | Can view accounts routine Preciso alterar esta query para excluir dela as permissões já concedidas a um determinado grupo. Como fazer? -
Django template language
"dishList" is a list of "dish" object and "dish" object includes an "id" field. For example: dishList = [dish1, dish2, dish3, ...] dish1.id = 1 "dishCount" is a dictionary type in python, which include a number for each dish. For example: dishCount = { dish1.id: 0, dish2.id: 0, ...} My problem is that in this for loop: {% for d in dishList %} How can I assess the number of dish "d"? I want to use {{ dishCount.(d.id) }} but it is not working. Could not parse the remainder: '(d.id)' from 'dishCount.(d.id)' -
ValueError at /
The view demo.views.index didn't return an HttpResponse object. It returned None instead. @csrf_exempt def index(request): if request.method == 'POST': session_id = request.POST.get('sessionId') service_code = request.POST.get('serviceCode') phone_number = request.POST.get('phoneNumber') text = request.POST.get('text') response = "" if text == "": response = "CON What would you want to check \n" # response .= "1. My Account \n" response += "1. My Phone Number" elif text == "1": response = "END My Phone number is {0}".format(phone_number) return HttpResponse(response) -
Export pdf file
Please help me i just want to export pdf file i am stuck with qs variable i dont know how to type i searched but could not find complete answer. views.py response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="hello.pdf"' buffer = BytesIO() p = canvas.Canvas(buffer) qs = Item.objects.all() # SOLVE IT PLEASE p.drawString(100, 100, qs) p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response -
The current path, about, didn't match any of these
I'm learning Django and just started looking at it installing Django 1.11.17 on my local. But I got the below error while browsing the url. Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: ^admin/ The current path, about, didn't match any of these. I have created a Django project named website and an app named blog. I have made the views file and urls.py as below urls.py file in website package from django.conf.urls import url from blog.views import Aboutus urlpatterns = [ url(r'^about', Aboutus), ] root_urlconf of setting.py file in website ROOT_URLCONF = 'website.urls' views.py of blog from django.http import HttpResponse def Aboutus(request): retrun HttpResponse('Woww') I have spent so much time on this and browsed the answers related to this but I didn't get the solution. I can't find out what I'm missing here so please draw my attention to the gap. -
Django tries to convert an object into an UUID after serialization
I'm creating a web app with Django and Django-rest-framework. Here are my models: class Affilie(TimeStampedModel): TITRE = ( ('Monsieur', 'Monsieur'), ('Madame', 'Madame'), ) TYPE_CONTACT = ( ('Courrier', 'Courrier'), ('Mail', 'Mail'), ) uuid = models.UUIDField( db_index=True, default=uuid_lib.uuid4, editable=False, unique=True, primary_key=True ) titre = models.CharField(max_length=8, choices=TITRE) nom = models.CharField(max_length=25) prenom = models.CharField(max_length=25) id_federation = models.CharField( max_length=50, unique=True, blank=True) adresse = models.ForeignKey( 'utils.Adresse', on_delete=models.SET_NULL, null=True, related_name='affilies' ) mail = models.EmailField(validators=[EmailValidator( message="Veuillez entrer une adresse mail valide")], blank=True) telephone = models.CharField( max_length=14, blank=True, validators=[ RegexValidator( regex=r"^(0\d{8}|04[5-9]\d{7}|(00|\+)\d{2,3}4[5-9]\d{7})$", message="Le numéro de téléphone n'a pas un format valide" )]) type_contact = models.CharField(max_length=8, choices=TYPE_CONTACT) date_naissance = models.CharField(max_length=10, blank=True) inscrit_cours = models.BooleanField(default=False) membre_arista = models.BooleanField(default=False) membre_comite = models.BooleanField(default=False) class Affiliation(models.Model): TYPE_AFFILIATION = Choices( ('BA', 'Belgique apicole + Assurance'), ('BARF', 'Belgique apicole + Assurance + "Abeilles et fleurs"'), ('BASA', 'Belgique apicole + Assurance + "Santé de l\'abeille"'), ('BAAF', 'Belgique apicole + Assurance + "Abeille de France"'), ('AR', 'Sans abonnement ni assurance'), ) uuid = models.UUIDField( db_index=True, default=uuid_lib.uuid4, editable=False, unique=True, primary_key=True ) annee = models.SmallIntegerField( db_index=True, validators=[ MinValueValidator(2015), MaxValueValidator(datetime.date.today().year + 2) ], default=datetime.date.today().year, ) type_affiliation = models.CharField( max_length=4, choices=TYPE_AFFILIATION, blank=True, null=True) payee = models.BooleanField(default=False) date_payement = models.DateField(null=True, blank=True) affilie = models.ForeignKey( 'Affilie', related_name='affiliations', on_delete=models.CASCADE, editable=False, ) class Meta: ordering = ('payee', … -
How to communicate data between Xcode and Django WebApp
So I am writing an IOS app that will present sort of a notification/message board. At the moment I have the board making a GET request to my django webapp for a JSON file that populates the messageboard. My question is, how should I got about having a live feed to my notifications board? Such that once my webapp has created a "task" my ios app will populate that app as soon as possible, rather than waiting until the next time I open the app. -
getting NoneType object has no attribute '<attribute name>
I tried very hard to find out the problem but i failed. Error-NoneType object has no attribute 'membership_type' i think problem in context ;if i use context as None then the error cause I used foriegn key to refering the Membership class and all the objects of it but still i am getting this error models.py from django.conf import settings from django.db import models from django.db.models.signals import post_save import stripe stripe.api_key = settings.STRIPE_SECRET_KEY MEMBERSHIP_CHOICES = ( ('Enterprise','ent'), ('Professional','pro'), ('Free','free') ) class Membership(models.Model): slug = models.SlugField() membership_type = models.CharField(choices=MEMBERSHIP_CHOICES,default='Free',max_length=30) price = models.IntegerField(default=15) stripe_plan_id = models.CharField(max_length=40) def __str__(self): return self.membership_type class UserMembership(models.Model): user= models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user.username def post_save_usermembership_create(sender,instance, created, *args, **kwargs): if created: UserMembership.objects.get_or_create(user= instance) user_membership, created = UserMembership.objects.get_or_create(user= instance) if user_membership.stripe_customer_id is None or user_membership.stripe_customer_id=='': new_customer_id = stripe.Customer.create(email= instance.email) user_membership.stripe_customer_id = new_customer_id['id'] user_membership.save() post_save.connect(post_save_usermembership_create, sender=settings.AUTH_USER_MODEL) class Subscription(models.Model): user_membership = models.ForeignKey(UserMembership, on_delete=models.CASCADE) stripe_subscription_id = models.CharField(max_length=40) active = models.BooleanField(default=True) def __str__(self): return self.user_membership.user.username courses/views.py from django.shortcuts import render from django.views.generic import ListView, DetailView,View from .models import Course, Lesson from membership_app.models import UserMembership class CourseListView(ListView): model = Course class CourseDetailView(DetailView): model = Course class LessonDetailView(View): def get(self, request, course_slug, lesson_slug, *args, **kwargs): course_qs … -
Zip folder only returning one file
I have a Django application in which a user generates a report in a Word document. I've created an archive page where a user can select from a checkbox form that contains a list of all files that have been created. I've got it working to the point where if I check off just one file, it returns the file with no issue. If I select more than one, it returns a zip file but only containing the first file selected. Where have I gone wrong? How can I tweak my code below to return all reports selected? Return function def create_archive_response(selected_reports): """ Given a list of file names, create a zip in memory and return response object """ zip_name = "generated_reports.zip" s = BytesIO() zf = ZipFile(s, "w") for sr in selected_reports: fp = "/app/created_files/{}".format(sr) zf.write(fp, sr) zf.close() response = HttpResponse(s.getvalue(), content_type="application/x-zip-compressed") response["Content-Disposition"] = f"attachment; filename={zip_name}" return response def reports_page(request): """ Download previously generated reports """ if request.method == "GET": # renders form without issue ... elif request.method == "POST": all_reports = os.listdir("/app/created_files") selections = [int(x) for x in request.POST.getlist("reports")] if len(selections) == 1: file = "/app/created_files/{fn}".format(fn=all_reports[selections[0]]) doc = Document(file) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename={}'.format(all_reports[selections[0]]) doc.save(response) return … -
How to Test in Django the Numbers of Querysets Returned by a CBV
For a real-estate app I have a search form and a class-based ListView that shows only the objects (properties) that match the search query from the form: # views.py from django.views.generic import ListView from django.db.models import Q from .models import Property from .forms import PropertyForm class ListPageView(ListView): template_name = 'property_list.html' model = Property def get_queryset(self): plz = self.request.GET.get('plz') rooms = self.request.GET.get('rooms') if plz and not rooms: object_list = Property.objects.filter(zip_code__exact=plz) elif rooms and not plz: object_list = Property.objects.filter(rooms__exact=rooms) elif plz and rooms: object_list = Property.objects.filter( Q(zip_code__icontains=plz) & Q(rooms__exact=rooms) ) else: object_list = self.model.objects.none() return object_list Tests I wrote a test to check the logic of my view. I was able to write a test that checks if the queryset returns nothing: from django.test import TestCase from django.db.models import Q from na_mi.models import Property class ListPageViewTest(TestCase): @classmethod def setUpTestData(cls): Property.objects.bulk_create( [Property(zip_code=4054,rooms=1), Property(zip_code=4132,rooms=4), Property(zip_code=4132,rooms=4), Property(zip_code=4132,rooms=3), Property(zip_code=4056,rooms=1)] ) # tests if the queryset returns nothing def test_view_no_match(self): response = self.client.get('/list/') self.assertContains(response, 'Sorry, no search result') Question: How can I test my view if it returns the right number of querysets? I want to have a test that ensures that the right number of querysets is returned. Something like that (pseudo code). def test_view_show_zip_code_only(self): response … -
How to signal to Django when inserting data using custom SQL in psycopg2?
When using psycopg2 in order to write data to a postgres database, the data is inserted no problem, however django does not seem to realise it has occurred. There are no signals sent as far as I can tell. My (generic) code for inserting using psycopg2 is shown below: conn = psycopg2.connect(.....) cursor.execute("INSERT INTO ......) conn.commit() cursor.close() conn.close() I have been looking into NOTIFY in postgres, but can't seem to have any luck. Would appreciate if anyone has any advice for this problem and can show me how to send a signal when an INSERT occurs. Perhaps I should explore NOTIFY in postgres? Expected result is a post_save signal maybe? -
How to add this def function?
How to add this two def function and get result . def get_total_co2_electric(self,obj): totalpieces = ElectricBike.objects.all().aggregate(total_co2_electric=Sum('co2')) return totalpieces["total_co2_electric"] # Total Co2 save by Electric def get_total_co2_classic(self,obj): totalprice = ClassicBike.objects.all().aggregate(total_co2_classic=Sum('co2')) return totalprice["total_co2_classic"] -
Searchbar in Django not working: like query is not executed
I am developing an app in Django. I have contents of a database displayed on my template glossario.html ad I want to implement a search bar to query the database and display only the quert results. So I have set up the toolbar in glossario.html <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="topnav"> <a id="pulsante_ricerca_avanzata" href="#Ricerca_avanzata">Ricerca avanzata</a> <div id="blocco_ricerca_semplice" class="search-container"> <form method="GET" action="{% url 'glossario' %}"> <input type="text" placeholder="Ricerca terminologia..." name="q" value="{{request.GET.q}}"> <button id="cancel_search_button" type=""><i class="fa fa-trash"></i></button> <button id="search_button" type="submit"><i class="fa fa-search"></i></button> </form> </div> </div> In views.py have prepared a function to show only the query results: def vista_ricerca_semplice(request): template = "glossario.html" query = request.GET.get('q') selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query)) context = {'selected_entries':selected_entries} return render(request, template, context) Note: Lemma_it is the field of my model I want to search and glossary_entry is the name of my model To tell the truth I am looking for a command to do the query on all the model fields without typing selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query) | Q(field2__icontains=query) | Q(field3__icontains=query) ...) In app/urls.py I have mapped the url of the search results: from django.urls import path from . import views from .views import vista_ricerca_semplice urlpatterns=[ path('', views.home, name='home'), path('aggiungi_terminologia', views.aggiungi_terminologia, name="aggiungi_terminologia"), path('glossario', views.glossario, name="glossario"), path('glossario', views.vista_ricerca_semplice, name="vista_ricerca_semplice"), ] But it … -
List and detail views error in Django using vies.py
I am using the following code in the views.py but i have an error with the Post. here is the code I use : from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) May I have some help to unserstand why the word "Post" in the following line is underline in red : posts = Post.published.all() Note: I am using Visual Studio Code and Django 2.2 Thank you for the help. -
TypeError: unhashable type: 'list' in Django/djangorestframework
first of all I know there are some answers about this TypeError but none of them resolved my case. I did the research and that is why I am posting this question. I got sutck at error saying TypeError: unhashable type:'list' in Django/djangorestframework. I am not even sure where the error is located at because traceback is not that clear to me. Here is my code: serializers.py: from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): """User model serializer""" class Meta: model = User fields = ('id', 'email', 'username', 'password') extra_kwargs = { 'password': { 'write_only': True, 'style': {'input': 'password'} } } def create(self, validated_data): """Create and return a new user""" user = User.objects.create_user(email=validated_data['email'], username=validated_data['username'], password=validated_data['password']) return user I think the problem is in my serializer but if you need me to provide any other file please comment and I will update the question. -
django-filter custom descending label
I am new with django-filter and tried to find a way to change auto-generated labels. Inside my filter class I have ordering = django_filters.OrderingFilter( fields=( ('price', 'Price'), ), ) which gives me list of options like this: *Price *Price (descending) Is there any way to custom descending label. For example I would like to have labels like: *Price (lower to higher) *Price (higher to lower) I know about field_labels={} and how to change ascending labels, but how can I use it with descending option? Thanks! -
Using django annotate to work with percentage
I'm creating a filter by percentage. When I put X (percent), it list all objects that attends. This code below works. def my_example(self, percent): from models import Product return Product.objects.filter(amount=((percent * F("capacity")) / 100)) But I want to improve. My challenge is to use django annotate. I'm tryng something like this: pct = Product.objects.annotate(pct=(percent * F("capacity") / 100)).filter(pct="amount") Someone has any idea? -
Syntax "cellule.utilisateurs.all" does work in a Django HTML template, but not in a Django TeX template
The syntax "cellule.utilisateurs.all" does work with an HTML Django template, but does not work with a TeX Django template. With the HTML Django templates, it displays in the resulting HTML file displayd in the WEB browser the list of users ("utilisateurs" in French) of each cell ("cellule" in French). With the TeX Django template, I get the following error message in the WEB browser: 'method' object is not iterable Here are the different pieces of code: HTML template: <html charset="UTF-8"> <body> <p style="font-size:40px;color:blue">INFOREFLEX_GENER_HTML_CELLULES, version 1.0 (23/07/2019)</p> <p style="font-size:30px;color:red">(Date de l'import des données en base : {{ dateDernierExport }})</p> {% for cellule in listeCellules %} <a id="{{ cellule.dpt_im }}"></a> <h1 style="font-size:60px;color:blue">{{ cellule.dpt_im }}</h1> <table border="1"> {% for utilisateur in cellule.utilisateurs.all %} <tr> <td style="background-color:moccasin;font-weight: bold"><a href="http://annuaire-entreprise.inetpsa.com/?action=exec_recherche_personne&identifiant={{ utilisateur.cod_user }}" target="_blank">{{ utilisateur.cod_user }}</a>-{{ utilisateur.lib_prenom }} {{ utilisateur.lib_nom_usuel }}</td> </tr> {% endfor %} </table> {% endfor %} </body> </html> TeX template: \documentclass{book} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage[french]{babel} \usepackage{color, colortbl} \usepackage{hyperref} \usepackage[margin=0.25in]{geometry} \hypersetup{ colorlinks=true, linkcolor=blue, filecolor=magenta, urlcolor=cyan, } \title{INFOREFLEX_GENER_HTML_CELLULES, version 1.0 (23/07/2019)} \author{OPEN Emmanuel Duvshani} \date{\today} \begin{document} % \maketitle \bigskip (Date de l'import des données en base :\VAR{dateDernierExport}) \bigskip \newcolumntype{y}{>{\columncolor{yellow}}l} %% for cellule in listeCellules \hypertarget{\VAR{cellule.dpt_im}}{\VAR{cellule.dpt_im }} \bigskip \begin{flushleft} \begin{tabular}{ | y | } \hline %% for … -
Sparse index use for optimization with Pyomo model
I have Pyomo model connected to a Django-created website. My decision variable has 4 indices and i have a huge amount of constraints running on it. Since Pyomo takes a ton of time to read in the constraints with so many variables, i want to sparse out the index set to only contain variables that actually could be 1 (i have some conditions on that) I saw this post Create a variable with sparse index in pyomo and tried a for loop for all my conditions. I created a set "AllowedVariables" to later put this inside my constraints. But Djangos server takes so long to create this set while perfoming the system check, it never comes out. Currently i have this model: model = AbstractModel() model.x = Var(model.K, model.L, model.F, model.Z, domain=Boolean) def ObjRule(model): # some rule, sense maximize model.Obj = pyomo.environ.Objective(rule=ObjRule, sense=maximize) def ARule(model,l): maxA = sum(model.x[k,l,f,z] * for k in model.K for f in model.F for z in model.Z and (k,l,f,z) in model.AllowedVariables) return maxA <= 1 model.maxA = Constraint(model.L, rule=ARule) The constraint is exemplary, i have 15 more similar ones. I currently create "AllowedVariables" this way: AllowedVariables = [] for k in model.K: for l in model.L: … -
Instance of 'OneToOneField' has no 'username' member django 2.2.5
I got the following error when I created Profile model Instance of 'OneToOneField' has no 'username' member This is the snippet of the code I created class Profile (models.Model): #Proxy model que hereda los datos base #Primer argumento onetoone on delete define lo que pasa cunado se #elimina el registro que este relaciondo user=models.OneToOneField(User,on_delete=models.CASCADE) website=models.URLField(max_length=100,blank=True) biography=models.TextField(blank=True) phone_number=models.CharField(max_length=8) #Django guarda la referencia al archivo profile_picture= models.ImageField( upload_to='users/pictures', blank=True, null=True ) created = models.DateTimeField(auto_now_add=True) modified=models.DateTimeField(auto_now=True) def __str__ (self): return self.user.username I am getting the error in return self.user.username -
['ManagementForm data is missing or has been tampered with']
I am getting this error when trying to save a form: ['ManagementForm data is missing or has been tampered with'] Views: def scoreInput1View(request): Input1FormSet = modelformset_factory(Player, fields=('name', 'week1')) if request.method == 'POST': form = Input1FormSet(request.POST) form.save() form = Input1FormSet() players = Player.objects.all() context = { 'form': form, 'players': players } template_name = 'leaderboard/input1.html' return render(request, template_name, context) HTML: <form method='POST'> {% csrf_token %} <table> <tr> <th>Name</th> <th>Score</th> <th>17th Score</th> </tr> {{ form.management_form }} {% for field in form %} <tr> <td>{{ field.name }}</td> <td>{{ field.week1 }}</td> {% endfor %} </tr> </table> <input type='submit' value="Save"> </form> Does anyone know what is causing this? -
Django crispy form bootstrap split horizontal form
I am new to django and crispy forms so bear with me. I am having an issue blending bootstrap form types. I have two divs that take up the left and right columns. in the left column I would like the inputs to be standard bootstrap forms. in the right column for space reasons I would like to use horizontal forms. I am using Crispy forms. The trouble is I don't know how to pass the col sizes to the input and the label for only half the fields or on a individual field basis. I know you can set the label and input css for the whole project in the helper, but I only want about half of the fields to be horizontal. I tried the inline form and it worked ok, but the sizing was all off. here is the html, its not really working right {% extends 'base.html' %} {% load staticfiles %} {% load crispy_forms_tags %} {% block head %} <title>Receipt</title> <style> /* .form-inline .form-group-condensed label { width: 250px; justify-content: left; */ /* } */ #rightside>div:nth-child(1) { padding-top: 2.5rem; } </style> <script> $(document).ready(function () { function currentDate() { var today_date = new Date(); $("#date").append(today_date.toLocaleDateString("en-US")); }; currentDate(); … -
How can I make a form to update existing images to a model instance?
I'm making an app that has basic crud functionalities. A parent model is extended by a child model through a foreign key relationship. The second model ads images to the first. I've got the basic crud working ie. adding images and relating them to the first model. I have a hard time getting the child model's form to show images that has already been added through making use of an instance. I would like if possible keep the create and update view in a single view function. I've tried variations of the reverse lookup _set method, but I'm just getting other confusing errors. This is the one that makes most sense to me. def add_image(request): if 'product_id' in request.GET: product_id = request.GET['product_id'] product = get_object_or_404(Product, id=product_id) if request.method == 'POST': form = ProductImageForm(request.POST, request.FILES) if form.is_valid(): productimage = form.save(commit=False) productimage.product = product productimage.save() return redirect('dashboard:products') else: print(form.errors) else: if product.productimage_set: i = product.productimage_set.all() form = ProductImageForm(instance=i) else: form = ProductImageForm() return render(request, 'dashboard/add_image.html', {'form': form}) I would like the form to show the already added images from the instance I'm calling, should the user want to edit the model instance. Instead, I'm getting an error: AttributeError at /dashboard/products/add-image/ 'QuerySet' object … -
ModuleNotFoundError: No module named 'django', when I run tests
When I run the tests (in the pycharm environment) I get an error ModuleNotFoundError: No module named 'django'. Django installed (2.2.5) Traceback (most recent call last): File "/usr/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName module = __import__(module_name) File "/home/m0nte-cr1st0/projects/slack_bot/tests.py", line 4, in <module> from app.models import * File "/home/m0nte-cr1st0/projects/slack_bot/app/models.py", line 1, in <module> from django.db import models ModuleNotFoundError: No module named 'django' -
Clicking button without uploading file
I have an html form that users can upload files but if users clicking directly to submit button without uploading any file django gives an error. How can I control this problem? upload.html <!-- Upload form. Note enctype attribute! --> <form method="post" enctype="multipart/form-data" multiple> {% csrf_token %} <input type= "file" name ="docfile" multiple/> <button id="yukle" type="submit" value="Upload"> <img src="/static/img/upload.png" width=28 height=30 alt="Yükle"/> </button> </form> views.py def SenetList(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): dosya_tipi = "Senet" context = upload(request.FILES.getlist('docfile'),form, dosya_tipi) return render(request, 'operations/upload3.html', context) else: form = DocumentForm() return render(request, 'operations/upload3.html', {'form': form}) forms.py class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file', help_text='max. 42 megabytes' ) I gave an error like this: ValueError at /upload/senet The view operations.views.SenetList didn't return an HttpResponse object. It returned None instead.