Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
xhtml2pdf Pisa css broken Unknown color False
I am trying to generate a PDF using html+css using xhtml2pdf.pisa using Django. However, I'm running into all sorts of weird issues with the CSS. Below is my code: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None And my template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Example 2</title> <style> @font-face { font-family: SourceSansPro; src: url(SourceSansPro-Regular.ttf); } .clearfix:after { content: ""; display: table; clear: both; } a { color: #0087C3; text-decoration: none; } body { position: relative; width: 21cm; height: 29.7cm; margin: 0 auto; color: #555555; background: #FFFFFF; font-family: Arial, sans-serif; font-size: 14px; font-family: SourceSansPro; } header { padding: 10px 0; margin-bottom: 20px; border-bottom: 1px solid #AAAAAA; } #logo { float: left; margin-top: 8px; } #logo img { height: 70px; } #company { float: right; text-align: right; } #details { margin-bottom: 50px; } #client { padding-left: 6px; border-left: 6px solid #0087C3; float: left; } #client .to { color: #777777; } h2.name { font-size: 1.4em; font-weight: normal; margin: 0; } #invoice { float: right; text-align: right; } #invoice h1 { color: #0087C3; font-size: 2.4em; line-height: 1em; font-weight: normal; margin: 0 0 10px 0; } #invoice … -
Django url error when GET request with params,
I have a Django API to export file which needs format as input, Request URL: http://192.168.5.51:1212/rest/tasks/export_file/CIAYEK5W5JS4MdmCF2t8eB?format=xyz this request returns a error response detail (with status 404) but when I use get request without query params, Request URL: http://192.168.5.51:1212/rest/tasks/export_file/CIAYEK5W5JS4MdmCF2t8eB The API is triggered and the file is returned(with default format). As far as i know we don't need to change anything in urlpatterns to support query params. I have also put the specified url in first line to eliminate the chance for any other regex catching the request urlpatterns = [ url(r'^/export_file/(?P<pk>.+)$',views.TaskFileTranscript.as_view()), How to support query params in django requests. Thank you in advance. P.S : Im pretty sure the control is not reaching into the get function, Im using DRF. -
Django, how set the model field to give only month and year?
I have a question for you. I have the following model: class Budget_Vendite(models.Model): product=models.ForeignKey() income=models.DecimalField() date=models.DateField() I have an algo in my django app that split my income based on month as following: for product_id, year, month, totale in(Budget_Vendite.objects.values_list('prodotto__name', 'date__year', 'date__month'). All works perfectly but now I have the need to give the possibility to choose only month and year and not also the day. In other words is it possible to set DateField in this manner without modifying my algo structure? -
IntegerField doesnt accept negative number django
i try to make some calculate using annotate and Sum,F in django 2.2 and then the output output_field=IntegerField but sometimes the result of calculating will be negative number < 0 and it wont accept the negative number and raise this error : i use mysql version : 8 as the database 1690, "BIGINT UNSIGNED value is out of range in(some fields name) this is my query MyModel.objects.annotate( income=Sum( (F('somefield_name__a') * F('somefield_name__b')) - F('somefield_name__c'),output_field=IntegerField()) ) is there something accept positive and negative integer at the same time ? please thanks .. -
Django Channels with Postgre multi tenancy
I have followed the documentation at this link https://readthedocs.org/projects/building-multi-tenant-applications-with-django/downloads/pdf/latest/ Part3 'Shared database with isolated schema' to implement multiple schemas in my django app. It works great for the normal http requests using the custom middleware showed in the docs but i have an issue when it comes to have it working with websockets, specifically i am using django channels. I tried to make a custom middleware to similar to the one suggested in the docs for the http request but with no luck. Does anybody had experience with that and can suggest a possible solution? Thanks :) -
Comparing two lists and saving the values to a django model instance
Sorry if duplicate. Can't quite figure out the proper way to save a model instance based on the list comparison I'm trying to do. class FruitStock(models.Model): name = models.CharField(max_length=100) oranges = models.IntegerField(null=True, blank=True) bananas = models.IntegerField(null=True, blank=True) apples = models.IntegerField(null=True, blank=True) class FruitShipment(models.Model): name = models.CharField(max_length=100) bushels = models.IntegerField(null=True, blank=True) store = models.ForeignKey(Store, on_delete=models.CASCADE) python manage.py shell from app.models import * a = list(FruitShipment.objects.filter(store=1).values('name', 'bushels')) b = [field.name for field in FruitStock._meta.get_fields()] What I want to do is save an instance of Fruitstock with the bushels value as the value for the attribute field value. a = [{'name': 'ORANGES_060222', 'bushels': 5}, {'name': 'BANANAS_062620', 'bushels': 3}] b = ['name', 'oranges', 'bananas', 'apples'] How can I compare a to b and then create a new object instance for class FruitStock and save it? In shell I try for item in a: if item['name'].lower() in b: b.value() = item['bushels'] I get error: File "", line 3 SyntaxError: cannot assign to function call It's maybe more of a python question but I don't know how to set b.value = items['bushels'] -
How to return two dictionaries in python?
views.py def index(request): dests = photo.objects.all() return render(request, "index.html", {'dests':dests}) def gallery(request): gals = wedding.objects.all() return render(request, "gallery.html", 'gals':gals) -
How can I present IMDB info in html using Django and BeautifulSoup?
people. I am kinda new to Django and WebScraping but I am having issues with presenting the info in html via Django. I want to use a function so I can present the info in HTML/DTL like so (this example is just pure Python and the way it prints the info is the way I want it to be represented in HTML): import requests from bs4 import BeautifulSoup source = requests.get("https://www.imdb.com/search/title/?genres=comedy").text soup = BeautifulSoup(source, "lxml") for article in soup.find_all("div", class_="lister-item-content")[:5]: headline = article.h3.a.text summary = article.find_all("p", class_="text-muted")[1].text movie_launch = article.find("span", class_="lister-item-year text-muted unbold").text[1:5] movie_duration = article.find("span", class_="runtime").text movie_rating = article.find("div", class_="inline-block ratings-imdb-rating").text director = article.find_all("p")[2]("a")[0].text star1 = article.find_all("p")[2]("a")[1].text star2 = article.find_all("p")[2]("a")[2].text star3 = article.find_all("p")[2]("a")[3].text print(headline, summary, movie_launch, movie_duration, movie_rating, director, star1, star2, star3) And the result is (don't worry about how the structure looks, I didn't format it yet): The King of Staten Island Scott has been a case of arrested development since his firefighter dad died. He spends his days smoking weed and dreaming of being a tattoo artist until events force him to grapple with his grief and take his first steps forward in life. 2020 136 min 7.2 Judd Apatow Pete Davidson Bel Powley Ricky Velez Knives … -
Django 3.0: How to use different Boostrap versions in same template
I have made a template (Base.html) in my django project, of Bootstrap 4 which working is fine independently. I have also made another template (Child_Base.html) which is made with Bootstrap 3 and supposed to be injected in Base.html. But what happening here is, when I include BS3 template in first one it is ruining many things. So, I am looking for a solution in which both co-exist and doesn't spoil other one. Code of Base.html is supposed as follows: <!DOCTYPE html> <html lang="en"> <head> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> </head> <body> <p> {% block bodyblock %} Hello World! {% include "Child_Base.html" %} {% endblock %} </p> </body> </html> Code of Child_Base.html is supposed as follows: <!DOCTYPE html> <html lang="en"> <head> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> </head> <body> <p> {% block bodyblock %} Good Morning! {% endblock %} </p> </body> </html> In actual scenario, there is product page, displaying all the books available for user to add in cart (made in BS4) in which I want to include search box (made in BS3). But code is tangled and not so self-elaborated so I have used above examples. Thanks. -
how to apply an is a relation in Django models while the abstract class have many to many relation?
I've tried to reflect this in Django models as the following: class Service(TimeStampedModel): class Website(Service): class SocialMedia(Service): class Item(models.Model): class Order(models.Model): items = models.ManyToManyField(OrderItem) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) #The issue is when I try to create banner as an Item in a website class Banner(Item): website = models.ForeignKey(Website, on_delete=models.CASCADE) class Post(Item): social_media = models.ForeignKey(SocialMedia, on_delete=models.CASCADE) I am getting an error: services.OrderItem.item: (fields.E300) Field defines a relation with model 'Item', which is either not installed, or is abstract. What is the right way to build this relating? Or any suggestion to have like different services in one cart with different attributes and categories. -
Store name value with Django sessions for another view
The error that Django throws at me when I fill in the form is: 'GetSessionName' object has no attribute 'name' and I have never worked with sessions before so I don't know how to solve this problem. The idea of the site is to have a small Login screen where you type your name then move to the chat. views.py from django.shortcuts import render, redirect from django.utils import timezone from .models import * from .forms import Chat, GetSessionName def chat(request): Messages = Message.objects.all().order_by('-created') form = Chat() if request.method == "POST": form = Chat(request.POST) if form.is_valid(): form.save() return redirect ("chat") name = request.session['name'] context = {"Message": Messages, "form": form, 'name': name} return render(request, 'chat/chat_messages.html', context) def login(request): form = GetSessionName() if request.method == "POST": form = GetSessionName(request.POST) if form.is_valid(): request.session['name'] = form.name return redirect('chat') context={'form': form} return render(request, 'chat/chat_login.html', context) forms.py from django import forms from django.forms import ModelForm from .models import Message from .models import * class Chat(forms.ModelForm): class Meta: model = Message fields = "__all__" class GetSessionName(forms.Form): name = forms.CharField(max_length=30) chat_login.html {% extends 'chat/base.html' %} {% block content %} <form method="POST" action=""> {% csrf_token %} {{form}} </form> {% endblock content %} -
how to write multiple filter on django queryset?
i am working with django rest data is list contains fitness_target body_target_list is list, contains body_area equipment_list is contain number of equipments for d in data: exercise_obj = ExerciseMapping.objects.filter(fitness_target__contains = [d,], \ level=1,sub_level = 1,user_category = usr_cat) for target in body_target_list: exercise_obj = exercise_obj.filter(body_area__contains = [target,]) for equipment in equipment_list: exercise_obj = exercise_obj.filter(required_equipment = equipment) exercise_details = ExerciseMappingSerializer(exercise_obj, many=True) here i am trying to apply filter on ExerciseMapping model, but condition is that next filter need to be apply on previous one and so on. here one queryset result is dependant on previous queryset object -
Django : Add a dictionary into another one with a loop
I have a problem, I'm trying to make a Django Rest API. With this API, I want to send a list of product. For that, I tried to make a for loop to upgrade my dictionary which contain my data. This is my code : from rest_framework.decorators import api_view from rest_framework.response import Response from .models import product, by_product #List all the products @api_view(['GET']) def listing(request): context = {} product = product.objects.filter(dispo=1).order_by('name') for product in product: if not product.price_kg: price = product.price_uni unit = 'units' else: price = product.price_kg unit = 'Kg' dictionary = { 'id' : product.id, 'name': product.name, 'price': price, 'unit': unit, 'category': product.categorie, 'byProduct': [], } context = ({**context, **dictionary}) #Upgrade my dictionary by_products = by_product.objects.filter(product_id=product.id).order_by('bycat') for byprod in by_products: context['byProduct'].append({ 'id' : byprod.id, 'name' : byprod.bycat, }) if product.redu: context['oldPrice'] = product.redu return Response(context) In my JSON file, I just get data for the last product. Thanks by advance. -
What is the best way to bulk create in a through table?
This is what my through table looks like: class ThroughTable(models.Model): user = models.ForeignKey(User) society = models.ForeignKey(Society) I am getting 2 lists containing ids of 2 model objects, which have to be added in my through table. user_list = [1,2,5,6,9] society_list = [1,2,3,4] Here I want to create the entry in Through table for each possible pair in these 2 lists. I was thinking about using using nested loops to iterate and create the objects in Through table, but it seems very naive, and has a complexity of n*n. Is there a better approach to solve this issue? -
Django static file not changing my website when I make edits
I'm new to Django and web page design but I am having an issue I can't seem to find an answer for anywhere. I want to tweak the look of my web page a bit but for some reason when I go into the static file to change e.g. the RGB value for header colour it doesn't change to the new colour entered despite me saving the file and resetting the server. I even tried deleting the static file entirely and it made no change to my web page. It seems to me that somehow it has saved the data from the original static file I made and no matter what I change the file to it won't impact the page in any way. Please give me any suggestions for things that you think could be causing this issue to happen, Thanks. {% load static %} Note; if I get rid of the above line from my code the webpage totally breaks and if I get rid of the below line the webpage e.g. has no header colour (it doesn't even use the data I originally entered into the static file) <link rel="stylesheet" href="{% static 'css/blog.css' %}"> -
Django DatePicker widget for DateField with format MM-YYYY
I have set the following model: class Budget_Vendite(models.Model): data=models.DateField() Having the need to choose only month and year I have set in my form the following code: from tempus_dominus.widgets import DatePicker, TimePicker, DateTimePicker class Budget_VenditeForm(forms.ModelForm): data=forms.DateTimeField(widget=DatePicker(attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, }, options={'format': 'MM/YYYY'})) class Meta: model = Budget_Vendite fields = "__all__" But when I submit the form the objects is not saved. Why? This is my views.py def budget_vendite(request): if request.method == 'POST': form = Budget_VenditeForm(request.POST) if form.is_valid(): print("Il form è valido") new_input = form.save() else : form = Budget_VenditeForm() .... -
How to pass values of drop down from html template to views in Django?
I need to send the value of the selected option in a drop down to the views. My html code is as follows: <select name="version" id="version" onchange="location = this.value;"> <option>Select version to compare with</option> {%for ver in version_list%} **<option value={{ver}} href="{% url 'process_data' ver %}">{{ver}}</option>** {% endfor %} </select> The above is giving me the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/index/11.5.1.18900-96 http://127.0.0.1:8000/index/11.5.1.18900-97 Using the URLconf defined in Piechart_Excel.urls, Django tried these URL patterns, in this order: admin/ index/ process_data/<str:ver> [name='process_data'] The current path, index/11.5.1.18900-96, didn't match any of these. However if I am sending the value as follows i.e. without any drop down: **<a href="{% url 'process_data' ver1 %}">{{ver}}</a>** everything is working as expected. My urls.py file content is as follows: from django.urls import path from fusioncharts import views urlpatterns = [ path('index/', views.index, name='index'), path('process_data/<str:ver>', views.process_data, name='process_data'), ] Can anyone say why is it not working in the case of drop down but working otherwise? If we have to send any value from the html template using drop down, then how to do so? Thanks. -
No app named 'account' in my project but django still throws django.db.migrations.exceptions.NodeNotFoundError
Traceback : File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\Anaconda\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\Anaconda\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Anaconda\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\Anaconda\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\Anaconda\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "D:\Anaconda\lib\site-packages\django\core\management\commands\makemigrations.py", line 87, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "D:\Anaconda\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "D:\Anaconda\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "D:\Anaconda\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "D:\Anaconda\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "D:\Anaconda\lib\site-packages\django\db\migrations\graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "D:\Anaconda\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0012_user_following dependencies reference nonexistent parent node ('account', '0002_contact') There's no app named account in my project but i am still getting this error. I have tried to delete all pycache and migration files but it is not helping. I even tried to run the project in a virtual environment but i am still getting this error. Please help. -
I want to change the django template filter when dropdown is change?
i am loading products in html by using django templates tag ({% for i in products%} and it is working fine but i have an Dropdown section which is for sorting like sort by pricse,by name and etc i know with django tag {% for i in products|dictsort:"item_titile" %} we can easily do it but I want to change it value and reload the page with {% for i in products|dictsort:"{{dropdown_value}}" %} when the following dropdown change <div class="select-option"> <select class="sorting" id='sorting'> <option value="">Default Sorting</option> <option value="item_titile">Sort By Titile</option> <option value="item_category">Sort By Catagory</option> <option value="item_name">Sort by name</option> <option value="item_FrashPricse">Sort by pricse</option> </select> -
How to write manager class to set default attribute value for models while retrieval/filtering in Django queries?
class StudentModelManager(models.Manager): def get_queryset(self, *args, **kwargs): return ( super(StudentModelManager, self) .get_queryset() .filter(is_deleted=False) ) class StudentDetails(models.Model): name = models.TextField(null=True, default=None) is_deleted = models.BooleanField(default=False) objects = StudentModelManager() I have four entries in database 2 with is_deleted=False and 2 with is_deleted=True. Because of StudentModelManager in StudentDetails model I cannot retrieve records from database for is_deleted=True. I want to make sure that the default parameter while retrieving should be is_deleted=False, but when explicit parameter is given like is_deleted=True, it should return objects with that value. Actual Entries in db without applying StudentModelManager to StudentDetails model are : >>> StudentDetails.objects.all() <QuerySet [<StudentDetails: StudentDetails object (27)>, <StudentDetails StudentDetails object (29)>, <StudentDetails: StudentDetails object (30)>, <StudentDetails: StudentDetails object (28)>]> Entries retrieved from db with applying StudentModelManager to StudentDetails model with is_deleted=False: >>> StudentDetails.objects.all() <QuerySet [<StudentDetails: StudentDetails object (27)>, <StudentDetails StudentDetails object (29)>]> Now see the actual issues, Not able to retrieve entries with is_deleted=True >>> StudentDetails.objects.filter(is_deleted=True) <QuerySet []> Expected output is: >>> StudentDetails.objects.filter(is_deleted=True) <QuerySet [<StudentDetails: StudentDetails object (28)>, <StudentDetails StudentDetails object (30)>]> How can this achieved? -
Getting Error when starting my Django server
I wrote new models, made migrations, migrated the models but forgot to register the models in the admin.py file. After migrating I started my server and got the following error: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Bilawal Hassan\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Bilawal Hassan\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Bilawal Hassan\PycharmProjects\Ecommerce Website\venv\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Bilawal Hassan\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", … -
DJANGO basic shop
im looking for very basic Django online shop project (or online tutorial) where shopping cart, would be a model in same app as items and users, connected as in example below or sth similar: class Cart(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) items = models.ManyToManyField(Item) -
Navbar For Ecommerce Website Using Django
I am designing eCommerce website based on django in backend. I want to create navbar which will contain menu based on categories of products. I want this Navbar dynamic as whenever new category posted it should automatically appear in menu field. My front end is bootstrap and Html. Please help me with logic. Thank You. -
Get some examples for each unique value of a field in django
I have a model called NewsArticles which has a field country as a CharField with choices as the country names. I want to make a queryset getting 4 articles for each country. For now the only way I could think of is to get the unique country list and then get individual querysets for each which seems like a little computational heavy. Like so: countries = NewsArticle.objects.order_by('country').values_list('country', flat=True).distinct() final_queryset = NewsArticle.objects.filter(country=countries[0])[:4] for index in range(1, len(countries)): final_queryset |= NewsArticle.objects.filter(country=countries[index])[:4] Is there a better or more straightforward way to do this? -
Syntax error on view with if else if branch
I have a view where I am trying to detect which group a logged in user is a member off and displaying an appropriate page, or redirecting them back to the login screen. No matter how I try to write this, I continue to get a syntax error. Nothing more clear than that. My view at the moment is: from django.shortcuts import render from django.shortcuts import redirect def loginCheck(request): if User.objects.filter(pk=userId, groups__name='red').exists(): return render(request, 'colors/red.html', {}) elif User.objects.filter(pk=userId, groups__name='blue').exists() return render(request, 'colors/blue.html', {}) elif User.objects.filter(pk=userId, groups__name='staff').exists() return redirect('/site/staff/') else: return redirect('/site/login/') Is this approach sound? Am I missing an obvious mistake?