Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku and Django, database resets when heroku restarts the site
After 30mins of not being used Heroju resets my django site, however when the site is reset the database/models controlled and changed in the admin page are reset back to when the site was first uploaded. How do i stop this and make changes made in admin mode permanently to the site? thank you. -
employee multiple role relationship
I have tables of Employee and Roles. In Roles model I'm storing manager details, there is manager hierarchy like Manager, AGM, DGM, and MD, I have to design my schema such a way that each employee has one manager and 5 managers will be reporting to one AGM and 5 AGM to one DGM. How to design this schema? Any help would be appreciable. Thanx in advance. -
Django RF: AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`
In my models there is a Meeting model with a GenericForeignKey which can be either DailyMeeting or WeeklyMeeting like: class Meeting(models.Model): # More fields above content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() recurring_meeting = GenericForeignKey('content_type', 'object_id') class DailyMeeting(models.Model): meeting = GenericRelation(Meeting) # more fields class WeeklyMeeting(models.Model): meeting = GenericRelation(Meeting) # more fields As described in the documentation, I created a custom field in my serializers.py: class RecurringMeetingRelatedField(serializers.RelatedField): def to_representation(self, value): if isinstance(value, DailyMeeting): serializer = DailyMeetingSerializer(value) elif isinstance(value, WeeklyMeeting): serializer = WeeklyMeetingSerializer(value) else: raise Exception('Unexpected type of tagged object') return serializer.data class MeetingSerializer(serializers.ModelSerializer): recurring_meeting = RecurringMeetingRelatedField() class Meta: model = Meeting fields = '__all__' In the views.py I am overriding the create method and I am passing a DailyMeeting object. def create(self, request, *args, **kwargs): data = request.data d = DailyMeeting.objects.create(...) data['recurring_meeting'] = d serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) But the problem is that I am getting the following error: AssertionError: Relational field must provide a queryset argument, override get_queryset, or set read_only=True. Why does the Relational field has to be read_only? If I set it as read_only then it is not passed in the data in the serializer. How can I pass the DailyMeeting object in the serializer and print … -
django email sending after template js if function
I tried to send a email using django after the javascript if statement came true in template. when I refresh the web page it need to be send a email only that if statement is true. How I can achieve this? please help -
Add uuid field in django Existing User model?
I am using Django Rest framework for my application. I almost implemented registration and login process using django User Model without customizing it now i want to add a uuid field in it. Is there any way we can just add uuid field and other process remains same? -
Django: How to use apps installed with pip
I want to make use of Django's modularity and integrate some external apps that I installed using pip. However, I am encountering difficulties in understanding how can I integrate and use or extend their urls, views, models. There isn't much on this subject, I can't figure why. Let's take the example of changuito-cart: Do i create a folder named "changuito" in root and create urls/views in here, or should I just create a new app named like it? In settings.py I added "changuito" to my installed apps list and I got "no module named 'changuito'" error. How do I add it correctly? What are the basic steps required to integrate it? -
Multiple table filtering in Django DRF serializer or view
What I am trying to do is retrieve records that are relevant to the current user. I am using DRF JWT so the user_id is being stored in sessionStorage along with the JWT token. As I understand it, because JWT is being used, session authentication is not, so such things like request.user do not work. At least I could never get it working and was just told to store the user_id in sessionStorage with the JWT token. As such, if I want to retrieve records that are relevant to the current user, sessionStorage.getItem('user_id') needs to be passed to the API with POST. GET won't work since 1) request.user doesn't work and 2) can't send sessionStorage.getItem('user_id'). So here are the models I am working with that I need to filter on with some example data: -- Products table prod_id | prod_name | active ---------------------------- 3 | Widget1 | 0 10 | Widget2 | 1 11 | Widget3 | 1 -- Users table user_id | username ------------------ 10011 | joesmith -- User_to_Products table user_id | prod_id ----------------- 10011 | 3 10011 | 11 So what should be happening is the React FE sends the sessionStorage.getItem('user_id') to the DRF BE via POST, the … -
Django query - count up to 10 votes from one IP
let's say I have a simple voting form with different answers. the people can vote multiple times from one IP. I can easily find how many votes a given answer has got - a.vote_set.all().count() (no limit of votes from 1 IP) I can also find out how many votes there were, given the limit 1 vote from 1 IP - a.vote_set.all().values('ip').distinct().count() (limit of votes from one IP =1) How to get the sum of votes for a given answer provided that I want count up to 10 votes from 1 IP (limit=10)? -
How to store timezones efficiently in Django model?
I have a timezone field in my Django model : import pytz ALL_TIMEZONES = sorted((item, item) for item in pytz.all_timezones) ... class Snippet(models.Model): tz = models.CharField(choices=ALL_TIMEZONES,max_length=32) I'm a little bit concerned about the space occupied by the tz field because I expect to have many many snippets in the future. Longest timezone is 32 characters long but there are only 593 timezones so 2 bytes would be sufficient to store the timezone. Is there a better way to store/define my tz field? Of course I could use my own coding scheme but before I want to make sure there is no other solution. -
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.