Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to refer to foreign key linked table (django)
I have two models: class Incident(models.Model): iid = models.IntegerField(primary_key=True) class Source(models.Model): sid = models.IntegerField(primary_key=True) incident = models.ForeignKey('Incident', on_delete=models.SET_NULL, null=True) url = models.TextField(validators=[URLValidator()]) I want to display every source linked to an incident, but this doesn't work: {% for source in incident.source.all %} {{ source.url }} {% if not forloop.last %}, {% endif %}{% endfor %} -
Django TemplateHTMLRenderer - Rendering a HTML view
I'm trying to render some objects from my model to HTML. I initially thought this was going to be straightforward (and it likely is) but I'm coming up against numerous errors. In this project I have built some API views that work fine (HintsListApiView and HintsRudView work). But I'd ideally like to use the API to produce a regular - read only HTML page that I can then style as I wish - my HTMLAPIView. I'm trying to use TemplateHTMLRenderer, but am coming up against errors. All I want is to get the text attribute to show up in HTML. The actual texts are just a sentence long each. These are my files: models.py: from django.db import models from rest_framework.reverse import reverse as api_reverse class Hints(models.Model): text = models.TextField(max_length=255) author = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.text) def timestamp_pretty(self): return self.timestamp.strftime('%b %d %Y') def get_api_url(self, request=None): return api_reverse("api-hints1:hints-rud", kwargs={'pk': self.pk}, request=request) views.py: class HTMLAPIView(generics.RetrieveAPIView): lookup_field = 'pk' serializer_class = HTMLSerializer renderer_classes = (TemplateHTMLRenderer,) def get_queryset(self): queryset = Hints.objects.value('text') return Response({'queryset': queryset}, template_name='base.html') class HintsListApiView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'pk' serializer_class = HintsSerializer def get_queryset(self): qs = Hints.objects.all() query = self.request.GET.get("q") if query is not None: qs = qs.filter( Q(text__icontains=query)| … -
Modelformset_factory does not save to database
I am trying to scale multiple modelforms by using modelformset_factory and save them to database to their respective models. Even though code creates different forms for different models but it does not save them to database. Advise how to do it would be highly appreciated. Thank you. views.py from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Revenue_Assumptions, COGS_Assumptions, Assumptions model_names = [Revenue_Assumptions, COGS_Assumptions] def get_assumptions(request): AssumptionsFormSet_dict = {} for name in model_names: modelformset_ = modelformset_factory(name, form = AssumptionsForm, extra = 5) AssumptionsFormSet_dict[str(name)] = modelformset_ if request.method == 'POST' and str(name) in request.POST: print('reached post') formset = AssumptionsFormSet_dict[str(name)] if formset.is_valid(): print('valid form') print(str(name)) for form in formset: print('in for loop after valid form1') name = form.save() else: for key, value in AssumptionsFormSet_dict.items(): formset = AssumptionsFormSet_dict[key] print('reached else') return render(request, 'assumptions.html', {'formset': formset, 'model_names': model_names, 'name' : name}) assumptions.html <div class="form"> <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} {% for name in model_names %} <h1>{{name}}</h1> <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle 'row1' 'row2' %}"> {% for … -
Duplicate entry error in customize signup form in djnago
We have a django project app name "blog". We have built customized signup for same having fields like : Name ,mobile,email and password. In MYSQL DB , it is giving "Duplicate Entry Error " for table blog_Customuser and entry is made into table for email,password ,but no entry made for mobile column. Also no entries made to account_emailaddress table. Also while debugging the code ,doesn't stop at any below lines code marked for debug. Entry into Settings.py - ACCOUNT_SIGNUP_FORM_CLASS = 'blog.forms.AllauthUserRegisterForm' Form.py entry looks like this : class AllauthUserRegisterForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Name'})) mobile = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Mobile'})) #password = forms.CharField(widget = forms.PasswordInput) class Meta: model = CustomUser fields = ['email', 'mobile'] Models.py entry looks like this : class CustomUser(AbstractUser): name = models.CharField(default='', max_length=200, blank=True) mobile = models.PositiveIntegerField(null=True, blank=True) email = models.EmailField(unique=True) USERNAME_FIELD = 'email' # to enforce that you require email field to be associated with # every user at registration REQUIRED_FIELDS = ["mobile"] def __str__(self): return self.email Table blog_customuser column details `id` int(11) NOT NULL AUTO_INCREMENT, `password` varchar(128) NOT NULL, `last_login` datetime(6) DEFAULT NULL, `is_superuser` tinyint(1) NOT NULL, `username` varchar(150) NOT NULL, `first_name` varchar(30) NOT NULL, `last_name` varchar(30) NOT NULL, `is_staff` tinyint(1) NOT NULL, `is_active` tinyint(1) NOT NULL, `date_joined` … -
Implementing Django pagination in Reactjs
I have been struggling implementing Django pagination in React through JSON request which has over 3000 images For some reason, React isn't efficient in fetching images. My code to Pagination in Django looks like paginator = Paginator(images_list,50) images_pages = request.GET.get('page') image_pagination = =paginator.get_page(image_page) Im thinking to use return JSONResponse(image_pagination) but cant see myself thinking a bit ahead than that inside react. I'm trying to utilize query-string along with Redux to implement the Pagination for my React project. Would really appreciate your help in any way :) -
MOD_WSGI Xampp v3.2.2 + Windows 64 bit + Python 2.7.13 + Django
I have a problem starting Apache service in Xampp v3.2.2 in Windows 7 64 bit to work with Python and Django. The Apache service would not start after I edit httpd.conf with this added value : LoadModule wsgi_module modules/mod_wsgi.so My mod_wsgi.so file is from the packages that I already installed and downloaded from : https://www.lfd.uci.edu/~gohlke/pythonlibs/#mod_wsgi mod_wsgi‑4.5.24+ap24vc9‑cp27‑cp27m‑win32.whl mod_wsgi‑4.5.24+ap24vc9‑cp27‑cp27m‑win_amd64.whl Both files I have tested installed with : pip install mod_wsgi‑4.5.24+ap24vc9‑cp27‑cp27m‑win32.whl or pip install mod_wsgi‑4.5.24+ap24vc9‑cp27‑cp27m‑win_amd64.whl It's because the I can't install with this command: pip install mod_wsgi doesn't work. nor creating from source downloaded from here : https://github.com/GrahamDumpleton/mod_wsgi I can not install from source with this command : set "MOD_WSGI_APACHE_ROOTDIR=C:/xampp/apache" python setup.py install The last error Is : build\lib.win-amd64-2.7\mod_wsgi\server\mod_wsgi.pyd : fatal error LNK1120: 101 unresolved externals error: command 'C:\\Users\\SAU\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\link.exe' failed with exit status 1120 image :error build mod_wsgi from source My Question : * Is there any correct binary mod_wsgi package for my system that can run with Xampp v3.2.2 + Windows 7 64 bit and where to get it * If I should build mod_wsgi myself how to handle the error when building the mod_wsgi binary * Is there any other solution so I can run the Django framework … -
print and logger.errors in for loops
Is there any reason why a print statement or a logger.error wouldn't print to the command prompt (I'm developing on my local machine) when executed in a for loop? I've got the following code within one of my views that pertains to a form set. As there are multiple forms to if formset.is_valid(): instances = formset.save(commit=False) print ("Im outside the for loop") for instance in instances: print ("Im inside the for loop") instance.user = request.user ... #other code that successfully runs There is code within the "for instance in instances" loop that I know executes. I commented out the loop and the page breaks. As a result, I'm 100% certain the for loop is being executed 3x (there are 3 forms in the formset), but the print statement "Im inside the for loop" doesn't hit command prompt once. I've tried using logger.error as well with the same result: The 'outside' error prints, but there are no 'inside' errors that print. I'm baffled on this one. Thanks for your help! -
What does the error RuntimeError: populate() isn't reentrant mean
To be specific, I have a standalone script in my django app folder, which is accessing the models,as per the django docs here you have to do the following configuration: import os import django os.environ['DJANGO_SETTINGS_MODULE'] = settings_file django.setup() But when i run the server i get the error RuntimeError: populate() isn't reentrant -
UnicodeEncodeError: 'charmap' codec can't encode character - Python Report CSS
I know this kind of question has been asked before but nothing worked for me. I'm trying to generate some PDF report using weasyprint. Here is my code; htmlContent = py_str["htmlContent"] HTML(string=htmlContent).write_pdf(target=response, stylesheets=[CSS(string=getCSS())]) but it doesn't generate any PDF. On debugging I found out that issue is in this getCSS() function that returns css string. By print this funtion on console, I'm getting this error UnicodeEncodeError: 'charmap' codec can't encode character '\x91' in position 5042: character maps to <undefined> this is CSS that I've from line number 5040 to 5042 .nav-pills > li { float: left; } All solutions that I found out are related to utf-8 but I could not understand where to use this utf-8 in my code. I'm totally stuck here. Any kind of help will be appreciated. I can add full css if needed. -
Docker-Compose + Django + PostgreSQL + uwsgi + Nginx getting 404 not found
I have recently make some service for practice. I used Docker-Compose, Django, PostgreSQL, uwsgi, Nginx. I try to run in my local machine. Here is what my site like when I access it on my server. Here is part of about static my settings.py file in the Django 'django_project' root directory. # STATIC FILE CONFIGURATION STATIC_DIR = SRC_DIR.path('static') STATIC_ROOT = str(SRC_DIR('staticfiles')) STATIC_URL = '/static/' STATICFILES_DIRS = [str(SRC_DIR('static'))] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) Here is my Docker-compose file version: '2' services: nginx: restart: always build: ./nginx ports: - "80:80" volumes_from: - refrigerator links: - refrigerator:refrigerator depends_on: - refrigerator refrigeratordb: image: "postgres:9.6.1" container_name: refrigeratordb expose: - "5432" environment: POSTGRES_PASSWORD: "something" POSTGRES_USER: "something" POSTGRES_DB: "something" refrigerator: build: . container_name: refrigeratormanager depends_on: - refrigeratordb links: - refrigeratordb volumes: - .:/var/www/refrigerator - /usr/src/app/static command: uwsgi --ini ./refrigerator_manager_uwsgi.ini stdin_open: true tty: true Here is my Dockerfile for Django FROM centos/python-36-centos7:latest USER root ADD . /var/www/refrigerator/ WORKDIR /var/www/refrigerator RUN pip install --upgrade pip RUN pip install -r requirements.txt EXPOSE 8000 Here is my Dockerfile for Nginx FROM nginx:alpine RUN rm /etc/nginx/conf.d/default.conf COPY ./sites-enabled/nginx.conf /etc/nginx/conf.d/default.conf Here is my nginx.conf server { listen 80; server_name sodwkdrhdjemals.com www.sodwkdrhdjemals.com; charset utf-8; location /static { alias /static; } location / { … -
Calling image of nth model in template
I'm passing 5 headshots and 5 testimonials to a template in my context using the following: context = { 'headshots': headshots, 'testimonials', testimonials, } Each instance of the headshot model has a field of image. Within the template, I want to write each image using the forloop counter. {% for t in testimonials %} {{ t.body }} <img src="{{ headshots[forloop.counter].image }}" {% endfor %} My syntax appears to be wrong and the code in the tag is throwing an error. Any thoughts as to where I've gone wrong? Thanks! -
Django Rest Framework Nested Serializers
I am currently having trouble executing two layered nesting with django rest framework. I have read the DRF docs with nested relationships here http://www.django-rest-framework.org/api-guide/relations/ and have succesfully done the first layer which is to show styles with many colors in JSON. Not sure how to chain another layer though. Any help would be appreciated. Thanks in advance! The result I would like looks something like this: [ { style: ABC123, colors: [ {name: 'Red', sizes: [ {name: 'S'}, {name: 'M'} ], {name: 'Orange', sizes: [ {name: 'L'}, {name: 'XL'} ] ],... } ] Specifically, I would like to show that each style has a set of colors attributed to it, and each style-color combination has a set of sizes attributed to it. Below is my current models.py I've used intermediate table because I plan to add further complexities in the future (e.g. in style-color I would like to attach location of the colored picture and in style-color-size I will attach measurements) class Style(models.Model): name = models.CharField(max_length=36, unique=True) colors = models.ManyToManyField('Color', through='StyleColor') sizes = models.ManyToManyField('Size', through='StyleColorSize') class Color(models.Model): name = models.CharField(max_length=36, unique=True) class Size(models.Model): name = models.CharField(max_length=12, unique=True) class StyleColor(models.Model): style = models.ForeignKey('Style', on_delete=models.CASCADE) color = models.ForeignKey('Color', on_delete=models.CASCADE) class Meta: unique_together … -
Django: How can I give certain objects unique urls without errors (e.g. mysite.com/object)
I'm wanting to make urls like this: path('<slug:slug>/', login_required(views.CompanyDetailView.as_view()), name='company_detail'), But it leads to errors, like 404s become "No company found for that slug," and other errors. So I am having to do this, like reddit: path('c/<slug:slug>/', login_required(views.CompanyDetailView.as_view()),name='company_detail'), How can I make my urls like my first snippet of code without errors? -
A Complete guide to publish a news website
Am a beginner in front end and back-end , so please don't downvote this question. I have thought of building a news website as a project to learn front-end and back-end as well. So I need a complete guide / walkthrough. Like storing news article in database , a common template for all the news articles.. and any extra things needed -
django ValueError: invalid literal for int() with base 10:
I'm trying to make a query to the Preferences table I have in django, but whenever I try to do a lookup to find a users entry, it just gives me this error. ValueError: invalid literal for int() with base 10: 'jason' The lookup I'm doing is this. Preferences.objects.filter(customer='jason') I can do this though which is odd. Preferences.objects.all() And I retrieve the query set of the one object I want. When I ask Preferences.objects.all()[0].customer And here I do retrieve the string 'Jason'. Can you explain what's going wrong either in my query or in the code? Any help would be appreciated and I can give other parts of code if needed! #models.py class Preferences(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE) ebay_token = models.TextField(max_length=1024) app_id = models.CharField(max_length=128, default='asdf', editable=False) dev_id = models.CharField(max_length=128, default='1234', editable=False) cert_id = models.CharField(max_length=128, default='1234', editable=False) #this might need to be correct. I'm not sure if the user should have this much control over markup markup = models.FloatField(max_length=3, validators=[MaxValueValidator(50, message='Can\'t be this high!'), MinValueValidator(1, message='Can\'t be this low!')]) seller_location = models.CharField(max_length=256) #the ebay site number might need editing ebay_site_number = models.IntegerField() quantity = models.IntegerField(validators=[MinValueValidator(1, message='Must be atleast 1'), MaxValueValidator(10, message='Must be equal to or smaller than 10')]) #this will def … -
DRF one to many serialization -- AttributeError from missing field
Error: AttributeError at /stats/matches Got AttributeError when attempting to get a value for field players on serializer MatchSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Match instance. Original exception text was: 'Match' object has no attribute 'players'. Models: Every Match has 10 players. class Match(models.Model): tournament = models.ForeignKey(Tournament, blank=True) mid = models.CharField(primary_key=True, max_length=255) mlength = models.CharField(max_length=255) win_rad = models.BooleanField(default=True) class Player(models.Model): match = models.ForeignKey(Match, on_delete=models.CASCADE) playerid = models.CharField(max_length=255, default='novalue') # There is also a Meta class that defines unique_together but its omitted for clarity. Serializers: class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = "__all__" class MatchSerializer(serializers.ModelSerializer): players = PlayerSerializer(many=True) class Meta: model = Match fields = ("mid","players") -
Deleting model instance on save if field in model is null
I've got a model called Service. Upon the user saving the model form, I'd like the model instance to be deleted if the body is null. Here is my code. class Service(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) heading = models.CharField(max_length=60, null=True, blank=True) body = models.TextField(max_length=5000, null=True, blank=True) price = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): if self.body == None: #also tried if bool(self.body) == False: self.delete() else: pass This code is not successful at deleting the model instance when body is null (or blank). Do you know where I've gone wrong? Thanks! -
Oraginizing django urlpatterns for APIs
I would like to use an api version index for all my API endpoints (api/v1/). Currently I'm achieving it by structuring my urlpatterns like so: urlpatterns = [ path('api/v1/units/', include('units.api.urls')), path('api/v1/accounts/', include('accounts.api.urls')), ] Is there a way to organize this more elegantly? Ideally I would like it to look something like this: apipatterns = [ 'units/', include('units.api.urls'), 'accounts/', include('accounts.api.urls') ] urlpatterns = [ path('api/v1/', include(apipatterns)), ] -
Post_save in django is being called twice when using objects.create(...) method
In django post_save signal we can know if an object is new or modified using the created flag. But, the post_save signal is called twice when create an object using objects.create method, Where the create method does init then save(). The post save has created = False when it is called using init and it gets to be created=True after saving the object, How can I differentiate between an object is being modified and then saved or an object is being initialized? Here is a link to an old question, but it does not answer my question: Django post save signal getting called twice despite uid -
Adding Django CMS to an existing Django site. Can it damage the existing site and data?
A friend asked if they could/update their existing site to Django CMS It has a n e-commerce section added to it and apparently uses the Maris DB. He wants to use Django CMS mostly to easily add articles and other content. How intrusive or dangerous is it to install Django CMS to an already existing Django site especially it's customized existing e-commerce section? Thank you. -
Enable dirty reads for single transaction in Django
I'm building a REST API in Django where users can run tasks for objects. I've created a simple example below where I use transactions to easily rollback the state of the object in case the task fails. from django.db import IntegrityError, transaction def send_object(id): obj = MyModel.objects.get(pk=id) if obj.state != 'Created': raise ValueError('Object not in state "Created"') with transaction.atomic(): obj.state = 'Sending' obj.save() # send the object... obj.state = 'Sent' obj.save() Now I want the state of the object to be visible for users through the API while the task is running. Since the transaction isn't commited until the task is done, users only see the current state before and after the task. I need some sort of transaction in case of a system failure/shutdown occurs during the task and the object gets stuck at 'Sending'. The state must be reset so that the task easily can be retried. The isolation level is set to READ COMMITTED and cannot be changed without updating other parts of the code. Can I make the new state available before the transaction is commited (i.e. enable dirty reads) for just this transaction? Or is there something else I can do? -
The empty path didn't match any of these - Django 2 By Example
I am trying to complete the Django Girls blog in the Django 2 by example book. I ran into this error: error message This is the code in my urls.py: code in mysite/urls.py Here is the code in the blog/urls.py code in blog/urls.py I did add this 'blog.apps.BlogConfig' to settings.py I followed carefully the instructions but somehow couldn't fix the problem. Can you please help me? Thanks a ton -
How to give a parent name in serializers?
I have three serializers as below: class MalbSerializer(serializers.ModelSerializer): class Meta: model = malb fields = ('zoning', 'zoningdesc', ) class MasrSerializer(serializers.ModelSerializer): class Meta: model = masr fields = ('solddate', 'soldprice', ) class MataSerializer(serializers.ModelSerializer): class Meta: model = mata fields = ('assessyear', 'landvalue', ) The views is as below: malb_serializer = MalbSerializer(malb.objects.filter(maid=maid), many=True) masr_serializer = MasrSerializer(masr.objects.filter(maid=maid), many=True) mata_serializer = MataSerializer(mata.objects.filter(maid=maid), many=True) reponse = malb_serializer.data + masr_serializer.data + mata_serializer.data return Response(reponse) as a result, the response is as below: [ { "zoning": null, "zoningdesc": null, }, { "solddate": null, "soldprice": null, }, { "assessyear": null, "landvalue": null, } ] I want to give each element a tag like as below: [ {"Land Building": { "zoning": null, "zoningdesc": null, }}, { "Sales Record":{ "solddate": null, "soldprice": null, }}, {"Tax Assessment":{ "assessyear": null, "landvalue": null, }} ] I have tried to use a nested serializer, but I don't have a model which includes all these three messages, which can I use to give them a json parent name base on my current code? Any help will be many appreciated. Thanks! -
How to override DurationField widget with three NumberInput for years, months and days?
The default widget for DurationField is a single input box. But I need three input boxes, one for years, other for months and the last for days, the three inputs need to be converted to days to be stored in a single DurationField. Is there a way to archieve this? -
Getting an error whenever i click on add to cart button
i created a cart app inside an ecommerce site am building but when i click on the add cart form that is rendered on my page, it doesn't come through. any help will be appreciated inside the cart app, i have the normal django files in it.(__init__.py, admin.py, apps.py, cart.py (added by me), models.py, tests.py, urls.py and views.py) Here are the content of files in my cart app that i filled with content. for cart.py: from cart.models import CartItems from catalog.models import Product from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect import decimal import random CART_ID_SESSION_KEY = 'cart_id' # get the current user's cart id, sets new one if blank def _cart_id(request): if request.session.get(CART_ID_SESSION_KEY,'') == '': request.session[CART_ID_SESSION_KEY] = _generate_cart_id() return request.session[CART_ID_SESSION_KEY] def _generate_cart_id(): cart_id = '' characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()' cart_id_length = 50 for y in range(cart_id_length): cart_id += characters[random.randint(0, len(characters)-1)] return cart_id # return all items from the current user's cart def get_cart_items(request): return CartItems.objects.filter(cart_id=_cart_id(request)) # add an item to the cart def add_to_cart(request): postdata = request.POST.copy() # get product slug from post data, return blank if empty product_slug = postdata.get('self.slug','') # get quantity added, return 1 if empty quantity = postdata.get('quantity',1) # fetch the product or return a missing …