Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update nested field
I can't update my object within nested object field. In here I can't update name from Movie model. Here is my model.py: class Movie(models.Model): name = models.CharField(max_length=800, unique=True) imdb_rating = models.IntegerField(null=True) movie_choice = ( ('Act', 'Action'), ........... ) movie_type = models.CharField(max_length=3, choices=movie_choice) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Hiren(models.Model): movie = models.ForeignKey(Movie) watched_full = models.BooleanField(default=True) rating = models.IntegerField() source = models.CharField(max_length=500, null=True) watched_at = models.DateField() quality_choice = ( .................. ) video_quality = models.CharField(max_length=3, choices=quality_choice) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) and serializer.py class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = '__all__' class HirenSerializer(serializers.ModelSerializer): movie = MovieSerializer() class Meta: model = Hiren fields = ('movie', 'id', 'watched_full', 'rating', 'source', 'video_quality', 'watched_at') def update(self, instance, validated_data): instance.movie.name = validated_data.get('movie.name', instance.movie.name) instance.watched_full = validated_data.get('watched_full', instance.watched_full) instance.rating = validated_data.get('rating', instance.rating) instance.source = validated_data.get('source', instance.source) instance.video_quality = validated_data.get('video_quality', instance.video_quality) instance.watched_at = validated_data.get('watched_at', instance.watched_at) instance.save() return instance -
Python-Django-WSGI-Apache on windows - “ImportError: No module named site”
I'm trying to connect django with apache on windows server with the wsgi mod. when I'm running httpd.exe , it shutdown immediately. in the error.log I got this : [Thu Nov 17 00:44:19.918823 2016] [wsgi:warn] [pid 520:tid 452] mod_wsgi: Compiled for Python/2.7.9+. [Thu Nov 17 00:44:19.918823 2016] [wsgi:warn] [pid 520:tid 452] mod_wsgi: Runtime using Python/2.7.11. [Thu Nov 17 00:44:19.918823 2016] [mpm_winnt:notice] [pid 520:tid 452] AH00455: Apache/2.4.23 (Win64) mod_wsgi/4.4.12 Python/2.7.11 configured -- resuming normal operations [Thu Nov 17 00:44:19.918823 2016] [mpm_winnt:notice] [pid 520:tid 452] AH00456: Apache Lounge VC10 Server built: Jul 9 2016 11:59:00 [Thu Nov 17 00:44:19.918823 2016] [core:notice] [pid 520:tid 452] AH00094: Command line: 'httpd -d C:/Apache24' [Thu Nov 17 00:44:19.918823 2016] [core:debug] [pid 520:tid 452] log.c(1543): AH02639: Using SO_REUSEPORT: no (0) [Thu Nov 17 00:44:19.918823 2016] [mpm_winnt:notice] [pid 520:tid 452] AH00418: Parent: Created child process 2308 [Thu Nov 17 00:44:19.918823 2016] [mpm_winnt:debug] [pid 520:tid 452] mpm_winnt.c(429): AH00402: Parent: Sent the scoreboard to the child [Thu Nov 17 00:44:20.043916 2016] [wsgi:warn] [pid 2308:tid 448] mod_wsgi: Compiled for Python/2.7.9+. [Thu Nov 17 00:44:20.043916 2016] [wsgi:warn] [pid 2308:tid 448] mod_wsgi: Runtime using Python/2.7.11. [Thu Nov 17 00:44:20.043916 2016] [mpm_winnt:debug] [pid 2308:tid 448] mpm_winnt.c(1718): AH00453: Child process is running [Thu Nov 17 … -
How to send excel as email attachment using openpyxl without saving [On The Fly]
I have been trying to send excel as email attachment using openpyxl without saving [On The Fly] in Django -
CSRF cookie not set error
I have developed a project on django in which AJAX post request is sent to server. I have used csrf token in ajax and my project runs just fine. the problem comes when I copy my project to another machine and run it there. following error arises: Forbidden (CSRF cookie not set.) Both machines run just fine and have almost same configurations for django. Does anyone have any idea this problem arose?? Following is my ajax : var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); var $chatlog = $('.js-chat-log'); var $input = $('.js-text'); var $sayButton = $('.js-say'); function createRow(text) { var $row = $('<li class="list-group-item"></li>'); $row.text(text); $chatlog.append($row); } function submitInput() { var inputData = { 'text': $input.val() } // Display the user's input on the web page createRow(inputData.text); var $submit = $.ajax({ type: 'POST', url: chatterbotUrl, data: JSON.stringify(inputData), contentType: 'application/json' }); $submit.done(function(statement) { createRow(statement.text); // Clear the input field $input.val(''); }); $submit.fail(function() { // TODO: Handle errors }); } $sayButton.click(function() { submitInput(); }); $input.keydown(function(event) { // Submit the input when the enter button is … -
MultipleObjectsReturned at ... get() returned more than one Person -- it returned 2
I am using these model: class Person(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) name_in_bangla = models.CharField(max_length=100) nick_name = models.CharField(max_length=30) birth_date = models.DateField() user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='member_persons') class Meta: ordering = ['name'] unique_together = ['name', 'birth_date'] my views: class PersonCreate(SuccessMessageMixin,CreateView): model = Person form_class = MemberForm success_message = "%(name)s was added as %(category)s successfully." def get_form(self, form_class=None): form = super().get_form(form_class) form.request = self.request return form my views: class MemberForm(ModelForm): class Meta: model = Person exclude =('user',) def clean(self): user = get_user(self.request) name = self.cleaned_data.get('name') birth_date = self.cleaned_data.get('birth_date') if self.instance.id: if Person.objects.filter(user=user).exclude(id=self.instance.id).exists(): self.add_error('name', "You already submitted data") elif Person.objects.filter(name=name, birth_date=birth_date).exclude(id=self.instance.id).exists(): self.add_error('name', "Person with this Name and Birth date already exists.") else: if Person.objects.filter(user=user).exists(): self.add_error('name', "You already submitted data") elif Person.objects.filter(name=name, birth_date=birth_date).exists(): self.add_error('name', "Person with this Name and Birth date already exists.") return self.cleaned_data def save(self, commit=True): person = super().save(commit=False) if not person.pk: person.user = get_user(self.request) if commit: person.save() self.save_m2m() return person It works fine for different persons. But when I try to use same name for person but different birth date it gives MultipleObjectReturn with 'get() returned more than one Person -- it returned 2!' But I used unique_together = ['name', 'birth_date'] constraints as well as I use clean method to … -
Updating a model instance via a ModelForm: 'unicode' object has no attribute '_meta'
Disclaimer: I have read this and a few other related questions, but either I have not understood the answers or the problems discussed there are actually different. In my app the user can view an instance of a model Kurs or edit it -- I have two separate views for the two actions. The details of the model Kurs are as follows: class Kurs(models.Model): prowadzacy = models.ForeignKey(User) nazwa = models.CharField(max_length=200) [skipping some fields...] def __unicode__(self): return self.nazwa class Meta: verbose_name_plural = "Kursy" So as you can see it has a unicode method and a Meta class. The ModelForm I'm using is this simple one: class KursForm(ModelForm): class Meta: model = Kurs fields = "__all__" The relevant view is as follows (I don't want to use class-based views now): def editcourse(request, pk): kurs_id = pk if request.method=='POST': form = KursForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/polls/usersite') else: form = KursForm(instance=pk) return render(request, 'polls/editcourse.html', {"form" : form}) My urlpatterns contain url(r'^editcourse/(?P<pk>[0-9]+)/$', views.editcourse, name='editcourse') and I'm calling the view from a page which contains the link <a href="{% url 'polls:editcourse' kur.id %}">EDIT THIS COURSE</a> where "kur" is a Kurs. My editcourse.html contains the following: <form action="" method="post"> {% csrf_token %} {{ form }} <input … -
Django Int vs String for 'type' field
If I have a django model that can have many types (assume they will rarely change, but new ones may perhaps be added), is it better to do it with an int? from enum import Enum class Places(Enum): gym = 0 coffee_shop = 1 home = 2 garage = 3 office = 4 study = 5 shed = 6 Or is it better to do it as strings? GYM = 'gym' COFFEE_SHOP = 'coffee_shop' HOME = 'home' GARAGE = 'garage' OFFICE = 'office' STUDY = 'study' SHED = 'shed' I like strings because they're human readable (and the documentation seems to use strings like FR, JR, SR, etc) but I often see people using ints to do this. Could someone explain why? -
django 1.10 postgres full text search is not working
I am trying to integrate full text search for django 1.10 with postgres database. I am following tutorial from https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/search/ class Question(models.Model): text = models.TextField(max_length=500) ans = models.TextField(max_length=1500, blank=True) I have several questions in the database which has the text 'for' in its text field for example: one question is: text: what is best for me? ans: this is best for you. I am trying to make a query like q = Question.objects.filter(text__search='for') But this query is not returning any result. can anyone suggest me why? -
Passing 2 arguments(album.id & song.id) from a form to a url(regex) and accessing it in Generic DeleteView in Django
I'm new to Django. I want to know how to pass both the album.id and song.id to the url and use it in the view(SongDelete). I'm using generic view DeleteView. I need the album.id so that I can use it in calling the url('music:detail') as my success_url. I can only pass 1 argument(song.id) and call url 'music:index' without having an error. Please help. Thanks. detail.html <form action="{% url 'music:song-delete' song.id %}" method="post"> {% csrf_token %} <input type="hidden" name="song_id" value="{{ song.id }}" /> <button type="submit" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form><br> music/urls.py url(r'^song/(?P<pk>[0-9]+)/delete/$', views.SongDelete.as_view(), name='song-delete'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^$', views.IndexView.as_view(), name='index'), view.py class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' # object_list is the default def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/detail.html' class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('music:detail') class SongDelete(DeleteView): model = Song success_url = reverse_lazy('music:index') models.py class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) song_title = models.CharField(max_length=250) audio_file = models.FileField(default='') is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('music:detail', kwargs={'pk': self.album.pk}) def __str__(self): return self.song_title -
Using django-registration package (hmac method), how to assign a user to a specific user model?
I want to apologize in advance for not being clear enough, I am in the process of learning Django. My project utilizes django-registration package, hmac method. It has different types of Users, like: Teachers and Students. Each of these types has its own model, like: class Student(models.Model): user = models.ForeignKey(User, related_name="courses") The question I have is how to assign a user to the Student model when the user hits activation link that was sent to him by django-registration? Should I override "ActivationView"? What is the proper way to do this? -
Django Registration Redux - How to get error messages to display at correct fields.
I am using Django Registration Redux and wanted to get some custom field styling done. However my error messages are not showing up as intended in template. I have tried to get it to show using {{form.errors}} and several variations on this without success. I would like to have the correct error message show up at the right field as it would when you use Registration Redux out of the box. <form action="." method="POST"> {% csrf_token %} <div class="row"> <div class="col-md-12"> <div class="form-group no-margin"> {{form.username | add_some_css:"form-control" }} </div> <span class="help-block">Your profile - http://snapper.com/<strong>username</strong></span> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group margin-top-30"> {{form.email | add_some_css:"form-control" }} </div> <div class="form-group"> {{form.password1 | add_some_css:"form-control" }} </div> <div class="form-group"> {{form.password2 | add_some_css:"form-control" }} </div> <div class="form-group no-border"> <button type="submit" class="btn btn-danger btn-block">Sign up</button> </div> </div> </div> </form> -
django administration page display only texts and links
I made a web server using python+django+mysql+iis server runs fine but when I surf into admin page, I only see texts and links,,not images..the screen capture of my admin page is in the link below. (sorry i don't have enough reputation to post an image..) my django admin page I'd really appreciate for any help Thanks! -
Django admin view without model
Sorry, I don't have a code sample yet as I'm trying to work out if what I'm thinking can even be done. I'm writing a Django app to manage Celery tasks. I'm using django-celery-beat for scheduled tasks but I'd like a similar admin interface to launch ad-hoc tasks with a form to accept parameters. All of the docs for ModelAdmin are based around custom fields for models but I don't think this object needs to be stored in a model as they are transient and data will be saved by the Celery task. From what I can troll you can't register a custom among view without trying it to a model. What I'm looking for is a custom view that's not tied to a model, just so I can create a custom gui with management commands in the admin. Ideas I've had from reading around the subject: Create a dummy model with managed = False in the Meta Create a real model, but just never access it within the custom ModelForm Just create a view and add the URL into the admin section manually. This might be the simplest approach but I've been avoiding as I'm not sure what would … -
How to let specific user to upload media files in Django
I wanted to let only some authenticated user(or use have specific permission) can upload media file with ImageField or FileField in Django. I tried to find out a way to this. I could find only way to let authenticated users view media files by apache basic or digest authentication with wsgi. Temporarily, I changed media file to chmod 777 to allow anyone can upload images. But I don't think it is good way with security issues. Is there any way to let only specific user(i.e users in specific group or users has specific permission) upload media file in Apache? I can do permission check to let specific users can upload in views in Django. But media folder remains 777. I don't want to remain that anonymous users can have read write permission for media folder. -
How to set multiple settings.py for sites framework django?
Am trying to set up multiple website with same base. While browsing, came to know Django has Sites framework which I could use. I didnt get how to set multiple settings.py file with site id. Any ideas anyone? Thanks in advance :) -
Can't save null for Integer and DateTime fields in Django Haystack with ElasticSearch Engine
I am using django haystack with django 1.8, using elastic search as the back end or search engine. Everything is working fine except rebuild_index in not able to create index for null IntegerField and Null DateTimeField. The error I am receiving is ValueError: invalid literal for int() with base 10: '' my felds are price = indexes.IntegerField(null=True, model_attr="get_price") year = indexes.IntegerField(null=True, model_attr="get_year") In the model_attr methods I am returning None if value is not null. -
How build to slack app using Django . Can anyone guide me ( atleast for baisc steps)
I want to achieve following thing here: I want to have my interactive massage with Buttons. For that, I got know that I need to create A "Slack App" for this. ( that is where problem begins ) I went through the slack documentation. Followed the steps but could not get it done. Then got this link https://medium.com/@MVaragnat/how-to-build-a-slack-app-5b83d71e083a#.qzh7hwskb Above link talks about An app ( written in Rails ) then hosted in Herako. But Since, I am more easy with Django so want anyone who can put some lights on it. PS: besides above, If I could get Interactive massages working any shorter way will also help. Thanks, -
Posting issue to BitBucket repository via API in Django
I'm trying to make it so users of a web portal are able to post issues to BitBucket by filling out information in a form and then grabbing the information from that form and posting it to the repository's API. My code is not throwing any exceptions, but it is also not posting the issue when I try to create it. BitBucket's REST API appears to accept basic authentication which is the route I took using python requests to do so: https://developer.atlassian.com/bitbucket/server/docs/latest/how-tos/command-line-rest.html I have my code setup this way: views.py if request.method == "POST": getUser = request.user form = IssueForm(request.POST) if form.is_valid(): priority = "minor" issue = Issue(**form.cleaned_data) title = form.cleaned_data['title'] kind = form.cleaned_data['kind'] content = form.cleaned_data['description'] #JSON payload to send to bitbucket with issue payload = { "priority": priority, "title": title, "kind": kind, "content": content, "created_on": issue.timestamp, "reported_by":{ "username": str(getUser), } } headers = { 'Content-Type': 'application/json', } r = requests.post('https://api.bitbucket.org/1.0/repositories/{accountname}/{repo_slug}/issues', headers=headers, data=payload, auth=('user', 'pass')) return HttpResponseRedirect("/main/") else: form = IssueForm() context = { "form": form, } return render(request, "issue_form.html", context) Where 'user' and 'pass' are my BitBucket username and password (for testing purposes) and the API url is my test repo. I was going by this documentation as … -
Filter objects based on related objects
So I have a form where user can post Parent details also form for Kid for a different model. what i need is to allow users to access list of Parent objects by filtering their related objects Kid let's say a filter to list Parents objects that has children named X older than Z live in Y city AND has no children named X who is younger than Z live in Y city . models.py : class Parent(models.Model): title = models.CharField(max_length=250) class Kid(models.Model): cities = ( ('city1', city1), ('city2', city2) ) family = models.ForeignKey(Parent) title = models.CharField(max_length=250) age = models.CharField(max_length=250) city = models.CharField(choices=cities) Views.py : def index(request): my_pattern = ( (name=samy, age_lt=15, city=paris), ) filter_ids = Kid.objects.filter(my_pattern).values_list('parents_id', flat=True).distinct() exclude_ids = Kid.objects.exclude(my_pattern).values_list('parents_id', flat=True).distinct() parents = Parent.objects.filter(id__in=filter_ids).exclude(id__in=exclude_ids) template = 'index.html' context = {'parents': parents} return render(request, template, context) as the views.py shows i listed the pattern as a tuple but didn't work! i am also wondering if this is the way to do django Q objects except for adding Q in the beginning! -
Add permissions to the default group in django using post_save signals
I created two groups using post_save signals in django. My default groups name are: 'members' and 'managers'. Now I try to add default permissions to the default gropu 'members'. So far I did: @receiver(post_save, sender=settings.AUTH_USER_MODEL) def add_to_default_permission(sender, **kwargs): members = kwargs["instance"] if kwargs["created"]: permission1 = Permission.objects.get(name='Can add person') permission2 = Permission.objects.get(name='Can change person') permission3 = Permission.objects.get(name='Can add child') permission4 = Permission.objects.get(name='Can change child') permission5 = Permission.objects.get(name='Can delete child') members.permissions.add(permission1, permission2,permission3,permission4,permission5) But when I tried to create superuser, it gives errors: in add_to_default_permission members.permissions.add(permission1, permission2,permission3,permission4,permission5) AttributeError: 'User' object has no attribute 'permissions' How could I fix this error. Any advice will be much appreciated. -
Tastypie with oAuth 2.0
Hi I am relatively new to python with django framework, is there a way where in I can use tastypie rest framework with oAuth 2.0 if so what is the best approach -
Risks of open sourcing nginx configuration
I recently open sourced the source code to a small Django project I've been working on. As part of open sourcing, I would like to also make public the nginx configuration and uwsgi files. I was wondering if there is a list of considerations I need to be aware of before making this public, or if it is a terrible idea altogether. -
gunicorn status is active (exited) but showing not running in monit
I am trying to setup a new django project on a server from scratch (django+gunicorn+nginx) and I have everything correct except the init scripts for gunicorn. if I run the gunicorn command manually it works and I can view my site on the ip address, but when I try to do service gunicorn start it gives me this output and it doesn't work... gunicorn-project.service Loaded: loaded (/etc/init.d/gunicorn-project; bad; vendor preset: enabled) Active: active (exited) since Thu 2016-11-17 04:23:56 UTC; 17min ago Docs: man:systemd-sysv-generator(8) Process: 1656 ExecStart=/etc/init.d/gunicorn-project start (code=exited, status=0/SUCCESS) Tasks: 0 Memory: 0B CPU: 0 Nov 17 04:23:56 project gunicorn-project[1656]: from multiprocessing import cpu_count Nov 17 04:23:56 project gunicorn-project[1656]: /etc/gunicorn.d/gunicorn-project2.py:3: RuntimeWarning: Parent module '/ Nov 17 04:23:56 project gunicorn-project[1656]: from os import environ Nov 17 04:23:56 project gunicorn-project[1656]: /etc/gunicorn.d/gunicorn-project3.py:2: RuntimeWarning: Parent module ' Nov 17 04:23:56 project gunicorn-project[1656]: from multiprocessing import cpu_count Nov 17 04:23:56 project gunicorn-project[1656]: /etc/gunicorn.d/gunicorn-project3.py:3: RuntimeWarning: Parent module ' Nov 17 04:23:56 project gunicorn-project[1656]: from os import environ Nov 17 04:23:56 project gunicorn-project[1656]: * Nov 17 04:23:56 project systemd[1]: Started gunicorn-project.service. Nov 17 04:25:01 project systemd[1]: Started gunicorn-project.service. I cannot figure out why this is happening... this is the file references in the output... """gunicorn WSGI server … -
filter objects using foreignkeys
So I have a form where user can post "Parent" details also form for Kid for a different model. what i need is to allow users to access list of "Parent" objects by filtering their related objects "Children" let's say a filter to list Parents objects that has children named X older than Z live in Y city AND has no children named X who is younger than Z live in Y city . models.py : class Parent(models.Model): title = models.CharField(max_length=250) class Kid(models.Model): cities = ( ('city1', city1), ('city2', city2) family = models.ForeignKey(Parent) title = models.CharField(max_length=250) age = models.CharField(max_length=250) city = models.CharField(choices=cities) any idea how to do it or where/what to look for the answer? -
Can't seem to capture multiple files in form using Django
I want to be able to retrieve two images from a form in Django but I'm only able to find one in the request.FILES dictionary after submitting. When attempting to reference the other file by name I get the exception "MultiValueDictKeyError". I was under the impression that this was able to be done with two input fields in a form and with the form attribute "enctype" being set as "multipart/form-data" but have had not had any success nor found any working suggestions on other posts. Below is the code I am currently using, please be aware that it is still a very rough draft. Here is my HTML template with the form: {% extends 'base.html' %} {% block content %} <form action="{% url 'picloader:upload_pics' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="container"> <div class="col-sm-8 col-lg-offset-2"> <div class="jumbotron"> <div class="container text-center"> <div class="row"> <em>Upload a base image and a style image.</em> <br> <em><u>Remember</u> - the base image will receive the style transfer!</em> <hr> </div> <div class="row"> <div class="col-sm-4 col-lg-offset-2 text-center"> <label class="btn btn-default" for="my-file-selector"> <input id="my-file-selector" type="file" name="base-image" style="display:none;"> Base Image </label> </div> <div class="col-sm-4 text-center"> <label class="btn btn-default" for="my-file-selector"> <input id="my-file-selector" type="file" name="style-image" style="display:none;"> Style Image </label> </div> </div> </div> …