Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
count distinct value in django model field
Hi I have a django model which has two field 'date' and 'result'. +----------+-------------+-------------------------- |date | result| +----------+-------------+-------------------------- |2017-03-27 | passed | |2017-03-27 | passed | |2017-03-27 | passed | |2017-03-27 | failed | |2017-03-27 | failed | |2017-03-26 | passed | |2017-03-26 | failed | +-----------+-------------+-------------------------- I need to count the value of result following way date 2017-03-27 passed=3 and failed=2 One of the probable solution is following Results.objects.filter(date=date.today()).values('result').annotate(passed=Count('result'))}, I am using above command in the django chartit in order to draw pie chart to show total number of passed and failed value. View: def chart(request): resultdata = DataPool( series= [{'options': { 'source': Results.objects.filter(date=date.today()).values('result').annotate(passed=Count('result'))}, 'terms':[ 'date', 'passed']} ]) cht = Chart( datasource = resultdata, series_options = [{'options':{ 'type': 'pie','stacking': False, }, 'terms':{ 'date':[ 'passed'] }}], chart_options = {'title': { 'text': 'Result of test cases'}, }) But it assign the count value both to "passed" variable.I need to show in two separate variable passed and failed. How can I separate the value? -
Django url configuration by groups of data
I need to create month based views. I can filter my entry items by month and I can display them on an html page. What I am having a hard time doing is only showing which month's data you select from the main page. So for example, if you click on November, it takes you to a page that only shows November's items, and so on. Do I need a specific url config for this? I'm hoping there is a simpler way to do this rather than creating a view for every month and then creating each month's url... urls.py urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'entry/list/?P<month_here>$', views.EntryListView.as_view(), name='entry-list'), ] views.py class EntryListView(generic.ListView): template_name = 'argent/index_list.html' context_object_name = 'object_list' def get_queryset(self): return Entry.objects.all() def get_context_data(self, **kwargs): mth = super(EntryListView, self).get_context_data(**kwargs) # ENTRY BY MONTH # January17 mth['January17_qs'] = Entry.objects.filter(date__range=('2017-1-1', '2017-1-31')) # February17 mth['February17_qs'] = Entry.objects.filter(date__range=('2017-2-1', '2017-2-28')) return ctx -
Django rest framework: convert queryset to json response
I have two models, Appointment and EmployeeEvent. I need to get data from these models and combine the result in to a single get api request. urls.py url(r'^calenderevents', calender_events) views.py @api_view(['GET']) def calender_events(request): queryset1 = Appointment.objects.all() queryset2 = EmployeeEvent.objects.all() return Response({'Appointments':json.loads(serializers.serialize('json', queryset1)), 'EmployeeEvents': json.loads(serializers.serialize('json', queryset2))}) When I call the API, I am getting the result, but it includes some unwanted keys like "pk", "model", "fields" etc. Also in the appoinments result, I need the full customer object instead of the customer id. Is there any way to specify the CustomerSerializer along with the query set? Results am getting { "Appointments": [ { "pk": "33a0fffb-326e-4566-bfb4-b146a87a4f3f", "model": "appointment.appointment", "fields": { "customer": "25503315-8bac-4070-87c1-86bf0630c846", "status": "Requested", "description": "Assigned appointment", } }, { "pk": "9da806f5-77f1-41e6-a745-7be3f79d6f7a", "model": "appointment.appointment", "fields": { "customer": "25503315-8bac-4070-87c1-86bf0630c846", "status": "Requested", "description": "Assigned appointment", } } ], "EmployeeEvents": [ { "pk": "f76b5de0-1ab8-4ac3-947d-15ba8941d97d", "model": "employee_event.employeeevent", "fields": { "event_name": "New Event", "start_date": "2017-02-17", "end_date": "2017-02-22" } }, { "pk": "56f02290-370e-426c-951e-a93c57fde681", "model": "employee_event.employeeevent", "fields": { "event_name": "New Event", "start_date": "2017-02-02", "end_date": "2017-03-22" } } ] } Expected Result { "Appointments": [ { "id": "33a0fffb-326e-4566-bfb4-b146a87a4f3f", "customer": { "id": "25503315-8bac-4070-87c1-86bf0630c846", "firstname": "Customre 1", "photo_url": "imagepath", }, "status": "Requested", "description": "Assigned appointment" }, { "id": "9da806f5-77f1-41e6-a745-7be3f79d6f7a", "customer": { "id": … -
Why does 0 in a GET request evaluate to True in a Django 1.10 form?
I am passing a GET request to a Django form that contains the parameter "favorite." When I do localhost:8000?favorite=1, it works fine. 1 evaluates to True, just as I expect. However, when I do localhost:8000?favorite=0, 0 evaluates to True as well, which is not what I expect. When I look at request.GET['favorite'] directly, before it is evaluated by the FavoriteForm class, I see that it equals 0. However, the FavoriteForm class seems to be converting this to True, and I don't know why. I assume that it is treating 0 as a string, and it evaluates all strings to True, but it does not make sense that this is how they would have set it up, because it is counterintuitive, so I imagine there must be something else going on, like some misconfiguration of my form or something. Ideas? forms.py class FavoriteForm(forms.Form): favorite = forms.BooleanField() views.py if request.method == 'GET': form = FavoriteForm(request.GET) favorite = form.cleaned_data['favorite'] print favorite #This returns True if request.GET['favorite'] == 0 print request.GET['favorite'] #This returns 0 as expected query http://localhost:8000?favorite=0 -
how to redirect user after admin deletion
I want a logged in user to be redirected back to the homepage when the django admin hard deletes his entry from the backend. Currently it just shows empty values for everything in the frontend after deletion. How can this be achieved so that a user session is automatically terminated and redirected to homepage after his member entry is deleted from the backend? -
how to get audio file in response to ajax get request in django
i am creating a music app i have a function in view album(request) which display all the albums and songs. I want to function it like: when i hit play button it should sent an ajax-get request and in that request it sends song-id of whosoever song user clicked , when view receive that ajax-get request, based on song-id ajax request sent, it should return the corresponding song file (mp3) back to browser as JsonResponse and using jquery song plays. i know there is something wrong with my view so please tell me the correct way to do so!!!! THANK YOU IN ADVANCE list-album.html with javascript {% extends "base.html" %} {% block content %} {% for album in albums %} <li>{{ album.album_title }} <small> {{ album.album_genre }}</small></li> <li>{{ album.album_artist }}</li> {% for song in album.song_set.all %} <li>{{ song.song_title }}</li> <button type="submit" class="play" data-id="{{ song.pk }}" >Play</button> {% endfor %} {% endfor %} {% endblock content %} {% block javascript %} <script type="text/javascript"> $(document).ready(function(){ $('.play').click(function(e){ e.preventDefault(); var song_id = $(this).attr('data-id') alert(song_id); $.ajax({ type: 'GET', url: 'get_song/', // it goes to function get_song given below data: { 'song_id': song_id }, dataType: 'json', success: function (data) { // Code to play received song … -
Copy object from one user profile to another in django
I am finding a lot of answers on this question but not able to to figure out how to apply this to my issue. I have a wishlist for each user and many users can have the same wish. What I want to do is if David has a pepsi on it list the pepsi = product. And Michelle wants to add that to her list. I want to be able to to copy and save the product ie pepsi save it as a vairable so i can add it to the database with Michelles user name so now i have to database entries with pepsi but different users. I do not want michelle to have to enter the product but just click the button to add it. I belive if I modify my create function I could do this. I just dont know what to use to get the product into the model of the specfic one they clicked. Html <h1>Hello {{theUser.name}}!</h1> <h2>Your Wish List</h2> <table class="table"> <tr> <th>Name</th> <th>Added by</th> <th>Date Added</th> <th>Remove From my Wishlist</th> <th>Delete</th> </tr> {% for i in info%} <tr> <td><a href="{% url 'blackbelt:show' i.id %}">{{i.product}}</a></a></td> <td>{{i.creator.name}}</td> <td>{{i.created_at}}</td> <td><a href="{% url 'blackbelt:show' i.id %}">Remove … -
show a list of rent contacted by specific buyer
I am a beginner of django-rest-framework. I am trying hard to understand the serializer and good api design. I dont want to dive directly into viewset and generics view like ListView, RetrieveAPIView and etc. I want to understand the serializer and APIView clearly so i drew the following criteria to solve them. However i could only solve 2 of the problem from below. Here is the list of problems i drew to hone my rest api skill """ return a list of rent """ """ return a list of rent or specific rent if token is give n """ """ return a list of rent contacted by specific buyer """ """ return a list of buyer that has contacted a specific rent """ Here is my model of Rent, Galleries and Contact. Rental and contact are separate app. Contact is to contact a rent owner to buy or rent the space listed by that owner. class Rental(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=300, blank=False, null=False) phone_number = models.PositiveIntegerField(null=False, blank=False) rate = models.FloatField() class Gallery(models.Model): rent = models.ForeignKey(Rental, related_name="galleries") image = models.FileField(upload_to=user_directory_path, null=True, blank=True) tag = models.CharField(max_length=1, choices=TAGS, null=True, blank=True) BUYER_CHOICES = ( ('B', 'Buy'), ('R', 'Rent'), ) class Contact(models.Model): buyer … -
Angular with django templates [duplicate]
This question already has an answer here: AngularJS with Django - Conflicting template tags 13 answers Today i'm start learn angular with django try do next: {{ 1 + 2 }} That it must calculate angular but i got an error. Could not parse the remainder: ' + 2' from '1 + 2' How i can user angular tags with django tags un template coz. Django template: {{ somevar }} Angular: {{ 1 + 2 }} -
Validate modelform field based on attributes of foreignkeys of the model the form is based on
Ok I got 2 models and a through model .The through model has 2 foreign keys to the other 2 models .I also a have a form to fill the integer field the though model contains .The problem is that I want to validate this field based on attributes of the parent models(attributes of the foreign keys).Why is this a problem ?Because first the user fills the integer field and hits submit ,then the foreign keys are set.So its impossible to validate it correctly.That happens because when form.is_valid() is called the foreign keys are not yet set.So the question is "is there a way to do so ?" or "is there a way to prefill the foreign keys when the forms are loaded for the first time?".I tried to pass the foreign keys as initial data to the forms but didnt have any luck . Models : class criterion(models.Model): quantity = 0 quality = 1 ascending = 0 descending = 1 three = 3 five = 5 seven = 7 ten = 10 type_choices = ( (quantity,'Ποσοτικό'), (quality,'Ποιοτικό'), ) monotonicity_choices = ( (ascending,'Αύξον'), (descending,'Φθίνον'), ) a_choices = ( (three,'Τριβάθμια'), (five,'Πενταβάθμια'), (seven,'Εφταβάθμια'), (ten,'Δεκαβάθμια'), ) criterion_research = models.ForeignKey('research', on_delete=models.CASCADE,null=True) criterion_name = models.CharField(max_length … -
Trying to import images in Django
I am currently working on a project that requires me to upload huge amounts of data through the admin panel, I have installed Django-import-export. Now when I export records I get an image column if I try to re-uplaod that data but fill in the image field I get an error: Cannot assign "u''": "Component.image" must be a "Image" instance. Traceback (most recent call last): File "/home/vagrant/env/local/lib/python2.7/site- packages/import_export/resources.py", line 452, in import_row self.import_obj(instance, row, dry_run) File "/home/vagrant/env/local/lib/python2.7/site- packages/import_export/resources.py", line 331, in import_obj self.import_field(field, obj, data) File "/home/vagrant/env/local/lib/python2.7/site- packages/import_export/resources.py", line 321, in import_field field.save(obj, data) File "/home/vagrant/env/local/lib/python2.7/site- packages/import_export/fields.py", line 112, in save setattr(obj, attrs[-1], self.clean(data)) File "/home/vagrant/env/local/lib/python2.7/site- packages/django/db/models/fields/related.py", line 639, in __set__ self.field.rel.to._meta.object_name, ValueError: Cannot assign "u''": "Component.image" must be a "Image" instance. I have tried multiple ways to upload multiple images but nothing I have tried has worked, I really need this to allow images to be uploaded I have to import over 60,000 records each with images (Most of them are the same) but I cant manually go through them all and assign images to them. Is there anyway to get round this problem so I can upload images or at least a destination of the file location that … -
Django - stop users from getting access to same value
I have a calendar which is suppose to be connected to the current admins-association. Admin picks a date in the calendar and register the form so that event is set. But when i log in with another admins-association, i still can see the event from the last admin. I want to keep them separately from each other. These data seems correct to me as no other admins who does not have the same association_id will see the event. Still a newbie so guide me in the right way and appreciate all your help, folks! models.py class Administrator(AbstractUser): # inherits the standard User-model ... association = models.ForeignKey(Association) class Event(models.Model): name = models.CharField(max_length=50) location = models.CharField(max_length=100) start = models.DateTimeField(blank=False) end = models.DateTimeField(blank=False) allday = models.BooleanField() description = models.TextField(max_length=200) synced = models.BooleanField(default=False) gid = models.CharField(default='', max_length=100) association = models.ForeignKey(Association) class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) views.py class calendar(ListView): model = Event template_name = 'calapp/calendar.html' def get_queryset(self): queryset = Event.objects.filter(association=self.request.user.association) return queryset def event_add_edit(request): if request.method == 'POST': res = {'success': False} action = request.POST['action'] name = request.POST['name'] location = request.POST['location'] start = request.POST['start'] end = request.POST['end'] allday = request.POST['allday'] == 'true' description = request.POST['description'] synced = request.POST['synced'] == 'true' association = Association.objects.filter(asoc_name=request.user.association) … -
How do I build a user login using Python and Django so that users have unique message objects?
Have you ever used Django and Python to build a user login? I eventually want users with unique message objects. How would I accomplish something like that? -
Django installed_apps does not recognise my app?
This is my installed apps section in settings.py. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'homepage.apps.HomepageConfig', . . . ] My app name is "homepage" and I really can't remember why I changed it to 'homepage.apps.HomepageConfig', but whatever it is, it worked on my machine. Now, i uploaded my files to server, installed required apps, did the migrations, but i noticed django does not create my "homepage" app table and does not migrate anything from my app. And my website returns the error: table homepage_post does not exist. What is wrong? -
Django annotate single instance of many-2-many field using 'when' on other fields of the instnce
I have a somewhat complicated model, so I will do my best to give an example that simplifies my current state, and my need. I have a queryset: qs = MyModel.objects.all() Each instance in this queryset, has a many-2-many field to another model, let's call it 'First_M2M'. First_M2M has a foreign key to another model, and a many-2-many to yet another model (FkModel and Second_M2M, respectively): qs[0].first_m2m.fk_model.name # This is a string. qs[0].first_m2m.second_m2m.all() # This is a many2many manager. The Second_M2M has another many-2-many relationship, Third_M2M: qs[0].first_m2m.second_m2m[0].third_m2m.all() # Also a m2m manager. Now that's what I'm trying to do: I want to order my qs, based on a value from one of the second_m2m instances. However, I need to choose which instance is it, and this is done by querying a field in the fk_model (to determine the first_m2m instance) AND a field in one of the instances in the third_m2m (this will determine the second_m2m). In order to make it even more interesting, the value to order by, is YAML. Here's what I tried to do: qs.annotate(val_to_filter_by=Case( When( first_m2m__fk_model__name='foo', first_m2m__second_m2m__third_m2m__some_field='bar'), then='first_m2m__second_m2m__value_field', default=Value(None), output_field=YAMLField() ) ).order_by(val_to_filter) I believe what I got wrong is the querying, that is not coherent enough … -
Error during template rendering in Django
i know that i'm missing somthing within my base_template bu I can't figure it out. def IndexView(request): if request.user.is_authenticated(): base_template_name = 'blog/base.html' else: base_template_name = 'blog/visitor.html' profile_form = ProfileForm( instance = request.user.profile) posts = Post.objects.all() return render(request, 'blog/index.html', {'posts':posts,'profile_form': profile_form, 'base_template_name':base_template_name}) def Profil(request, pk): posts = Post.objects.filter(user=request.user) if not request.user.is_authenticated(): return render(request, 'blog/visitor.html') else: post = get_object_or_404(Post, pk=pk) context = {'posts':posts, 'post': post} if post.user != request.user: return render(request, 'blog/Profilvisitor.html', context) else: return render(request, 'blog/profil.html', context) -
Unable start gunicorn.sock after python 3.6 update
I am trying to deploy a Django App using Gunicorn + Python3 + Nginx. Before updating to python 3.6 everything was working. But after update I cant seem to create a gunicorn sock file. I use below script to run the Gunicorn. #!/bin/bash NAME=yogavidya #Name of the application (*) DJANGODIR=/home/ytsejam/public_html/abctasarim/ # Django project directory (*) SOCKFILE=/home/ytsejam/public_html/abctasarim/run/gunicorn.sock # we will communicate using this unix socket (*) USE=ytsejam # the user to run as (*) GROUP=webdata # the group to run as (*) NUM_WORKERS=1 # how many worker processes should Gunicorn spawn (*) DJANGO_SETTINGS_MODULE=yogavidya.settings.base # which settings file should Django use (*) DJANGO_WSGI_MODULE=yogavidya.wsgi # WSGI module name (*) echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /usr/bin/virtualenvwrapper.sh source /home/ytsejam/.virtualenvs/yv_dev/bin/activate workon yv_dev export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec /home/ytsejam/public_html/abctasarim/gunicorn --name=$NAME --workers=$NUM_WORKERS --env=DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE --pythonpath /home/ytsejam/public_html/abctasarim --user ytsejam --bind=unix:/home/ytsejam/public_html/abctasarim/run/gunicorn.sock yogavidya.wsgi:application When I check the output message showing status service which runs script, behaviour changes time to time if it fails : ● … -
How to resolve ID (Django ORM) that generates with SQL script on DB
Django ORM doesn't resolve id that generates in DB with special SQL trigger while record inserting. When I'm saving model without ID it saves correctly and have ID in DB? but m.id returns me None. class SomeModel(Model): id = IntegerField(primary_key=True) name = CharField(null=False, max=50) m = SomeModel(name='asd') m.save() m.id # - None How I can resolve autogenerated ID after saving? Or how I can rewrite save() method? Or maybe change field type? -
UpdateView is missing a QuerySet Error
As of today, my UpdateView no longer works. Whenever I select the icon to edit an item I get the following error: EntryUpdate is missing a QuerySet. Define EntryUpdate.model, EntryUpdate.queryset, or override EntryUpdate.get_queryset(). I have never had to have a QuerySet within my UpdateView before, so I am unsure why it is asking for one now. My understanding of the Generic UpdateView is that the self-query was built in, but I may be wrong. Any help would be much appreciated. views.py class IndexView(generic.ListView): template_name = 'argent/index.html' # paginate_by = 10 def get_queryset(self): return Entry.objects.all() def get_context_data(self, **kwargs): ctx = super(IndexView, self).get_context_data(**kwargs) # TODAY'S ENTRY ctx['entry_qs'] = Entry.objects.filter(date=today_date) # CURRENT SAVINGS TOTALS ctx['savings_qs'] = Savings.objects.filter(id=1) # MONTHLY TOTALS # November ctx['November16_qs'] = MonthYear.objects.filter(month='November') # December ctx['December16_qs'] = MonthYear.objects.filter(month='December') # January ctx['January17_qs'] = MonthYear.objects.filter(month='January') # February ctx['February17_qs'] = MonthYear.objects.filter(month='February') # March ctx['March17_qs'] = MonthYear.objects.filter(month='March') # # April # ctx['April_qs'] = MonthYear.objects.filter(month='April') # # May # ctx['May_qs'] = MonthYear.objects.filter(month='May') return ctx class DetailView(generic.DetailView): model = Entry template_name = 'argent/detail.html' # # def get_context_data(self, **kwargs): # ctx = super(DetailView, self).get_context_data(**kwargs) # ctx['savings_qs'] = Savings.objects.filter(id=1) # return ctx class EntryCreate(CreateView): form_class = EntryForm template_name = 'argent/entry_form.html' def form_valid(self, form): if form.save(self): # total_euros_spent sum_euros = … -
How to change the heading of all models in django admin
enter image description here I have created a model named 'Questions' in my app.Please see the attached image. here my app name is 'polls'.Is it possible to change in admin view? -
What is the process for adding categorized blog functionality to an existing Django App using Wagtail?
I have an existing Django App running Django 1.9. I am trying to add blog functionality using Wagtail CMS to my existing App, but have been unable to make any meaningful progress. What I am trying to achieve Build a page on the website, e.g. http://www.example.com/content that when visited displays blog posts. The top part of the page should display the last 3 blog posts by any of three specific users. There should be some way to navigate through blog posts belonging to these three users, (perhaps a slider) or a link to a different page which simply lists all posts belonging to these users. The key is that the three latest blog posts and the functionality to display additional posts from these users should only take the top half of the screen space available. Underneath these blog posts, should be listed all other blog posts from any other users, using pagination or similar so that readers can navigate through the blog posts. Steps Taken So Far I have installed Wagtail into the existing Django app, using the instructions here: http://docs.wagtail.io/en/v1.9/getting_started/integrating_into_django.html Including: Installing Wagtail (pip install wagtail) Adding Wagtail apps, and dependencies to INSTALLED_APPS in settings.py Added the middleware classes … -
celery periodic task not getting executed with tasks.py
Hi I have added a new app called "schedule_stop" and registered the app in settings also. Now added a new file called tasks.py and following is the content of the file, from celery.task.schedules import crontab from celery.decorators import periodic_task from django.conf import settings import logging logger = logging.getLogger('app.main') @periodic_task(run_every=crontab(minute='*/1'), options={'queue':settings.APP_CORE_QUEUE}) def delete_inactive_task(): logger.info('log value') value of settings.APP_CORE_QUEUE = app_core_queue required celery process are running as below, ubuntu 5711 0.0 1.0 188564 41172 pts/0 S+ 10:28 0:00 /home/ubuntu/devbuild/venv/bin/python /home/ubuntu/devbuild/venv/octopus/../bin/django-admin celery -A app beat ubuntu 5712 0.0 1.2 218344 52428 pts/0 S+ 10:28 0:00 /home/ubuntu/devbuild/venv/bin/python /home/ubuntu/devbuild/venv/app/../bin/django-admin celery worker -Q app_core_queue ubuntu 5733 0.0 1.1 216484 47192 pts/0 S+ 10:28 0:00 /home/ubuntu/devbuild/venv/bin/python /home/ubuntu/devbuild/venv/app/../bin/django-admin celery worker -Q app_core_queue But still above function delete_intractive_task() is nog getting execute for every one minute. How to debug what is the issue ? tasks.py file is not even getting executed during the start of the application, even if there is any syntax error in this tasks.py file its not giving any error -
How sync web (postgresql),ios,android?
My scheme is: Django (backend) with REST API and 3 clients: angular, ios, android. Now all clients works only online (Rest api). I want to create offline version for my apps and sync all when app online. I add coreData to my ios app. I see realm, but is only mobile device sync. Tell me please what a way is more right? How I sync my backend with all devices? Thanks a lot. -
Removing fields from rss feed (based on syndication framework) Django
I wish to remove field 'length' from enclosure tag in rss, which I generated with built-in syndication framework in django, and I can not understand how it can be done. -
How to create "Many to Many" object using template?
I want to allow user to join one of the listed groups using template. So I found 2 problems here: "Join" button as a form with many to many field. Running python function as a button action in the template. If it's possible I want to run something like this: group.members.add(request.user) and hopefully refresh a page. models.py: class Group(models.Model): name = models.CharField(max_length=500) creator = models.ForeignKey(User) members = models.ManyToManyField(User, blank=True, related_name='member') template.html: {% for group in groups %} <p>{{ group.name }} <button type="submit" action="">Join</button></p> <hr> {% endfor %}