Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-admin: change column font to red when if condition is true
I have a vlog that I can preload vlog entries into the db, so that when the date of vlog-published-date is less than the models field of now, the vlog entry will be automatically displayed / published. How can I make the django-admin column of Vlog Date Published font red when the date of the vlog_published_date is greater than now (not yet published)? Here is a visual example of what I mean where the now date is January 16, 2018: Here is my vlog models.py code: class VlogDetails(models.Model): .... vlog_date_published = models.DateField(null=False, blank=False, default=datetime.now, help_text='The date the vlog video will be made public.') .... class Meta: .... There is this similar thread, but the thread is 7+ years old and I was hoping there was information more current to django 1.10 and python 3.5. -
Django, GDAL and CircleCI 2
I have a Django app configured with GeoDjango that is failing on CircleCI 2.0 builds with the following error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library. Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. However, when I remove 'django.contrib.gis' from DJANGO_APPS in settings.py the build runs successfully. Are there additional steps for configuring GDAL in CircleCI outside of the postgres and GDAL docker images? I (perhaps incorrectly) assumed that GDAL would be found after the docker image was installed. Below is my config.yml: version: 2 jobs: build: docker: - image: circleci/python:3.6.3 - image: circleci/postgres:10.1-postgis environment: - POSTGRES_USER=ubuntu - POSTGRES_DB=myapp_test - image: geodata/gdal working_directory: ~/repo steps: - checkout # Download and cache dependencies - restore_cache: keys: - v1-dependencies-{{ checksum "requirements.txt" }} # fallback to using the latest cache if no exact match is found - v1-dependencies- - run: name: install dependencies command: | python3 -m venv venv . venv/bin/activate pip install -r requirements.txt - save_cache: paths: - ./venv key: v1-dependencies-{{ checksum "requirements.txt" }} - run: name: run tests command: | . venv/bin/activate python manage.py test environment: DATABASE_URL: "postgres://ubuntu@localhost:5432/myapp_test" - store_artifacts: path: test-reports destination: test-reports -
Using Django Model form with ManyToMany relationship fields
I'm new to development. I have three tables. Table A and Table B have a OneToMany relationship. Where A can have many B's but a B can only have one A. The data from Table A and Table B are already synced. Their relationship table has all the data it needs. Table A and Table B both have a ManyToMany relationship with Table C. I need a form that will link the information in Table C to Tables A and B. I need a form that includes all three tables in a scroll down format. The user would pick an option on table A, depending on their choice on Table A they will get choices on Table B and then all the options in Table C would show up independent of choices A and B. Once the users pick what they want from each scroll down I want the users to be able to submit the form. Once submitted, I need the form to POST relationships, so that it fills the TableA_TableC and TableB_TableC tables in the database. Later on I'll be able to query all the items that Table A has related to Table C, and the items that … -
How to Iterate over four arrays one by one and printing them in django template?
I am going to print four array values simultaneously in django template . like this the four arrays are of equal length ,they are header_list , domain_list , domain_data , dom for i in range(10): print headerlist[i] print domain_list[i] print domain_data[i] print dom[i] how to acheive these in django template . -
Different field values for each user
I have this model: class Product(models.Model): art_name = models.CharField(max_length=100) plu_num = models.IntegerField(default=0, unique=True) sales_price_brutto = models.FloatField(null=True) sales_price_netto = models.FloatField(null=True) last_price = models.FloatField(null=True) purchase_price_brutto = models.FloatField(null=True) purchase_price_netto = models.FloatField(null=True) entry_date = models.DateField() margin = models.FloatField(null=True) stock = models.IntegerField(default=0) I created for example two user groups. Then I want to each group of users have different values in stock and sales_price_brutto (save method of model calculate rest of the fields values depending on sales_price_brutto and purchase_price_brutto). I tried adding one more field: owner = models.ForeignKey(Group, editable=False) But it seems to not work as I want. I don't really know if there is a way to do that. -
How can I escape underscores in Django's field lookups?
By default, Django cannot support trailing underscores in field names because it messes up field lookups. Unfortunately, I've found myself in a situation where the Postgres table was created without using Django and now I have to do the following: queryset = queryset.filter(**{field + '__icontains': value}) This field could have an underscore. How do I tell Django to ignore the first of the triple underscores and find the field? It clearly knows about the field because it shows it as an option in the error: django.core.exceptions.FieldError: Cannot resolve keyword 'ccc' into field. Choices are: _bbb, aa_a, ccc_ But I have not found any way to force filter to do what I want. Is there a syntax that let's me explicitly specify field name and lookup? -
Django queryset filter max values for list
I'm wondering if there is any way to pass a list to a django queryset and limit to the max/min/latest/oldest value for each item in the list. Basically something like this: serial_list = [2231, 2232, 2233] data_queryset = Data.objects.filter(serial__in=serial_list).latest() I'm fully aware that the above code doesn't work. I'm just trying to illustrate a queryset that would return the .latest() value for each object where the serial is in serial_list. -
Stacked in django2.0 tutorial / why "from . " is needed to import views?
I just start learning Python3.x from scratch. in the tutorial of django 2.0, I stacked with this question. please help me to solve the problem. as a module, following code is work [directory] mydir | +-test.py +-test2.py ====================== [test.py] import test2 test2.say() ====================== [test2.py] def say(): print("hey") but in django tutorial_01, (https://docs.djangoproject.com/en/2.0/intro/tutorial01/) [directry] polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.py ====================== [poll/urls.py] from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] import command does not work without "from .", even views.py exist in the same directory. Error message says "ModuleNotFoundError: No module named 'views'" could you explain why this kind Error is occurred ? Thank you in advance! -
Custom Django login form middleware
I'm looking at a solution of implementing a modal pop-up login form to be used site wide in the navigation bar. I'm working with Django 1.11. Now, I'm defining a LoginFormMiddleware class as follows: middleware.py from django.http import HttpResponseRedirect from django.contrib.auth import login from django.contrib.auth.forms import AuthenticationForm class LoginFormMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_request(self, request): from django.contrib.auth.forms import AuthenticationForm if request.method == 'POST' and request.POST.has_key('base-account') and request.POST['base-account'] == 'Login': form = AuthenticationForm(data=request.POST, prefix="login") if form.is_valid(): from django.contrib.auth import login login(request, form.get_user()) request.method = 'GET' else: form = AuthenticationForm(request, prefix="login") request.login_form = form This is all included in the standard way in settings.py in MIDDLEWARE = []. I also have 'django.template.context_processors.request' defined in TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ *** ] } ] as I should. Using {{ request.login_form }} in my templates as follows: <div class="container"> {{ request.login_form }} </div> Yet nothing is being rendered - where it should? From browser inspector tools: Can anyone advise me on what I am missing please? -
TypeError: url() got an unexpected keyword argument 'name_space'
I know it looks like a simple problem but I'm still too new for sorting it out myself, so : learing_log/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', 'learning_logs.urls',name_space='learning_logs'), ] Previously I had the following error so I've removed the include function ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. learing_logs/urls.py """Defines URL patterns for learning_logs.""" from django.conf.urls import url from . import views urlpatterns=[ #Homepage url(r'^$',views.index,name='index'), ] views.py from django.shortcuts import render #Create your views here. def index(request): """The home page for Learning Log""" return render(request,'learning_logs/index.html') Im using Django 2.0 and Python 3.6.1 Could you please advice why I'm getting TypeError with name_space arg, is that related to Django version, many thanks in advance. -
django The form does not show on the page
The form does not show on the page what is the problem I tried a lot but there was difficulty comment.html: <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> views.py : def post_detail_view(request,year, month, day, post): post = get_object_or_404(Post,slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) context ={ 'post':post } return render(request,'post/comment.html',context) comments = post.comments.filter(active=True) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.post = post new_comment.save() else: form = CommentForm() return render(request,'post/comment.html',{'post':post, 'comments': comments, 'form':form}) The form does not show on the page what is the problem I tried a lot but there was difficulty forms.py : from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name','email','body','website',) models.py : class Comment(models.Model): post= models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE) name = models.CharField(max_length=80) website = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering =('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name,self.post) The form does not show on the page what is the problem I tried a lot but there was difficulty urls: from django.conf.urls import url from . import views urlpatterns = [ #url(r'^$',PostListView.as_view(),name='blog'), url(r'^$',views.post_list_view,name='post_list_view'), #url(r'^(?P<pk>\d+)/$',PostDetailView.as_view(),name='post_detail'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$',views.post_detail_view,name="post_detail_view"), ] The … -
Django: automatically assigning foreign key in CBV form
This builds on: Django automatically set foreign key in form (with class based views). The answer there seems like it would work but Django throws a ValueError I have (2) models: Product and Procedure that are related by a foreign key. I want to have a link from the Product page to add the Procedure, and have the product FK (via its pk) automatically passed to the form. There are several thousand products, so selecting the FK manually from a dropdown isn't feasible. class ProductBase(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False) name = models.CharField(max_length=128,null=False) class ProcedureText(models.Model): id_procedure = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False) text_procedure = models.TextField() parent_product = models.ForeignKey(ProductBase,on_delete=models.CASCADE') I have a link from the Product details page to call a CreateView: <a class='btn btn-success' href="{% url 'products:addprocedure' pk=product_details.pk %}">Add Procedure</a> which is mapped through urls.py: path('addprocedure <pk>',views.AddProcedureView.as_view(),name='addprocedure'), class AddProcedureView(CreateView): form_class = AddProcedureForm template_name = 'addprocedure.html' model = ProcedureText #fields = ('__all__') def form_valid(self, form): form.instance.parent_recipe = self.kwargs.get('pk') return super(AddProcedureView, self).form_valid(form) calling in forms.py class AddProcedureForm(forms.ModelForm): class Meta: model = ProcedureText fields = ('__all__') and templating out to a standard form: <form class="form-horizontal" action="" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Submit</button> </form> Whenever the form is submitted, Django returns a ValueError of … -
django return edited form validation data from 'clean'
Python 3.x Django 2.x Hi, I have an address form. I am aware of the clean_<field> methods and the clean method. I am doing some per-field validation and that is all working. I want to validate/normalize the address information and am doing that in clean. I am in the US and my use case fits in the USPS address API (I think). In any case, I can build the USPS XML query structure from the cleaned_data dict. I can make the API call and receive the possibly reformatted XML API result. I can harvest the possibly reformatted data from the result XML and I can put it into cleaned_data or self.cleaned_data. I then try returning either cleaned_data or self.cleaned_data but the modified vales do not show up in the model. def clean(self): # # get the form data cleaned_data = super().clean() # # build a USPS xml object address_wrapper = xmlET.Element("AddressValidateRequest", attrib=dict( USERID=config_parser['USPS']['username'] )) ... # # build the request quoted_xml = urllib.request.quote(xmlET.tostring(address_wrapper)) with urllib.request.urlopen(config_parser['USPS']['url'] + "?API=Verify&XML=" + quoted_xml) as response: ... # # get the result of the request xml_result = response.read().decode('utf-8') my_xml = xmlET.fromstring(xml_result) # # cannonacalize the US address info self.cleaned_data["address1"] = "" if my_xml.find("Address1"): self.cleaned_data["address1"] = … -
Django Admin render TimeField as 12 hour time
In the Django admin I have it accepting input in 12 hour time inputs but when I return to it on the admin it is just turning that into a 24 hour time and leaving it in that field. Is there a way I can have it displayed in the admin as a 12 hour time input? class ShowDateAdminForm(ModelForm): time = forms.TimeField(input_formats=['%I:%M %p']) class Meta: model = ShowDates exclude = ('show_slug',) -
Using Django 2.0 So django.core.urlresolvers is no longer supported, how to make this try except block work?
I am trying to get the try except block to work with django 2.0. def find_recurrence_i18n_js_catalog(): # used cached version global _recurrence_javascript_catalog_url if _recurrence_javascript_catalog_url: return _recurrence_javascript_catalog_url # first try to use the dynamic form of the javascript_catalog view try: return urlresolvers.reverse( i18n.javascript_catalog, kwargs={'packages': 'recurrence'}) except urlresolvers.NoReverseMatch: pass I'm assuming that if I change it to this that it won't work: # first try to use the dynamic form of the javascript_catalog view try: return reverse( i18n.javascript_catalog, kwargs={'packages': 'recurrence'}) except: pass -
Why gunicorn don't use all the ressources but delier slowly pages
I've a setup with : Jelastic (PaaS) with Auto-Vertical Scaling Nginx as SSL/TLS end-Point + Reverse Proxy (inside docker) Gunicorn serving a Django application (inside docker) Postgres (inside docker) When the traffic is "heavy" (100 r/s), the page is very slow to be delivered, even if all containers are not very used (cpu 40% in Idle on application container, only use 2gb of 8 RAM used - other container more or less 0 % of CPU usage). I've already set Gunicorn worker to 16, I've check linux limit (fd, socket) and everything seems OK, so why it doesn't scale up ? nginx.conf (key value) worker_processes auto; events { use epoll; worker_connections 4096; } http { sendfile on; keepalive_timeout 10; } Gunicorn start : gunicorn --bind 0.0.0.0:80 --workers 16 --max-requests 1000 ****.wsgi:application -
ImportError at post/new al crear un formulario con Django
I'm new to DJango and I have some doubts about forms. Here is the code, I would appreciate your help :D This is the error that appears to me: enter image description here directories and files: blog |--_pycachce_ |--migrations |--static |--templates |--blog |--base.html |--forms.py |--post_bio.html |--post_detail.html |--post_edit.html |--post_list.html |--models.py |--tests.py |--urls.py |--views.py |--_init_.py |--admin-py forms.py code: {% extends 'blog/base.html' %} {% block content %} <h1>New post</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} urls.py code: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), ] views.py code: from django.shortcuts import render from django.utils import timezone from django.shortcuts import render, get_object_or_404 from .models import Post from .forms import PostForm from .models import Post from .forms import PostForm def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts' : posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def post_new(request): form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) -
VsCODE error when importing Django module
I work on Mac os with Vs code on a python WebApp and I use Django as framework. I get an error when I try to import some Django module. This is a snap of my code in error. Image of my code in error The error message is the following : [pylint] E0401:Unable to import 'django.conf.urls' -
Django Rest ManyToMany(self) Post request
Here the Model: class User(AbstractBaseUser, PermissionsMixin): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) id = models.AutoField(primary_key=True) username = models.CharField(max_length=25, unique=True) email = models.EmailField(unique=True, blank=False) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) releation = models.ManyToManyField("self", blank=True, symmetrical=True) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "username" I have no idea how to write the serializer... I've been trying and testing around but I never get to the point where it works. And I don't really find anything after many hours of searching -.-. Maybe I can't see the wood full of trees anymore or Django is just not my gusto at all -
Read The Docs ImportError
For a long time I can not find the right way. I always get a mistake. I have already tried all the paths listed below. os.path.abspath sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(".")))) sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, os.path.dirname(os.path.abspath('.'))) sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath('..')) Here is the ReadTheDocs error output Running Sphinx v1.6.5 making output directory... Traceback (most recent call last): File "/home/docs/checkouts/readthedocs.org/user_builds/kh-taskbuster/envs/latest/local/lib/python2.7/site-packages/sphinx/cmdline.py", line 305, in main opts.warningiserror, opts.tags, opts.verbosity, opts.jobs) File "/home/docs/checkouts/readthedocs.org/user_builds/kh-taskbuster/envs/latest/local/lib/python2.7/site-packages/sphinx/application.py", line 168, in __init__ confoverrides or {}, self.tags) File "/home/docs/checkouts/readthedocs.org/user_builds/kh-taskbuster/envs/latest/local/lib/python2.7/site-packages/sphinx/config.py", line 150, in __init__ execfile_(filename, config) File "/home/docs/checkouts/readthedocs.org/user_builds/kh-taskbuster/envs/latest/local/lib/python2.7/site-packages/sphinx/util/pycompat.py", line 150, in execfile_ exec_(code, _globals) File "/home/docs/checkouts/readthedocs.org/user_builds/kh-taskbuster/envs/latest/local/lib/python2.7/site-packages/six.py", line 709, in exec_ exec("""exec _code_ in _globs_, _locs_""") File "<string>", line 1, in <module> File "conf.py", line 23, in <module> from django.conf import settings ImportError: No module named django.conf Exception occurred: File "conf.py", line 23, in <module> from django.conf import settings ImportError: No module named django.conf Here is my conf.py line 1-19 only comments import os import sys sys.path.insert(0, os.path.abspath('.')) from django.conf import settings settings.configure() Here is my project three -
Can Django filter using just a CASE or a COALESCE expression?
I'm trying to write build a Django Queryset off of a working Postgres query which has the following WHERE condition: ... WHERE COALESCE("project_story"."owner_id" = [INSERT_USER_ID], "project_story"."published_date" IS NOT NULL) In english: if the user is the owner of the story, then include it. If the user is not the owner and if the story is unpublished, then exclude it. Ideally, the Django ORM should allow something like: queryset = queryset.filter( Coalesce( Q(owner_id=user.id), Q(published_date__isnull=False) ) ) But upon executing, Django throws the following error: TypeError: 'Coalesce' object is not iterable Unfortunately, the framework I'm using demands that I do the filtering at the database level. Is there a notation that I'm missing that would allow me to filter based on a Coalesce expression? I'd prefer not to use rawsql or queryset.extra. -
Django auth views causing Http502 (with Gunicorn + Nginx)
I'm getting 502s when I try to access any of the views that rely on auth (so /admin/login/, posting to my own /login/ page, etc). It's not occurring on any other views/requests. Here's the nginx acess log: GET /admin/login/ HTTP/1.1" 502 182 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0 Not much that's going to help me there. Here's an extract from the gunicorn log (the first line is a worker booting from when the last one died): [2018-01-15 19:44:43 +0000] [4775] [INFO] Booting worker with pid: 4775 [2018-01-15 19:46:10 +0000] [4679] [CRITICAL] WORKER TIMEOUT (pid:4775) [2018-01-15 19:46:10 +0000] [4775] [INFO] Worker exiting (pid: 4775) What's causing me to lose workers and get 502s? -
How does Django CreateView class instanciate models?
I have a basic model / form / views: models.py class Tag(models.Model): name = models.CharField(max_length=100, unique=True) forms.py class TagForm(forms.ModelForm): class Meta: model = Tag fields = '__all__' views.py class TagCreate(CreateView): model = Tag form_class = TagForm success_url = reverse_lazy('view_somethin') When using django-rest-frawework or Tag.objects.create(name="aagagaga"), the "name" field is passed to the __init__() of Tag, and i can do all hacks i want. But when using the class based view, __init__() is of course called but no args are passed to. However, in the save method, i can check that the name attribute is already set to the good value. My question is, how and where the data are transfered to the model instance if in case of class based views nothing is passed to the __init__() ?? I try to dig in the source code with no success, i suspect some king of manager If you want to reproduce the issue, here is the testing code: class Tag(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return f"Tag {self.name}" def __init__(self, *args, **kwargs): print(args) print(kwargs) super().__init__(*args, **kwargs) print(self.__dict__) def save(self, *args, **kwargs): print(self.__dict__) # the filled attributes are here, but when were they filled ? super().save(*args, **kwargs) Tag.objects.create(name="aagagaga") # this call the … -
Django Auto Complete Light Usage on Backwards ForeignKey
I'm wondering if anyone has an example for implementing Django AutoComplete Light (DAL) to be used in a backward foreign key look up in the Django Admin site? For example. class Issue(models.Model): publisher = models.ForeignKey(Publisher,related_name='issues') class Publisher(models.Model): name = models.CharField(max_length=255) Then when editing a Publisher I would like an Django Autocomplete Light lookup to list out the issues the publisher is related to and let me look up and add any additional issue with the Issue Model Table. -
Django import excel file using openpyxl
I want to add an excel file to my model My view code is like this by using openpyxl : def excel_import(request): uploadform=UploadFileForm(None) if request.method == 'POST' : uploadform = UploadFileForm(request.POST, request.FILES) if uploadform.is_valid(): file = uploadform.cleaned_data['docfile'] workbook = openpyxl.load_workbook(filename=file, read_only=True) first_sheet = workbook.get_sheet_names()[0] worksheet = workbook.get_sheet_by_name(first_sheet) data = [] for row in worksheet.iter_rows(row_offset=1): # Offset for header stock = Stocks() stock.user = request.user stock.name = row[0].value stock.number = row[1].value stock.suffix = row[2].value stock.brand = row[3].value stock.comment = row[4].value stock.price = row[5].value stock.date = datetime.today() stock.confirm = 'approved' stock.seller = row[7].value data.append(stock) # Bulk create data Stocks.objects.bulk_create(data) return render(request, 'BallbearingSite/news.html',{'uploadform':uploadform}) the problem is it add some extra empty rows for example i had 4 rows in my excel file , it added 32 rows which 4 of them were the rows of the excel file, also for 6 or 10 rows and when i had 42 rows it added 3 extra empty rows !!!!! How can i fix it ? where is the problem in it ?