Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django update object - validator
I have an AJAX request that updates a model object. It sends the new value in a dict, like: new_value = {'attribute': 'value'} I'm using the method update() to save the new value: .update(**new_value) It saves the object fine, but it's skipping my MinValueValidator: field = models.DecimalField(... validators=[MinValueValidator(Decimal('0.01'))]) How could I make this validator work with update()? It works good from the admin. -
Annotate query row with latest date and corresponding subsriber Django
I have a following models: class Post(Model): word = TextField() subscribers = ManyToManyField(User, related_name='subscribed', through='Subscription') class Subscription(Model): post = ForeignKey(Post) subscriber = ForeignKey(User) date_subscribed = DateTimeField(default=timezone.now) class Meta: ordering = ('-date_subscribed', ) unique_together = (('post', 'subscriber')) I want to annotate all posts with latest date of subscriptions and corresponding subscriber. How to do it? Now I have the following query (thanks to @AKS Django manytomany query weird behavior): posts = Post.objects.annotate( s_count=Count('subscribers'), s_date_max=Max('subscription__date_subscribed') ).order_by('-s_count', '-s_date_max') -
Using Django and PHP in Nginx
I'm using Django in a Vhost and PHP in another, now I want to make one file with the two things, a part for Django and another for PHP. I've read this question but it's not helping me. How to run django and wordpress on NGINX server using same domain? this one didn't help either How can I configure nginx to serve a Django app and a Wordpress site? This is part of what I have in the PHP config: root /var/www/agendav/web/public; # Add index.php to the list if you are using PHP index index.php; location ~ ^(.+\.php)(.*)$ { try_files $fastcgi_script_name =404; include /etc/nginx/fastcgi_params; fastcgi_split_path_info ^(.+\.php)(.*)$; fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; And I'm trying to add this to the other conf file (that's already working) location ~ /cal/.*\.php$ { root /var/www/agendav/web/public; index index.php; try_files $uri $uri/ /index.php/login =404; fastcgi_index index.php; include fastcgi_params; fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; } for what I've read, that should do, but all I've getting is a 404 error, or a blank page and no readings in the nginx log or even in the agendav(the app in PHP) ones. What am I doing wrong? -
How to add Tuples in a particular plase in a List of Tuples?
Hello everyone I'm pretty new in Python and Django so I'll appreciate any help. What I have currently is: configs = Configuration.objects.all() fields = [] for config in configs: choice = ( config.ObjectType.ObjectTypeDSC + '_' + config.MetadataFieldNM, config.ObjectType.ObjectTypeDSC + ': ' + config.WebFieldNM ) I use this list of Tuples to add em as ChoiceField choices. So the result is something like: <select> <option value="Clarity Report_LastRunDTS">Clarity Report: Last Run</option> <option value="Clarity Report_OwnerNM">Clarity Report: Owner</option> <option value="Clarity Report_ObjectSQL">Clarity Report: Report SQL</option> <option value="Dashboard_SourceSystemNM">Dashboard: Source System</option> <option value="Data Mart_CreateDTS">Data Mart: Created</option> <option value="Data Mart_LastLoadDTS">Data Mart: Last Refresh</option> <option value="Helpful SQL_OwnerNM">Helpful SQL: Owner</option> </select> In ObjectTypes table I have additional three columns - Column1, Column2, Column3 I need to select all Object Types (object_types = ObjectType.objects.all()), iterate trough them and add one more option for each column. For example: object_type_choice = ( object_type.ObjectTypeDSC + '_' + config.Column1, object_type.ObjectTypeDSC + ': ' + config.Column1 ) Also I need these new 3 options to be added after the old options of the same type. The result should be: <select> <option value="Clarity Report_LastRunDTS">Clarity Report: Last Run</option> <option value="Clarity Report_OwnerNM">Clarity Report: Owner</option> <option value="Clarity Report_ObjectSQL">Clarity Report: Report SQL</option> <option value="Clarity Report_First Column">Clarity Report: First Column</option> <option value="Clarity … -
Django not updating Database
I am working on a Django 1.10 project with python 3. This is my models.py: # /Multiple choices/ SEX_CHOICES = (('M', 'Male'), ('F', 'Female') ) ZONE_CHOICES = (('D', 'Départementale'), ('N', 'Nationale') ) # /Extension of User model/ class Profile(models.Model): user = models.OneToOneField(User, related_name='profile') sex = models.CharField(max_length=1, choices=SEX_CHOICES, default='M') departementNumber = models.PositiveSmallIntegerField(default=88, validators=[MaxValueValidator(101)]) departement = models.CharField(max_length=200) zone = models.CharField(max_length=1, choices=ZONE_CHOICES, default='D') receivedApprove = models.PositiveSmallIntegerField(default=0) receivedDescription = models.PositiveSmallIntegerField(default=0) receivedDesapprove = models.PositiveSmallIntegerField(default=0) givenApprove = models.PositiveSmallIntegerField(default=0) givenDescription = models.PositiveSmallIntegerField(default=0) givenDisapprove = models.PositiveSmallIntegerField(default=0) def __str__(self): return self.user.username What I am trying to do is to take some users information and complete their profile. Here is what i did in my views.py : user_id = request.user firstname = form.cleaned_data['firstname'] lastname = form.cleaned_data['lastname'] email = form.cleaned_data['email'] sex = form2.cleaned_data['sex'] departementNumber = form2.cleaned_data['departementNumber'] zone = form2.cleaned_data['zone'] At this stage, everything is working fine. The problem start when I try to update my model. User object is updating correctly : upd = User.objects.filter(id=user_id.id).update(first_name=firstname, last_name=lastname, email=email) But Profile is not updating : upd2 = Profile.objects.filter(id=user_id.id).update(sex=sex, departementNumber=departementNumber, departement=depName, zone=zone) And I have not a single warning or error message. -
NewConnectionError using django-haystack with Amazon ElasticSearch as backend
I'm trying to use Amazon ElasticSearch as the backend for Haystack on Django 1.10. The error I get is urllib3.exceptions.NewConnectionError: : Failed to establish a new connection: [Errno 111] Connection refused From my django setttings file: from requests_aws4auth import AWS4Auth from elasticsearch import Elasticsearch, RequestsHttpConnection import elasticsearch AWS_ACCESS_KEY = "<secret>" AWS_SECRET_KEY = "<secret>" awsauth = AWS4Auth(AWS_ACCESS_KEY, AWS_SECRET_KEY, 'eu-central-1', 'es') HAYSTACK_CONNECTIONS = { 'local': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', }, 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': ['http://<endpoint>'], 'INDEX_NAME': 'haystack', 'KWARGS': { 'port':443, 'http_auth': awsauth, 'use_ssl': True, 'verify_certs': True, 'connection_class': elasticsearch.RequestsHttpConnection, } } } I've tried simulating the requests with this script: import requests from requests_aws4auth import AWS4Auth from elasticsearch import Elasticsearch, RequestsHttpConnection import elasticsearch AWS_ACCESS_KEY = "<secret>" AWS_SECRET_KEY = "<secret>" HOST = "https://<endpoint>" awsauth = AWS4Auth(AWS_ACCESS_KEY, AWS_SECRET_KEY, 'eu-central-1', 'es') response = requests.get(HOST, auth=awsauth) print(response.text) and it works, as the response is: { "status" : 200, "name" : "Abominatrix", "cluster_name" : "<name>", "version" : { "number" : "1.5.2", "build_hash" : "cd916cf85f094f387a3d2ebde149bea2980df526", "build_timestamp" : "2016-11-14T16:10:00Z", "build_snapshot" : false, "lucene_version" : "4.10.4" }, "tagline" : "You Know, for Search" } What's going wrong then? -
Django Rest Framework - How to use update_or_create
I am using Django Rest Framework. I want to create record if it doesn't exists, or update if it exists. What I did: class MyModelList(generics.ListCreateAPIView): queryset = MyModel.objects.all() serializer_class = MyModeSerializer permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): my_model, created = MyModel.objects.update_or_create(user_id=self.request.data['user_id'], defaults={ 'reg_id': self.request.data['reg_id'] }) The record is created or updated. But I am getting an error 'OrderedDict' object has no attribute 'pk' -
Creating a file and returning it to Django in a view
I am trying to build a KML file on the fly for a user to download. I am playing with a KML library in python to produce and save KMLs but I want to return the file as ad ownload. Essentially if a user in my app clicks a link bam the KML is generated and downloaded by the user clicking the link. The code I have isn't working and I am guessing my response is not set up correctly: in views.py: def buildKML(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/kml') response['Content-Disposition'] = 'attachment; filename="botanicalgarden.kml"' #just testing the simplekml library for now kml = simplekml.Kml() kml.newpoint(name="Kirstenbosch", coords=[(18.432314,-33.988862)]) # lon, lat, optional height kml.save('botanicalgarden.kml') return response The error I get running this method when I click the link or goto the link: No results - Empty KML file I assume it is because the filename= and the final that is saved are not one in the same. -
When we use Django session framework, what data is stored on the server and what on client?
what data is stored on the client (browser) and on the server when we are using Django's session framework. -
Django pymssql migration
I have to use a MSSQL Server Database with a project made in Django, i use the django-pymssql dependency and all works fine at first. When I run the initial migrations it throws me an error: django.db.utils.OperationalError: (5074, "The object 'UQ__auth_use__F3DBC5726EFED139' is dependent on column 'username'.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\nDB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n") This just happend just after django migrations tries this: Applying auth.0008_alter_user_username_max_length... So, i'm guessing that Django is trying to make a move on a field, but MSSQL throws the error at the time it gets altered. I'm working on Ubuntu 16.10, so if anyone have a clue of how to avoid this error would be lot of help. -
new created virtualenv not being activated but old
I'm working with a django project with virtualenv. I needed to create a new virtualenv for another project. and I've did that. but while I was trying to activate new virtualenv, it show that my old virtualenv is being activate. My request to you- why this? and how to solve this problem? -
How to get the Year value from models.DateField...?
I want to calculate age. I tried below code... DOB = models.DateField() Age = models.IntegerField(max_length= 2, default= date.today().year - DOB.year) I got Error AttributeError: 'DateField' object has no attribute 'year' How can I get the Year value from DateField.. -
Custom filename in django image_field
i need to define an custom filename for images uploaded, i have this models: class Personas(model.Models): ... some fields here ... documento = models.CharField(max_length=10) class Identificacion(model.Models): ...some fields here... persona = models.ForeignKey('Personas') fotos = models.ManyToManyField('FotoPersona',related_name='foto_persona',blank=True,null=True) class FotoPersona(model.Models): persona = models.ForeignKey('Personas') foto = models.ImageField(upload_to= CUSTOM_PATH) CUSTOM_PATH must be in the next format: app_name/persona.documento/file_name where file_name can be: perfil frente cuerpo_entero how can i make that? -
Django/ Python set min/ max date values on DateTimeField
I have a Django form, with a date field displayed on it, which has a data type of mDateField (a custom class that extends forms.DateField). It is defined in forms.py with: class mDateField(forms.DateField): def __init__(self, *args, **kwargs): kwargs.setdefault('input_formats', DATE_INPUT_FORMATS) super(mDateField, self).__init__(*args, **kwargs) I now want to set a 'minimum' & 'maximum' possible value for that date field (i.e. a date a certain length of time either in the past or in the future relevant to today's date that this value can be set to). I came across this answer on SO: jquery datetime picker set minDate dynamic and tried following what it says, by writing the line: presentation_date = mDateTimeField(required=False, widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M', attrs=({'class':'datetimepicker presentation_date', 'name':'presentation_date2'}))) presentation_date.options.maxDate = $( ".selector" ).datepicker( "option", "maxDate", new Date(2014, 1 - 1, 1)); but when I do, I get a syntax error in the console, which points to the $, and says: SyntaxError: invalid syntax What is wrong with what I'm doing here? How can I specify what the earliest/ latest date to be shown in the datepicker should be? -
Move customized django-allauth templates to directory other than 'account'
I set up django-allauth correctly following the project's documentation. I wanted to override the look and feel of the django-allauth templates so I went to the project github and downloaded the django-allauth templates folder into my accountsapp/templates directory. My problem is that django-allauth will only look for its templates in the templates/account folder. I want to put my templates in the templates/allauth/account folder to help keep MY template files separate from django-allauth's template files. When I do this, django-allauth is unable to find the templates that I customized. Here is my project structure: projectfolder/ accountsapp/ templates/ projectsettings/ settings.py manage.py What I've tried: Setting my TEMPLATES 'DIRS' to this 'DIRS': [ os.path.join(os.path.dirname(BASE_DIR), 'accounts', 'templates', 'allauth'), ], This works, but I'm not sure that this is the best practice/solution to my problem. -
Custom allautj template with Django 1.8
I read many different setup for getting all auth working with django in general, and 1.8 specifically but none is working. here is my current setup: TEMPLATES = [ { 'BACKEND' : 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join( BASE_DIR, 'templates' ), os.path.join( BASE_DIR, 'templates', 'allauth' ) ], 'APP_DIRS': True, 'OPTIONS' : { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] With all Allauth accounts templates in basedir/templates/allauth/accounts Altough all allauth template pickup the site's base template, any modification to the template in tis directory are royally ignored. if you have this working with django 1.8 please describe your setup. -
Django Manytomany admin interface create new entrys without looping
I am using Djangos admin interface to build a database for vulnerabilites and the according CVEs. A vulnerability might consist of multiple CVEs, CVEs can occur in multiple vulnerabilitys. For doing so, I have two models that are connected via a Many-to-Many relationship: class Schwachstelle(models.Model): titel = models.CharField("Titel", max_length = 200, unique=True) class CVE(models.Model): cveNummer = models.CharField("CVE Nummer", max_length = 30, unique=True) schwachsstelle = models.ManyToManyField("Schwachstelle", related_name='CVE', default = "", blank = True) If I now create a new vulnerability, via the admin interface of djano I can also create new CVEs. While creating these new CVEs I can again create new vulnerabilies and so on. I would like to prevent this kind of "looping". It shall be possible to create new CVEs while creating a vulnerability which then again should NOT be able to create new vulnerabilies. How can I realize this? My admin classes can be seen below. The code examples have been reduced by not important lines of code. Screenshots for the current output are also attached. class CVEInline(admin.TabularInline): model = CVE.schwachsstelle.through extra = 0 class CVEAdmin(ImportExportActionModelAdmin): list_display = ("cveNummer") class SchwachstelleAdmin(ImportExportActionModelAdmin): inlines = [CVEInline] list_display = ("titel") admin.site.register(CVE, CVEAdmin) admin.site.register(Schwachstelle, SchwachstelleAdmin) Screenshot of the current lopp -
Django permissions not updating
I have setup permissions in my model class as follows: class MeetingHistory(models.Model): ..... class Meta: permissions = ( ("add_meeting_details","Can add meeting details"), ("change_meeting_details","Can change meeting details"), ) The change_meeting_details is a new permission I added however the django admin interface is not diplaying the new permission. I tried the following so far(based on other similar questions): - Run makemigrations app_name then ran migrate - refreshed the browser page and deleted all cache the issue still seems to persist. Any suggestions? -
How to create download file link in django template?
I'm currently developing a django app in localhost for school where the user can upload a file through admin site and to serve the download link through template, but i don't know why isn't working. File: models.py class Document(models.Model): checklist = models.FileField( upload_to='files/', blank=True, null=True, verbose_name=ugettext_lazy('Filename'), ) File: view.py def documents(request): obj = Document.objects.all() assert isinstance(request, HttpRequest) return render( request, 'app/documents.html', { 'obj':obj, } ) File: url.py url(r'^documents', app.views.documents, name='documents'), File: settings.py MEDIA_URL = '/uploads/' MEDIA_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['uploads'])) Template: documents.html {% for u in obj %} ... {{ u.checklist }} ... {% endfor %} -
Django Changing the language in Template
I'm on a DetailView page I want to change the language to (French/English). But I'm getting a 404. Let's say I'm reaching for /emplois/32 when I switch language I got a 404. I don't know is it because that switching language seems to do a redirect without providing a pk key logs [14/Dec/2016 09:00:39] "GET /emplois/34/ HTTP/1.1" 200 27032 [14/Dec/2016 09:00:52] "GET /emplois/searchJobs?csrfmiddlewaretoken=elxs(private)&utf8=%E2%9C%93&searchKey= HTTP/1.1" 301 0 [14/Dec/2016 09:00:52] "POST /i18n/setlang/ HTTP/1.1" 302 0 [14/Dec/2016 09:00:52] "GET /emplois/34/ HTTP/1.1" 404 1755 views.py #http://localhost:8001/emplois/<pk> class DetailView(generic.DetailView): """ Return the detail content of a Job posting """ model = Job paginate_by = 10 template_name = 'emplois/details.html' context_object_name='job' def get_queryset(self, **kwargs): #import ipdb; ipdb.set_trace() pk = int(self.kwargs.get('pk')) obj = Job.objects.get(pk=pk) # i.e obj.JOBREF = '2016-EX-EN-51534056' # other language = '2016-EX-FR-51534056' #Get the Object whith the desired language obj = Job.objects.filter( JOBREF__contains=obj.JOBREF.split('-')[-1], language=(self.request.LANGUAGE_CODE).upper() ) return obj ulrs.py url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), http://ottawacitycarreers.ca -
Create S3 Buckets from Django
Is it possible to create an AWS S3 bucket remotely from Django? IE: If a new user wants to upload something, it is placed in a newly generated bucket where they can continue to upload to that specific bucket. I am currently having users upload to a generated folder in a single bucket: def get_upload_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.id, filename) Is there a way to generate a bucket from a Django app? Thanks for reading! -
Python/ Django- forms.DateTimeField is restricting available values
I have a Python/ Django project, and on one of the forms, I am giving the user a 'date/time' field on which to select a date & time for a meeting. The field definition in the form is written (in forms.py) with: class presentationForm(ValidatedForm): ... presentation_date = mDateTimeField(required=False, widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M', attrs=({'class':'datetimepicker presentation_date', 'name':'presentation_date2'}))) ... def __init__(self, *args, **kwargs): ... budget = self.instance if hasattr(budget, 'id'): ... if budget.presentation_date: pres_meeting = budget.meeting or Meeting.objects.create(project=budget.project, purpost='7') ... if not budget.meeting: budget.meeting = pres_meeting budget.save() if not budget.meeting or not pres_meeting.date: pres_meeting.date = budget.presentation_date pres_meeting.save() else: self.presenters = [] super(BudgetPresentationForm, self).__init__(*args, **kwargs) self.fields['presentation_date'].widget.attrs.update({'data-meeting-id': getattr(self,'pres_meeting_id', ''), 'data-meeting-creator': getattr(self,'pres_meeting_creator', '')}) BudgetPresentationFormset = inlineformset_factory(Project, Budget, form= BudgetPresentationForm, max_num=30, extra=1, can_delete=False) The problem that I'm having with the 'date/time' field on the form, is that although the user can scroll through the calendar that is displayed as a drop down when they click in the field (they can scroll as far back/ forward as they like), only the dates between 01/01/2015- 01/01/2017 are available for selection- all of the other dates before 01/01/2015, or after 01/01/2017 are 'greyed out' and it is not possible to select them. Obviously, as it's now approaching the 01/01/2017, users need to … -
Django edit form not showing the previosly entered data
views.py @login_required def profile_edit(request): profile, created = ProfileGroom.objects.get_or_create(user=request.user) form = ProfileForm(request.POST or None, request.FILES or None, instance=profile) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('profiles:profile', username=request.user.username) context = { "title": 'Edit Profile', "form": form, } return render(request, 'profiles/profile_form.html', context) profile_form.html <form method='POST' action='{% url "profiles:profile_update" %}' enctype='multipart/form-data' role="form">{% csrf_token %} <div id="div_id_first_name" class="form-group"> <label for="id_first_name" class="control-label "> First name </label> <div class="controls "> <input class="textinput textInput form-control" id="id_first_name" maxlength="80" name="first_name" type="text" /> </div> </div> <div id="div_id_last_name" class="form-group"> <label for="id_last_name" class="control-label "> Last name </label> <div class="controls "> <input class="textinput textInput form-control" id="id_last_name" maxlength="80" name="last_name" type="text" /> </div> </div> <div id="div_id_age" class="form-group"> <label for="id_age" class="control-label "> Age </label> <div class="controls "> <input class="numberinput form-control" id="id_age" name="age" type="number" /> <input type='submit' class='btn btn-success' value='Add/Edit Profile' /> </form> Form is saving data and working but when open for editing the data, it doesn't retain previously entered data. Any body can help? Thank you. -
'Member' object has no attribute 'all'
My models are defined as: class MembershipHistory(models.Model): mem_name = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='mem_number') project_number = models.IntegerField() project_name = models.CharField(max_length=200) evaluator_remark = models.TextField(null=True, blank=True) And this is my other model from which I make the ForeignKey class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) membership_number = models.CharField(max_length=10) I defined my form as class MembershipHistoryForm(forms.Form): def __init__(self,*args, **kwargs): self.user = kwargs.pop('user') super(MembershipHistoryForm, self).__init__(*args, **kwargs) self.fields['mem_name'].queryset = Member.objects.get(user=self.user) #mem_name = forms.ModelChoiceField(empty_label="NAME") class Meta: model = MembershipHistory fields = '__all__' widgets = { 'project_number':forms.TextInput(attrs={'placeholder':'Project Number'}), 'project_name':forms.TextInput(attrs={'placeholder':'Project Name'}), 'evaluator_remark':forms.Textarea(attrs={'placeholder':'Evaluator Remark'}), } Now, whenever I instantiate the form, I am not getting the following error Django Version: 1.10.4 Exception Type: AttributeError Exception Value: 'Member' object has no attribute 'all' any ideas as to where is the error? -
Django module is not getting identified in basic view.py code
I am new to Python and Django. I have installed virtual environment , activated it in Pycharm. Installed Django and ran the server. I am able to open page http://127.0.0.1:8000/ But when I try to write "from django.http import HttpResponse" in view.py it gives an error as "No module named Django" Tried reinstallation of Django, readded in environment variables but it doesnt work at all. Do I need to edit any settings or any issue with the installation?