Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
Ajax Post method not detected in django
I'm discovering Ajax with Django and cannot to make them work. Before I continue, the project directory looks like this: mySite | |-> myApp |-> views.py |-> urls.py | ... // other py-files and directories |-> mySite |-> urls.py | ... // other py-files When I run the site and trigger the event for sending an Ajax request, I get a status 200 code but the function in views.py doesn't get executed so I assume that my urls.py is not properly configured. The Javascript implementing the Ajax post: function sendReq(){ console.log('AJX'); $.ajax({ type: 'POST', url: 'ajax_test', data:{ name: 'AjaxReq', val: '...', csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, sucess:function(){ console.log('SUCCES!'); } }); console.log('AJX done'); } The urls.py of myApp: from django.conf.urls import url from . import views urlpatterns = [ url(r'^', views.index, name='index'), url(r'^ajax_test', views.ajax_test, name='ajax_test'), ] The urls.py of mySite: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^',include('myApp.urls')), ] And finally the views.py of myApp: from django.shortcuts import render from django.http import JsonResponse def index(request): return render(request, 'myApp/index.html') def ajax_test(request): if request.method == 'POST': name = request.POST.get['name', None] val = request.POST.get['val', None] print(name + ': ' + val) I found different solution but seemed outdated. Can someone … -
Django admin panel app model list_display not showing
Here is my code from django.contrib import admin from farmer.models import * class listAllFarmer(admin.ModelAdmin): list_display = ('username', 'code') admin.site.register(allFarmers, listAllFarmer) if I write this only it works from django.contrib import admin from farmer.models import * admin.site.register(allFarmers) -
Django Inner Join tables with queryset
I'm trying to INNER join 2 tables. Comments and Auth. So i store userid in comment table and i need to pair it with auth. I did with .raw() but i don't want to do with raw, i have tried also other like get_objects_or_404 but that does not work either because of multiple querys. Here is my query works as excepted. "SELECT * FROM index_comment INNER JOIN auth_user WHERE index_comment.userid=auth_user.id" So i need to pair userid from comment table to auth id, and then get the username. -
django.core.exceptions.FieldError: Unknown field(s)
I've seen a lot of issues similar to mine, but none had exactly the same problem. I have my code running on another machine and it's working perfectly, it's exactly the same code since I'm using github for version control, but when I run on my machine I started to get this error, I use postgres, I already tried give drop in the database and create another but continue with this error. The error started after I imported the database from the machine that is running fine. When I tried to go back to the local database, I started to have an error, I already tried to reinstall all the packages (those installed via pip) and nothing. -
does django saves Charfield as strings?
so basic and confused about this question. i tried to see type of some objects in django and equals together . see example below : print(type(request.data['token'])) >>> <class 'str'> and : obj = UserProfile.objects.get(pk=1) print(type(obj.first_token)) >>><class 'app.models.first_token'> obj.first_token is a charfield. so how can i know that first_token stored as string? if request.data['token'] == obj.first_token: are this two objects equals if have a same value in them? -
Django how to build an invoice that gives the user the ability to add multiple items?
I am trying to build a e-shop using django 2.0, but I have a 'logic' question not a syntax one, how to build an invoice that can accept many Items? In other words I have a model for the invoice item that is connected To a product model but I do not know how to build an invoice view that That gives the user the ability to add multiple items to this invoice How to do so knowing that I use CBV for the views? Thanks in advance -
LoginView with Success
I am currently working with my Django authentification app. My goal is once the user logged in successful I want to redirect it to the index page where my code shows a customised message: messages.success(request, 'Login Successful', extra_tags='alert alert-dark') My problem is I didn't manage to 'access' LoginView in my views.py. I read about SuccessMessageMixin, but this LoginView won't work (Template Not Found): class LoginView(auth_views.LoginView): template_name = "accounts/login.html" Do you have any idea how to solve this? Only as long I include template_name in my urls.py it works, but I can't add the success message mixin there. urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='accounts/login.htm'), name='login'), ] -
Django - Increase a model field based on another model
I have a model called Product and a model called Stock. The model Product has a field called 'stock_current' that should show the current stock of an product and in model Stock has a field called 'quantity'. I'm looking for a way to when register one entry in model Stock, the field 'stock current' of Product's model get the current number and increase with the field 'quantity' of Stock model. I'm totally lost since i am a beginner with django. #model class Product(models.Model): name = models.CharField(max_length=200) code = models.CharField(max_length=200) cost = models.FloatField(blank=True, null=True) price = models.FloatField(blank=True, null=True) stock_min = models.IntegerField(blank=True, null=True) stock_current = models.IntegerField(blank=True, null=True) stock_control = models.BooleanField(default=True) class Stock (models.Model): product = models.ForeignKey(Product, blank=False, null=False) quantity = models.IntegerField(blank=False, null=False) #views def stock_add(request, stock_id=None): if stock_id: v_stock = Stock.objects.get(pk=stock_id) else: v_stock = None if request.method == 'POST': form_stock = StockaddForm(request.POST or None, instance=v_stock) if form_stock.is_valid(): resp = form_stock.save() if resp: messages.success(request, "Product has been registred !") return redirect('/') else: form_stock = StockaddForm(instance=v_stock) context_dict = {} context_dict['form_stock'] = form_stock return render(request, 'admin_panel/register/stock_add.html', context_dict) Until now i just know the way how to register a stock. The question is how to add the value of 'quantity' field to 'stock_current' field of a … -
Django Internationalization Broken URL
i followed all of the steps for the internationalization. I created the messages and compiled them for en and ro. When i go to my localhost /en/ i can see all of the items from navbar. The same when i go to my /ro/ site. But them i click from /ro/ to /ro/aboutus, instead of going to the romanian page of about us {"Despre noi"} i am redirected to en/about us. Do you know why this happens? Thank you! -
Modeling multiple many to many relationships
My goal is to create a voting API for users to make a Choice selection from a list of choices. Choice can be anything like cars, food, travel location, etc. Each user will select their choice then the votes will be tallied up and displayed. For instance, to create a vote, I would access the endpoint /votes. In the json data I would add the users I want in the vote group as well as indicate my own vote, sending something like this: Post: {creator: "self" vote_attr: 5 particiants: [{ user : "self", choice: "35"}, { user : "2", choice: ""}, { user : "3", choice: ""}, ] } Response: { vote_id: 23 vote_attr: 5 creator: "self" participants: [{ user : "self", choice: "35"}, { user : "2", choice: ""}, { user : "3", choice: ""}, ] } I'm having trouble figuring out how to represent this relation in DRF. I've read up on through models and nested relationships but still don't fully understand either as well as which will be needed for my what I'm trying to do. models.py class User(models.Model): name = models.CharField(max_length = 50) email = models.CharField(max_length = 50) class Choice(models.Model): name = models.CharField(max_length = 50) description … -
How to enable daily new filename of logging in Python Django's Settings?
I want to log the calling of restful api on each day into yyyy-mm-dd.log. In settings.py I write: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' }, }, 'handlers': { 'infofile': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'C://mydoc/logs/'+str(datetime.date.today())+'.log', 'formatter':'standard', }, }, 'loggers': { 'django': { 'handlers': ['infofile'], 'propagate': True, }, }, If the server started e.g. on 01.01.2018, the "2018-01-01.log" will be created and all logs will be written into the file, even the callings is on 15.01, because the settings.py is run only one time on 01.01 at the server's starting. How can Django create everyday a new log file and use the file? -
MetaTrader 4 MT4 api
So, im developing backed in Python Django. Client is asking to implement synchronization with MT4 system. I tried to find solution, but all is dead end. Everything they are saying is here are the dlls use them in you .NET project, etc. I want to ask you if somebody has done this in some other language using something other than .NET (eg python, php, nodejs, java) and if that works in Linux environment, since our server is Ubuntu? -
If-None-Match header not accepted request header
I'm trying to understand how Etag works in Django. I added middleware in settings ('django.middleware.http.ConditionalGetMiddleware') and this seems to work as it generates the Etag: HTTP/1.0 200 OK Date: Mon, 15 Jan 2018 16:58:30 GMT Server: WSGIServer/0.2 CPython/3.6.0 Content-Type: application/json Vary: Accept Allow: GET, HEAD, OPTIONS X-Frame-Options: SAMEORIGIN Content-Length: 1210 ETag: "060e28ac5f08d82ba0cd876a8af64e6d" Access-Control-Allow-Origin: * However, when I put If-None-Match: '*' in the request header, I get the following error: Request header field If-None-Match is not allowed by Access-Control-Allow-Headers in preflight response. And I notice the request method sent back in the response is OPTIONS and the rest of the headers look like this: HTTP/1.0 200 OK Date: Mon, 15 Jan 2018 17:00:26 GMT Server: WSGIServer/0.2 CPython/3.6.0 Content-Type: text/html; charset=utf-8 Access-Control-Allow-Origin: * Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Max-Age: 86400 So the question is how do I get If-None-Match to be an allowed header? I'm not sure if this is a server or client issue. I'm using Django/DRF/Vue for my stack and Axios for making http requests.