Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django inlineformset_factory error_messages not working
I use a subform and validation works fine. But I want to override the error_messages, which for some reason doesn't work when using inlineformset_factory. What I want to achieve is overriding the required error message of the formset. The django documentation says: error_messages is a dictionary of model field names mapped to a dictionary of error messages. For that reason in inlineformset_factory I passed a dictionary as following: forms.py: from django import forms from .models import Product from brand.models import Brand from masterdata.models import Masterdata from django.forms.models import inlineformset_factory Master_Inlineformset = inlineformset_factory( Product, Masterdata, fields=('title', 'description', 'mpn', 'brand_id', 'categories'), extra=1, can_delete=False, labels={'title': 'Title', 'description': 'Description', 'mpn': 'Articlenumber', 'brand_id': 'Brand', 'categories': 'Categories'}, error_messages = { 'brand_id': { 'required': 'some custom required message', }, } ) You can also have a look on the remaining files: views.py: class ProductUpdateView(LoginRequiredMixin, UpdateView): form_class = ProductCreateForm template_name = "artikel/product_form.html" def get_queryset(self): queryset = Product.objects.filter(pk=self.kwargs.get("pk")) return queryset def get_context_data(self, *args, **kwargs): context = super(ProductUpdateView, self).get_context_data(*args, **kwargs) if self.request.POST: formset = Master_Inlineformset(self.request.POST, self.request.FILES, instance=self.object) else: formset = Master_Inlineformset(instance=self.object) context["formset"] = formset return context def form_valid(self, form, **kwargs): self.object = form.save() context = self.get_context_data(**kwargs) formset = context["formset"] if formset.is_valid(): formset.save() else: return render(self.request, self.template_name, {"form": self.form_class(self.request.POST), "formset": formset,}) … -
Nginx unable to load static files from django
family, Im having a little trouble to make nginx server load static file collected by django. here is my nginx sites-available server { listen 80; server_name <my_ip_address>; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; } location /asset/ { autoindex on; alias /var/www/html/dev2_assets/; } } Down here is my Django STATIC_URL and STATIC_ROOT configurations STATIC_URL = '/assets/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "assets"), ) STATIC_ROOT = '/var/www/html/dev2_assets/' When i run the application with ./manage.py runserver its loads all the static files. Any help. Thanks -
Passing parameters to zeep client
I have this piece of a wsdl file: <soapenv:Header/> <soapenv:Body> <pag:creaCarrello> <GestioneCarrelliRequest> <utenteApplicativo>YZSMOPMO</utenteApplicativo> <carrelloDto> <idCarrelloSorgente>99999999999</idCarrelloSorgente> <itemCarrelloDtoList> <causale>prova</causale> <codiceEnte>CCIAA_MI</codiceEnte> <importo>2</importo> <importoImposta>1</importoImposta> <importoTotale>3</importoTotale> <importoUnitario>2</importoUnitario> <quantitaItem>1</quantitaItem> <tipoContabilizzazione>TA</tipoContabilizzazione> </itemCarrelloDtoList> </carrelloDto> </GestioneCarrelliRequest> </pag:creaCarrello> This is a SOAP service wrote in Java. I need to query this service and I'm using python Zeep library: utenteApplicativo='XXXX' idCarrelloSorgente=999999999998 itemCarrelloDtoList=('prova', 'Datatest', 2, 1, 3, 2, 1, 'TA') carrelloDto=(idCarrelloSorgente, itemCarrelloDtoList) var=(utenteApplicativo, carrelloDto) call=client.service.creaCarrello(var) but I receive the error: ValidationError at /soapclient/ Missing element utenteApplicativo (creaCarrello.GestioneCarrelliRequest) parameters are passed in a wrong manner? -
django quryset save does not work
def goBed1(key): for p in get_Day(1,key): num = p.Date dday = day.objects.get(Date=num) dday.bedTime = timeNow() dday.save() As a result of debugging, the save () up line works normally. This was the code that originally worked well. This is the day class before change. class day(models.Model): Date = models.DateField() sleepingTime = models.IntegerField(default = 0) bedTime = models.IntegerField(default = 0) condition = models.IntegerField(default = 0) def __str__(self): return str(self.Date) By the way, I changed day. class day(models.Model): Date = models.DateField() sleepingTime = models.IntegerField(default = 0) bedTime = models.IntegerField(default = 0) condition = models.IntegerField(default = 0) user_key = models.TextField(default = "0") user_name = models.TextField(default = "0") def __str__(self): return str(self.user_name+str(self.Date)) Then dday.save() does not work. Since this code works in sns called kakao talk, I do not know how to check what error is coming up. It drives me crazy. This is another part of my code. def wakeUp(key,name): for p in get_Day(1,key): num = p.bedTime yestime = num totime = int(timeNow()) yesH = int(yestime/100) toH = int(totime/100) yesM = yestime - yesH*100 toM = totime - toH*100 sleepH = toH -yesH if sleepH<0: sleepH += 24 sleepM = toM - yesM if sleepM <0: sleepM += 60 sleepH -= 1 if sleepM … -
Combined Gunicorn No module Celery error and no module name wsgi error - how to fix?
I'm working uploading my django project onto a an AWS server. I've followed these instructions (here) and have managed to get the server running. However when In try to run Gunicorn (using gunicorn milingual.wsgi -b 0.0.0.0:8000[ )I get either on of two errors depending on where in my directory I am located. If I am in the root directory, the one with my manage.py file then I get the 'No module name celery' error. If I run the command in a sub directory that has my wsgi.py file then I get the 'No module named milingual.wsgi' error. Additionally, when In run 2 other commands from the root directory (gunicorn -b 0.0.0.0:8000 wsgi:application) and (gunicorn -b 0.0.0.0:8000 milingual.wsgi:application) I get the same error. I've looked at questions here, here and here How can I fix this? The errors: (.venv) ubuntu@ip-172-31-43-50:~/milingual_api$ gunicorn -b 0.0.0.0:8000 wsgi:application [2017-11-24 14:38:18 +0000] [2886] [INFO] Starting gunicorn 19.4.5 [2017-11-24 14:38:18 +0000] [2886] [INFO] Listening at: http://0.0.0.0:8000 (2886) [2017-11-24 14:38:18 +0000] [2886] [INFO] Using worker: sync [2017-11-24 14:38:18 +0000] [2891] [INFO] Booting worker with pid: 2891 [2017-11-24 14:38:18 +0000] [2891] [ERROR] Exception in worker process: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File … -
Upload PDF to Django and convert it to image
That is basically what I want to achieve: Users uploads a file on their browser. Form data is sent to a Django or Djang-Rest API endpoint, on a Linux server. If it is an image, it will be written onto a model's ImageField directly, which will save it to Amazon S3 Bucket. If it is a PDF, it will written as a temp file. Then each page will be converted to PNG or JPG and will be written onto multiple models. From I have found, I think python library Wand is able to do something similar. But I am not entirely sure how. Does anybody have an idea that can help my situation? -
Choosing a cross-platform design pattern
I made a Python script that acts as a command-line application. It prompts users for keywords (i.e. "size", "product name") that get stored as variables in a dictionary. The variables are then passed into Selenium operations to allow users to checkout automatically from websites. My partner developed an iOS version of the script and created a Firebase database to authenticate users. We'd like the desktop version to use the same database, as users will be subscribers who've purchased a three-month subscription to our service. The desktop version should support two-factor-authentificatoin and should require a license key to work. I was planning on simply building a GUI with PyQt5, but I've been considering web frameworks like Django and Flask to both get variables via HTTP requests and develop a more modern GUI with JavaScript, Materialize, React etc. I'm unsure, however, whether either would be overkill for an application with merely three views: Login Forms Main window I've completed tutorials for both frameworks and am unsure how to move forward. On the one hand, I feel limited by Python's GUIs. On the other hand, I don't want to set myself back in development. Plan B would be to turn the script into … -
Wagtail - migrate / copy data
I have setup Wagtail on my project Dev server and some content has been added there, pages with streamfields and images. What is the best way to copy this data to the existing project on the live server? Thanks -
merge two model query by time in DRF
I'd like to combine two models in view and sort by timeline. My attempt is to have two serializer model and in views, I'd combine the serializer, but i get response has no len() in my pagination. I'm guessing it is returning nothing. The goal is to combine new post and new registered user into a timeline. So I'm not looking for a foreign key on the new post, I'm looking to combine the two models by time. serializer.py class UserSerializer(serializers.Serializer): class Meta: model = User fields = ['username','date_joined'] class PostSerializer(serializers.Serializer): class Meta: model = Post fields = '__all__' class TimelineSerializer(serializers.Serializer): user = UserSerializer(many=True) post= PostSerializer(many=True) views.py class TimelineAPIView(generics.ListAPIView): serializer_class = TimelineSerializer permission_classes = (IsAuthenticated,) queryset = Post.objects.all() pagination_class = SmallResultsSetPagination def get_queryset(self): Timeline = namedtuple('Timeline', ('user', 'post')) merged_queryset = Post.get_explore_queryset(self.request.user) #gets similar to user's post post_pks = [u.pk for u in merged_queryset] timeline = Timeline( user = User.objects.annotate(post_time=Extract('date_joined','epoch')), post= Post.objects.filter(pk__in=post_pks ) ) serializer = TimelineSerializer(timeline) return Response(serializer.data) -
Django login and register : 'AnonymousUser' object has no attribute '_meta'
I write login and register form and I use my database (NOT DJANGO's DATABASE). and this is my code: models.py : from django.db import models from django.contrib.auth.base_user import AbstractBaseUser class Student (AbstractBaseUser): username = models.CharField(max_length=250) password = models.CharField(max_length=250) first_name= models.CharField(max_length=250) last_name= models.CharField(max_length=250) gender= models.CharField(max_length=250) telNo = models.CharField(max_length=250) USERNAME_FIELD = 'username' def __str__(self): return self.username forms.py: from django import forms from .models import Student class SignUpForm(forms.ModelForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') # email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') telNo = forms.CharField(widget=forms.TextInput(attrs={'style': 'color: black;','placeholder':'تلفن همراه'}),label='تلفن همراه',error_messages = {'required': "تلفن همراه خود را وارد کنید"}) password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField() class Meta: model = Student fields = ( 'username', 'first_name', 'last_name', 'telNo', 'password', 'confirm_password' ) def clean(self): cleaned_data = super(Student, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) class UserLoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'style': 'color: black;','placeholder':'ایمیل یا شماره دانشجویی'}),label='نام کاربری',error_messages = {'required': "فیلد را پر کنید"}) password = forms.CharField(widget=forms.PasswordInput(attrs={'style': 'color: black;','placeholder':'رمز عبور'}),label='رمز عبور',error_messages = {'required': "فیلد را پر کنید"}) views.py: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.set_password(user.password) user.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user … -
Equity Stock Portfolio Management Website using Django
I am trying to built a website for stock portfolio management. In that case, I need to take input of certain fields like stock code, buy value and quantity from the user. But I want to display more fields like today's value, today's change etc etc in the portfolio. Do I need to define them in models? As i don't need user input in that but it uses the user input for doing calculations. -
DetailView can't return a list as a queryset?
I get an AttributeError: list object has no attribute filter. the same thing works with ListView. why can't I return a list as queryset in DetailView? so that I can pass in multiple models. this question: Django DetailView + show related record of another Model asks the same thing. and the solutions are those? I'm pretty new to django but this sounds stupid. can anybody tell me why it isn't? this should be a relatively common thing to do right? -
module 'enum' has no attribute 'IntFlag' while deploying django application to AWS Beanstalk
I am deploying my django application using elastic beanstalk's CLI and it is showing following errors in the logs. I have created a python 2.7 environment, and have verified by typing "python -V" into the EC2 instance and it shows correct python version (2.7) but somehow in the error logs it seems that python3.6 is being used. Please have a look at the following error Collecting enum==0.4.6 (from -r /opt/python/ondeck/app/requirements.txt (line 43)) Downloading enum-0.4.6.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/__init__.py", line 5, in <module> import distutils.core File "/opt/python/run/venv/lib64/python3.6/distutils/__init__.py", line 4, in <module> import imp File "/opt/python/run/venv/lib64/python3.6/imp.py", line 27, in <module> import tokenize File "/opt/python/run/venv/lib64/python3.6/tokenize.py", line 33, in <module> import re File "/opt/python/run/venv/lib64/python3.6/re.py", line 142, in <module> class RegexFlag(enum.IntFlag): AttributeError: module 'enum' has no attribute 'IntFlag' When I build locally, it works perfectly but it's happening only when I upload my code to elastic beanstalk using "eb deploy" command. -
can't connect between app server with SQL server
dears, I can't connect Application Server using iclock application with DB server SQL 2016, while i'm using this port 1433 it's work fine but when i change it with another port ex 2233 it's not connect with the SQL server it's shown this message: raise OperationalError(e, "Error opening connection: " + connection_string) django.db.backends.sqlserver_ado.dbapi.OperationalError: (com_error(-2147352567, 'Exception occurred.', (0, u'Microsoft OLE DB Provider for SQL Server', u'[DBNE TLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.', None, 0, -2147467259), None), 'Error opening connection: PROVIDER=SQLOLEDB;DATA SOURCE=10.1.45.51;Initial Catalog=adms_db;UID=***;PWD=***') -
Iterating over a subset of Apps in Django
As part of a Django project, my user will be able to select from a variety of options. The functionality for each option is stored in a separate app. My project structure looks something like this: MyProject/ MyProject App1 App2 Options/ Option1/ Option2/ Option3/ … … manage.py My question is: Is there a way of iterating over each app contained within the options directory. For example suppose each app contained a file called utils.py with a function called foo in each utils.py. Is there a way of doing something like this: from .. import Options survey = [ app.utils.foo() for app in Options] Failing this, is there a way to just iterate over all apps? Is there something I can do with django.apps perhaps? -
How to implement this complex query in ORM style in Django?
I have a complex query that help me create a rich data set to display in a list view. The result of the query includes fields from Event model and a field based on the aggregation in the subquery. I'd like to know how to implement this using Django ORM instead of writing raw queries all the time? Sample query below: SELECT g.event_id,event_name, gm.member_counts from care_event g inner join ( SELECT gc.event_id, COUNT(DISTINCT gc.member_id) AS member_counts FROM event_member gc INNER JOIN care_member m on gc.member_id = m.member_id and m.is_deleted = 'N' GROUP BY 1 ) gm ON g.event_id = gm.event_id WHERE org_id = %(org_id)s AND g.is_deleted = 'N' Event, Member and EventMember are models that store data. Can I have a conceptual level implemention of this query in ORM style? Thanks. -
django loop inside loop is not working print on teamplates
i am using django framework with python2.7 and in model i am receiving the following values as a query resultset { "receivable": -90786.82, "payable": 8826.72, "receivable_aging": { "age5": 235114.91999999998, "age4": 235114.91999999998, "age3": 0, "age2": 0, "age1": 0, "range": [ {"age5": "overdue in 10 days"}, {"age1": "<30"}, {"age2": "30-60"}, {"age3": "60-90"}, {"age4": ">90"} ], "overdue": 235114.91999999998 } } by the above result set i want to display in django template as below receivable_aging > range >90 is has 0 #0 is from receivable_aging.age1 & >90 is from #receivable_aging.range.age1 30-60 is has 0 #0 is from receivable_aging.age2 & 30-60 is from #receivable_aging.range.age1 I new here , i tried lot of methods but not working pls help me on this my tries are, {% for key, value in response_bills.receivable_aging.items reversed %} <div class="invoice-box-content"> <span class="invoice-box-text"> 31 - 60 Days </span> {% if key not in "age5,range,overdue" %} <span class="invoice-box-value"> <i class="fa fa-inr fa-black fa-4" aria-hidden="true"></i> {{ value }} </span> {% endif %} </div> {% endfor %} -
Javascript strings : Appending django urls
I'm trying to create a simple url builder. For example in javascript I have: var url = document.URL; If I wanted to append something to the url I could just simply type its pattern, but in Django we can use something like this: url = url + "{% url 'object_view' %}"; alert(url); The problem is where the document.URL and Django URL creates a pattern like this: http://localhost:8000//objects/view/ I've tried looking at Javascript string manipulation such as trim() and replace(), but both doesn't have the manipulation to just drop the single slash in the string from document.URL. If I replace all () it may get affected if for example my document.URL is something like: http://localhost:8000/something/something2/ Any suggestions? -
Factory Boy and related objects creation
Some beginner question about Factory Boy: Let's say you have these models related this way: class Service: restaurant = models.ForeignKey(Restaurant) hist_day_period = models.ForeignKey(DayPeriod) class DayPeriod: restaurant = models.ForeignKey(Restaurant) I want to create a Service object, using a Factory. It should create all 3 models, but use the same restaurant. Using this code: class ServiceFactory(factory.django.DjangoModelFactory): class Meta: model = Service restaurant = factory.SubFactory('restaurants.factories.RestaurantFactory') hist_day_period = factory.SubFactory( 'day_periods.factories.DayPeriodFactory', restaurant=restaurant) Factory boy will create 2 different restaurants: s1 = ServiceFactory.create() s1.restaurant == s1.hist_day_period.restaurant >>> False Any idea on how to do this? It's unclear to me if I should use RelatedFactory instead of SubFactory to accomplish this. -
Django TimeStamped mixin with different created/modified fields
Here is the classic mixin used to know when a Django object is created or modified: class TimeStampable(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True The problem (it's not really a problem for most of us I guess) is that created and modified fields are not equals, at the first creation (there is a tiny delta between them). How would you improve this mixin to solve that specific issue? I checked django-model-utils source code but found nothing. I guess we would need to override __init__ method? -
GUI for a simulator
Good day to all, I have a general question but in need of a detailed answer. Sorry, I'm kind a noob in this. I have a project which requires me to build a web GUI for a simulator. I was told preferably to code it in python. But the thing is I'm not a python coder. I asked around my friends, some recommended me Tkinter, QT, Django... So my question will be, which framework will best suit me? (in designing the interface) I'm looking for something easy to work with, like those with drag and drop features but I also need heavy documentation on code like how to make a menu bar with drop out menu, to open / save a file function etc, create a select button, zoom in/out button, refresh button, a console window, and all you can think of when using a simulator. I need the interface to function as well, not those that print statement to command prompt I need to build that interface out, any recommendation? -
Django website tracked by piwik on same webserver
I'm trying to run a django website which is handled over the mod-wsgi module by an apache2 webserver and to track this site with piwik which is "running" on the same maschine and served by the same apache2 webserver. Piwik lives under /var/www/piwik/. <VirtualHost *:80> # ServerName www.example.com ServerAdmin admin@test.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /path/to/django/static-files <Directory /path/to/django/static-files> Require all granted </Directory> <Directory /path/to/django/wsgifile> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django-cms python-home=/path/to/python/env python-path=/path/to/django-project WSGIProcessGroup django-project WSGIScriptAlias / /path/to/django/wsgifile/wsgi.py # DocumentRoot /var/www/piwik # <Directory /var/www/piwik> # Require all granted # </Directory> </VirtualHost> Later running on port 443 (SSL). But what do I need to change to access piwik? Use seperate port for it? -
Index/Stock Quote on Website-Python-Django
I am trying to create a portfolio management website. I want to add a realtime ticker for some of the indexes and stocks. I can fetch the realtime data using googlefinance or some other module. But how can I display it on my website. -
Get URL response from Python swiftclient
While putting object into OpenStack Swift by swiftclient client library, I would like to have URL adress in the response from POST/PUT request, while posting file into storage. I utilize this code to post file into storage, but this method brings any response: import swiftclient conn = swiftclient.Connection( authurl=settings.SWIFT_AUTH_URL, user=settings.SWIFT_USERNAME, key=settings.SWIFT_KEY, tenant_name=settings.SWIFT_TENANT_NAME, auth_version='2.0', os_options={settings.SWIFT_REGION_NAME} ) with open(file_path, 'rb') as file: conn.put_object(container_name, file_name, contents=file.read(), content_type=some_format) Question is, how to produce response containing URL adress of uploaded file? -
Passing a fixed query term to django-haystack
I'm looking to make a page that displays a fixed set of search results using django-haystack. I already have a page that can be used to make searches using haystack's SearchView, and want to make a second page that by default shows the results from a specific search -- in this example, searching for all documents that contain Fruit. Here's my urls.py: from haystack.views import SearchView from django.conf.urls import url import haystack from .search_Queries import custom_query from .forms import CustomSearchForm urlpatterns = [ url(r'^fruit/', SearchView(form_class=CustomSearchForm, searchqueryset=custom_query)), url(r'^$', SearchView(form_class=haystack.forms.SearchForm, searchqueryset=custom_query), ] And I am trying to make the view display the initial Fruit search term by overriding the get_queryset method in the form -- however, this doesn't seem to be the correct way to go about it forms.py class CustomSearchForm(SearchForm): def get_queryset(self): queryset = super(CustomSearchForm, self).get_queryset() queryset = queryset.auto_query('Fruit') return queryset How can I display a set of search results for a specific term as the default in a view using django-haystack? I want to make a separate view so that my ^fruit/ URL shows the Fruit search results directly, rather than redirecting to /q=Fruit.