Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form.save() saves incorrect data
I have a weird problem. My form doesn't save recieved data for one field. There is a field category which is a ForeignKey, in form it is ModelChoiceField filed. You can choose from 4 categories - Uncategorized, Televisions etc. The problem is that even when I choose Televisions or something else, it saves the model with category Uncategorized instead of Televisions. When I print request.POST it sends correct data. <QueryDict: {u'category': [u'3'], u'csrfmiddlewaretoken': ['token'], u'name': [u'dsadasda'], u'groups': [u'5']}> FORM class NewProductForm(forms.ModelForm): class Meta: model = models.Product fields = ('name','category','groups') def __init__(self, user, *args, **kwargs): super(NewProductForm, self).__init__(*args, **kwargs) self.fields['groups'] = forms.ModelMultipleChoiceField( queryset=models.Group.objects.filter(user=user)) self.instance.user = user MODEL class Product(models.Model): user = models.ForeignKey(User,null=False,blank=False) name = models.CharField(max_length=200) groups = models.ManyToManyField('Group', related_name='products') category = models.ForeignKey('Category', related_name='products', null=True, blank=True) VIEW @decorators.is_authenticated_or_homepage def add_new_product(request): form = NewProductForm(request.user, request.POST or None) if request.method == 'POST': print request.POST if form.is_valid(): form.save() return HttpResponseRedirect(reverse('dashboard_products')) context = {'form':form} return render(request,'main_app/dashboard/new-product.html',context=context) Do you know what's the problem? -
How to assertRaises a django.contrib.auth.models.DoesNotExist exception?
I'm trying to assert in a test that a statement raises this exception however it appears that it is impossible to import said exception. This does not work for example: from rest_framework.test import APITestCase from rest_framework.test import APIRequestFactory from CarPooling.views import login, logout from django.urls import reverse from django.contrib.auth.models import User, UserManager from django.contrib.auth import authenticate from rest_framework.authtoken.models import Token from CarPooling.models import AccountActivationToken from rest_framework import status from django.contrib.auth.models import DoesNotExist class LoginViewTests(APITestCase): def test_login(self): url = '/api/token/' data = {'email': 'up20@fe.up.pt', 'password': 'testpassword'} user = create_user('joao', 'testpassword', 'up20@fe.up.pt') user = User.objects.get() user.is_active = True user.save() response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['token'], Token.objects.get(user=user).key) data = {'email': 'up20@fe.up.pt', 'password': 'tsubasaolivesr'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) data = {'email': 'up20@fe.up.pt', 'password': 'tsubasaolivesr'} self.assertRaises(models.DoesNotExist, self.client.post(url, data, format='json')) The test fails complaining that exception django.auth.contrib.auth.models.DoesNotExist was invoked, even though I explicitly am asserting it is supposed to happen. -
django.db.utils.OperationalError: 1005, 'Can't create table `xyz`.`#sql-600_237` (errno: 150 "Foreign key constraint is incorrectly formed")
I am trying to add One-to-One keys into my Django app, but I always get that error when I try to "migrate" process (makemigrations works like charm). [....] return self.cursor.execute(sql, params) File "/opt/cvm/env/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 124, in execute return self.cursor.execute(query, args) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 226, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorvalue django.db.utils.OperationalError: (1005, 'Can\'t create table `xyz`.`#sql-600_237` (errno: 150 "Foreign key constraint is incorrectly formed")') That's what my models looks like : class PersonVolunteer(models.Model): person = models.OneToOneField(Person) class Person(models.Model): name = models.CharField(max_length=100) And the migration process that cause the crash : class Migration(migrations.Migration): dependencies = [ ('xyzapp', '0014_member_to_person'), ] operations = [ migrations.CreateModel( name='PersonVolunteer', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('personne', models.OneToOneField(to='cvmapp.Personne')), ], ), ] However, all works correctly when I test it even after the migrate error. But if that error message appears during "migrate", that should not be something good happening. If there's no problem, it is possible to skip that last step which crash my migration ? Can someone can say me why do I get that error message and how I can resolve it ? Thank you very much and have a great day ! -
Django Models from Across Apps
How do you access a model from across apps? For instance: app:customers -view:customerdetail model:customers table:tblCustomers app:reports -view:reportdetail model:customers table:tblReports servicereport:urls.py from django.conf.urls import include, url from django.contrib import admin from . import views as servicereport_views app_name = 'servicereport' urlpatterns = [ url(r'^$', servicereport_views.ServiceReportIndex.as_view(), name='servicereport_index'), servicereport:views.py from servicesite.customers import models as servicereports_models from django.views.generic import ListView, DetailView, UpdateView, DeleteView, CreateView, View from django.core.urlresolvers import reverse_lazy from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from . import forms as servicereport_forms class ServiceReportIndex(ListView): template_name = 'servicereport/servicereport_index.html' context_object_name = 'all_ServiceReports' def get_queryset(self): return servicereports_models.TblServiceRecords.objects.all().order_by("date_entered") Error File "/path/to/project" in 1. from servicesite.customers import models as servicereport_models Exception Type: ImportError at /servicereport/ Exception Value: No module named 'servicesite.customers' I've tried: from servicesite.customers import models as servicereports_models from customers import models as servicereports_models from ..customers import models as servicereports_models among other things and each of those fail. -
Django ImportError: No module named django_html?
Backtrace Error Log : ==>python manage.py runserver Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "//anaconda/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "//anaconda/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "//anaconda/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "//anaconda/lib/python2.7/site-packages/django/core/management/base.py", line 280, in execute translation.activate('en-us') File "//anaconda/lib/python2.7/site-packages/django/utils/translation/__init__.py", line 130, in activate return _trans.activate(language) File "//anaconda/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 188, in activate _active.value = translation(language) File "//anaconda/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 177, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "//anaconda/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 159, in _fetch app = import_module(appname) File "//anaconda/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module __import__(name) ImportError: No module named django_html How I can resolve this import error ? -
Include template with dynamic Django form
I have a model with a choices field, and the creation form has different fields depending on the field. I'm implementing the design of a dashboard in which the user can click a button (one button for each choice) and a modal containing the model form will be displayed. I want to use a template only for the modal, and send the form and action URL to it depending on which button the user clicks, but that would mean I have to mix JS and Django variables and I don't know if that's a good idea. The code right now is something like this: dashboard.html <div class="add-connections"> <div class="col-sm-3 text-center" > <div class="connection-box"> {% if user_connections.EP %} <img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check"> {% else %} <a href="" class="btn" data-toggle="modal" data-target="#modal-new-connection">Activate</a> {% endif %} </div> </div> <div class="col-sm-3 text-center" > <div class="connection-box"> {% if user_connections.OLX %} <img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check"> {% else %} <a href="" class="btn" data-toggle="modal" data-target="#modal-new-connection">Activate</a> {% endif %} </div> </div> <div class="col-sm-3 text-center" > <div class="connection-box"> {% if user_connections.CC %} <img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check"> {% else %} <a href="" class="btn" data-toggle="modal" data-target="#modal-new-connection">Activate</a> {% endif %} </div> </div> … -
Django Apache installation on CentOS. Using Apache as the Web server
from this link Serving files Django doesn’t serve files itself; it leaves that job to whichever Web server you choose. We recommend using a separate Web server – i.e., one that’s not also running Django – for serving media. Here are some good choices: Nginx A stripped-down version of Apache If, however, you have no option but to serve media files on the same Apache VirtualHost as Django, you can set up Apache to serve some URLs as static media, and others using the mod_wsgi interface to Django. after the painful installation of django, why can't I use apache to serve the application? Edit: using virtualenv for python -
Django page not rendering html template
New to Django - I am working on a simple deployment of a Django web application using the DjangoGirls tutorial and having issues with rendering templates from HTML. The code below runs on my localhost perfectly (displaying the posts from my blog model), the environment that is set up on the server is identical and the error log is empty on pythonanywhere, nothing in the console to assist. <html> <head> <title>Michael Test</title> </head> <body> <p>Hi There!</p> <p>It works!</p> {% for post in posts %} <div> <p>published: {{ post.published.date }}</p> <h1><a href="">{{ post.title }}</a></h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endfor %} </body> </html> http://michaelbergin.pythonanywhere.com/ - is the site where the deployment is not functioning properly (only showing Hi there!, It works!) and not rendering from the template. Thanks for any tips. -
Django core serializers, full path of image or method serialize
I have simply model: class SimplyModel(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to="images/", blank=True, null=True) def get_image(self): return self.image.path def __str__(self): return self.name And I serilize it by from django.core import serializers def get_my_model(request): #some operations... data = serializers.serialize('json', SimplyModel.objects.all()) return HttpResponse( data, content_type="application/json" ) But on frontend when I service this data, in image filed I have only: images/myimage.jpg without media prefix. I have all 'media-configuration' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "../media") And I can get this image by serveradress.com/media/images/myimage.jpg I tried to add method to model, like def get_image(self): return self.image.path But I cannot see this method in my respons. How can I get this absolute path? Or serilize method by django-core serialzer? (I don't want to use DRF) Best -
Django - How to pass queryset to the template using a class based UpdateView?
Is there a way to pass a queryset into the fields collection (shown in the views.py)? My intend is to populate a select HTML element with only active members. Or is there any other way or best practice to solve this? views.py: class Orders_update(UpdateView): model = Order active_members = Member.objects.all().filter(active=True) fields = ['order_text', 'customer', 'active_members'] template_name = "orders/orders_update.html" success_url = '../../../orders' orders_update.html: {% extends "base.html" %} {% load widget_tweaks %} {% block content %} <h1>Order - Update</h1> <form class="form-group" style="width:200px" action="" method="post">{% csrf_token %} <div class="form-group"> <div class="form-group"> {{ form.order_text|add_class:"form-control" }} {{ form.customer|add_class:"form-control" }} {{ form.active_members|add_class:"form-control" }} <input class="form-control" type="submit" value="Update" /> </div> </div> </form> {% endblock %} models.py: from django.db import models from django.utils import timezone class Order(models.Model): customer = models.ForeignKey('Customer') member = models.ForeignKey('Member') order_text = models.CharField(max_length=200) pick_up = models.CharField(max_length=200) destination = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) changed_date = models.DateTimeField(blank=True, null=True) def created(self): self.changed_date = timezone.now() self.save() def __str__(self): return self.order_text class Customer(models.Model): company_name = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) changed_date = models.DateTimeField(blank=True, null=True) def created(self): self.changed_date = timezone.now() self.save() def __str__(self): return self.company_name class Member(models.Model): lastname = models.CharField(max_length=20) firstname = models.CharField(max_length=20) created_date = models.DateTimeField(default=timezone.now) changed_date = models.DateTimeField(blank=True, null=True) active = models.BooleanField(default=True) def created(self): self.changed_date = timezone.now() self.save() def __str__(self): return … -
DJANGO 1.8 Image Not Found and Media FIles Not Found
Kindly am having this error Image not found: /attachment/small?media_file=daniel/attachments/1478272263818.jpg when am accessing the image files within django 1.8 , Below is my settings.py setting and url.py Any assistance will be highly appreciated . # Main URL for the project BASE_URL = 'http://localhost' # Absolute path to the directory that holds media MEDIA_ROOT = '%s/media/' % PROJECT_ROOT print 'MEDIA_ROOT' , MEDIA_ROOT # URL that handles the media served from MEDIA_ROOT MEDIA_URL ='/media/' print 'MEDIA_URL' , MEDIA_URL and on the url.py url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), url(r'^favicon\.ico', RedirectView.as_view(url='/static/images/favicon.ico')), url(r'^static/(?P<path>.*)$', 'serve')) if settings.DEBUG: urlpatterns += patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT})) urlpatterns += patterns('django.contrib.staticfiles.views', url(r'^static/(?P<path>.*)$', 'serve')) -
Bug with graphene.Mutation?
I use graphene-django for have a GrapQL API. I have created a mutation in my schema.py: class UpdateApplication(graphene.Mutation): class Input: id = graphene.String() name = graphene.String() application = graphene.Field(ApplicationNode) @classmethod def mutate(cls, instance, args, info): name = args.get('name') rid = from_global_id(args.get('id'))[1] update_application = Application.objects.filter(id=rid).update(name=name) return UpdateApplication(application=update_application) class Mutation(ObjectType): update_application = UpdateApplication.Field() schema = graphene.Schema(mutation=Mutation) When I run this resquest, I have an error. mutation update { updateApplication(id: "QXBwbGljYXRpb25Ob2RlOjE=", name: "foo") { application { name } } } The error: mutate() takes exactly 4 arguments (5 given) I put 4 arguments in mutate() not 5... Is it a bug? -
Django 1.8 : Model Admin Form - Checkbox make one-to-one form appears and set ID
I am currently maintaining a NPO org management system that works only with Django Admin (it is a database for members, volunteers, activities etc..) Now they want to add a functionality : You have a model admin form "Person", with name, address, phone etc.. But lower in that form, it should have a checkbox that when clicked, it spoils a form for a one-to-one entity. If the checkbox is not clicked then the one-to-one is NULL. When you reload this form after saving, what you should see is : If the checkbox was clicked and sub form entered, the checkbox should be already clicked, and the form present. It is possible to do that kind of functionality with Django 1.8 ? If yes, do you have some links to recommend me ? Hints ? Thank you very much and have a great day ! -
complex annotation in django query
Current state: model.py class Foo(models.model): name = models.CharField(max_length = 50, blank = True, unique = True) class Item(models.model): foo = models.ForeignKey('Foo') number = models.PositiveIntegerField() views.py def index(request): stats= Foo.objects.filter(somecond=somevalue).\ annotate(count=Count('item__number'), max=Max('item__number')) return render_to_response('stats.html', {'stats' : stats}) And the result as expected is the list of objects Foo with additional fields: count containing the count of items related with Foo and max - the max number of item. example: Item1: Foo1, 12 Item2: Foo2, 100 Item3: Foo1, 10 Item4: Foo2, 78 Item5: Foo1, 6 Result: stats: Foo1, 3, 12 Foo2, 2, 100 Allright. Now I'd like to get more: class sell(models.Model): foo = models.ForeignKey('Foo') value = models.DecimalField(max_digits=10,decimal_places=2) filled with: sell1: Foo1, 12.50 sell2: Foo2, 12.40 sell3: Foo1, 4.12 sell4: Foo2, 10.00 stats=Foo.objects.filter(somecond=somevalue).\ annotate(Count('item__number'), Max('item__number'), Sum('sell__value')) My expectation is: stats: Foo1, 3, 12, 16.62 Foo2, 2, 100, 22.40 but the result is some kind of multiplication of number of items and values (e.g. if the sell element is one, and there is four Foos, the sum is 4*sell.value) I also tried Sum('sell__value', distinct=True) but no difference. I wanted it for template, where I want to do for loop with stats {% for foo in stats %} <h2>{{ foo.name }} </h2> {{foo.count}}/{{foo.max}} sum … -
Can not compare text with redis hash key in Django
This problem bugs me for hours. Basically I'd like to compare unicode text retrived from mysql database and hash map keys in redis. Here is the code in my views.py: topicslug = topic.slug.encode('unicode-escape') topictitle = topic.title.encode('unicode-escape') topic_link = '<a href="/topic/%s">%s</a>' %(topicslug, topictitle) topic_link = "\'" + topic_link + "\'" print 'topic_link is', topic_link key_exists = r.hexists(creator_key, topic_link ) if key_exists == 1: print 'alert key found' print 'hget', r.hget(creator_key, topic_link) r.hdel(creator_key, topic_link) print 'alert key deleted' else: print 'alert key not found' print 'hmgetall', r.hgetall(creator_key) And here is the result of prints that I get: topic_link is '<a href="/topic/\u0631\u062f\u06cc\u0633-\u062a\u0633\u062a">\u0631\u062f\u06cc\u0633 \u062a\u0633\u062a</a>' alert key not found hmgetall {'<a href="/topic/\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3-\xd8\xaa\xd8\xb3\xd8\xaa">\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3 \xd8\xaa\xd8\xb3\xd8\xaa</a>': '1'} As you can see, since the `topic_link' that I construct is in unicode but the key obtained from redis is in hex (i guess), so the do not match. I'm wondering how can I fix this so that the comparison can be performed? -
'account_tags' is not a valid tag library
I'm working on designing a web page in Python/Django, and when I try to run my program's server, I get an error message stating: TemplateServerError: 'account_tags' is not a valid tag library: Template library account_tags not found, tried django.templatetags.account_tags,django.contrib.admin.templatetags.account_tags,django.contrib.staticfiles.templatetags.account_tags,django_forms_bootstrap.templatetags.account_tags,pinax_theme_bootstrap.templatetags.account_tags,pinax_theme_foundation.templatetags.account_tags,bootstrapform.templatetags.account_tags,metron.templatetags.account_tags The problem comes from this line of code: {% load account_tags %} Does anyone know what else I can install to obtain the correct 'account_tags' library? Thanks! -
Best way to add data to database Django?
I have some app which collect data and serialize it to .json file. Fields of .json file are equals fields in database. What the best way to add this data from .json to database? Raw sql request uncomfortable, because data may be need update or add new row to database. And where better do this? In my application which collect data or in django application and how? -
Why Django change requests header to uppercase?
I just want to know why django change requests header to uppercase ? example : i send headers "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36" , at backend django change it to HTTP_USER_AGENT : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ( What's the need of this ? and why i don't get complete user agent ? Any helpful suggestion will be appreciated . -
Getting the object that is created before this object
I want a delta between two objects: class Point(models.Model): measurement = models.ForeignKey(Measurement) time = models.DateTimeField() value = models.FloatField() def delta(self): measurement = self.measurement.point_set.order_by('time') measurement = measurement[-2] return self.value - measurement.value But this obviously just works for the latest object. Is there a way to get the predecessors of the self.object in a time-wise sense? -
How to create a table with links to change boolean values of a model instance in Django?
I have a ListView where I show customer orders in multiple tables. There is one table for orders that are sent (not yet marked as 'received'), one table for 'received' orders, one for 'processed' order and one for 'delivered' orders. This list is a staff list, only certain users have access to it. What I would like to do is to add a button (link or maybe a submit button for a form) to each order row. For example, in the table for the sent orders (not yet 'received') there should be a button that says 'Mark as received' ('Kvittera' in Swedish), in the 'received' table, the button should say 'Mark as processed' ('Klar' in Swedish) and so forth. This is a picture of how I would like it to look (sorry for the Swedish): The model has three boolean fields; order_received, order_processed and order_delivered. If I were to push the button 'Kvittera' in the table, the boolean value of order_received should change from False to True, and so forth. Note that you should never be able to change it back to False. I can set up a button/link that GETs a URL, i.e. http://example.com/orders/1/receive which runs a view that … -
Django: object has no attribute 'was_published_recently'
New to Django, I've been doing the 1st tutorial and I'm at part 5 now, which is automated testing. After following the tutorial until step "Fixing the Bug", it pops up an error when I run the test, as follows: Traceback (most recent call last): File "D:\Python\Django\ui1\polls\tests.py", line 13, in test_was_published_recently_with_future_question self.assertIs(future_question.was_published_recently(), False) AttributeError: 'Question' object has no attribute 'was_published_recently' ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1) Destroying test database for alias 'default'... Whereas in the tutorial page, it shows no error in the testing. Creating test database for alias 'default'... . ---------------------------------------------------------------------- Ran 1 test in 0.001s OK Destroying test database for alias 'default'... Here's my code. tests.py import datetime from django.utils import timezone from django.test import TestCase from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): #should return False for questions whose pub_date is in the future. time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) models.py from django.db import models class Question(models.Model): question_text= models.CharField(max_length=200) pub_date=models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question= models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now -
Specified fields in ModelSerializer not being filtered
I have a simple view with "athletes" should only show a name, and id, with some extra related data. However I am getting back the entire dataset from an record. @api_view(['GET']) @permission_classes((permissions.AllowAny,)) def get_by_years(request): athletes = AthleteProfile.objects.filter(owner=request.user) grouped_athletes_iterator = itertools.groupby(athletes, lambda athlete: athlete.graduation_year) grouped_athletes = [{'graduation_year': graduation_year, 'athletes': list(athletes_iterator)} for graduation_year, athletes_iterator in grouped_athletes_iterator] athletes_by_year = AthletesByYearSerializer(grouped_athletes, many=True) return Response(athletes_by_year.data) I am expecting this format: [ { "graduation_year": 2016, "athletes": [ { "id": 215, "evaluations": [], "additionalquestions": null, "first_name": "Joseph", "last_name": "Doe", "graduation_year": 2016, "notes": "fdgdfg wew" } ] } ] Instead, it's providing all the details like: [ { "graduation_year": 2016, "athletes": [ { "id": 215, "evaluations": [], "additionalquestions": null, "first_name": "Joseph", "last_name": "Doe", "email": "joedoe@gmail.com", "date_of_birth": null, "mobile_number": "123-234-23271", "team_name": "Wildcats", "coach_name": "", "coach_email": "", "coach_number": "", "event_seen": "NA", "jersey_number": 1, "graduation_year": 2016, "rank": 2, "notes": "fdgdfg wew", "public_record": false, "notify_key": "f9781efee667d26cdeb6cead447e49bdd8a836a3", "notified_on": "2016-11-02T10:58:37.131000Z", "level_of_interest": "1", "user": null, "owner": 30, "sport_position": null, "next_step": null, "next_steps": [ 1, 2 ] } ] } ] Here is my setup for serialization: class AdditionalQuestionsSerializer(serializers.ModelSerializer): class Meta: model = AdditionalQuestions fields = ( 'id', 'communication_datetime', 'full_name', 'nick_name', 'club_name', 'favorite_position', 'general_grades', 'high_school', 'sat_date', 'area_of_interest', 'looking_for_in_university', 'looking_for_in_soccer_program', 'decision_when', 'decision_who', 'know_college_conference', ) class EvaluationSerializer(serializers.ModelSerializer): class … -
Django uniqe by date queryset filtering
I have a queryset which represent visits and now I need to filter unique visits by day for all week. class Visit(models.Model): user = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) week = timezone.now().date() - timedelta(days=7) visits = Visit.objects.filter(created_at__gte=week) How can I filter visits queryset to get unique visits per day for one week range. So if user comes 4 times in a single day, it is one unique visit. Expected result is integer which represent unique visits for a last week. -
Python ImportError: No module name 'django'
I am using Python 3.5.2 and Django. And I am following this tutorial https://www.youtube.com/watch?v=Wm8Eq0HIISA . I have the following problem: when I try to do: from django.http import HttpResponse, I get ImportError: No module named 'django' -
How to get unicode repsentaion of a arabic strings in Django?
I'm wondering how to get unicode representation of arabic strings like سلام in python? The result should be \u0633\u0644\u0627\u0645 I need that so that I can compare data stored in mysql db and data stored in redis cache.