Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django No module name found although I already pip install
I am using this for push notification and it is okay on my locahost. https://github.com/jleclanche/django-push-notifications But when I deploy to server, I did pip install django-push-notifications But in my settings.py, when I add this, it crash and it say server configuration is wrong. How shall I do? INSTALLED_APPS = ( 'push_notifications' ) -
Django i18n/setlang/ response stuck pending
I came up to this problem: the HttpResponseRedirect of the /i18n/setlang/ never reaches my browser. The request is loading indefinitely. Code of the form: <form class="langForm" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select name="language" style="display:none;"> <option value="fr" selected="selected"></option> </select> <input class="langInput" type="image" src="/static/core/flag_fr.png"/> </form> First thing, it works perfectly fine on my development server which shares the exact same code. Secondly, it used to work with this configuration, it just suddenly stopped working. If I give it no csrf token using another http client than my browser, it returns a 403. I also went and printed the response in the function right before the return and it works too, no infinite loop. It gives me something like (status code 302): [Sat Oct 01 15:11:49 2016] [error] Content-Type: text/html; charset=utf-8\r [Sat Oct 01 15:11:49 2016] [error] Location: http://example.com/\r [Sat Oct 01 15:11:49 2016] [error] \r There is no trace of the setlang request in apache other vhosts access log. I restarted both my Apache and wsgi application and nothing changed. I would gladly take any help or suggestions. My server works with Apache2.2 on Debian. Django version 1.9 Python version 2.7 Other settings: … -
Extract Python dictionary from string
I have a string with valid python dictionary inside data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc." I need to extract that dict. -
Regexp for several URLs
I use this module in Django: https://github.com/ottoyiu/django-cors-headers There is setting (CORS_URLS_REGEX) to allow CORS URLs which I cant configure. I need to combine in one regex: r'^/api/general/enterpriseinfo/$' and r'^/api/general/availabletime/$' How can I do it? (Later probably I will need to add other similar URLs in to this regex.) Thanks! -
How to create new page in WagTail?
I started to work with WagTail CMS, and i cant create pages like Homepage from __future__ import absolute_import, unicode_literals from django.db import models from wagtail.wagtailcore.models import Page class HomePage(Page): pass #here is a new page declaration class ProjectPage(Page): def get_template(self, request): return 'project/project_page.html' i created project/project_page.html document in home/templates. After this i runned python manage.py makemigrations and python manage.py migrate. But when i add a child page of project page in admin panel and click on live button to acces them i'm redirected on this url: http://127.0.0.1:8000/admin/None/ -
Reverse Nested Relationship Serialization in django rest framework
I am working on a deals/coupon selling website. I have following models, (excluding extra details). class Order(models.Model): email = models.EmailField(max_length=200, null=False) phone_number = models.CharField(max_length=10, null=False) shipping_address = models.TextField(blank=True,null=True) coupon_code = models.CharField(max_length=20,null=True,blank=True) gross_total = models.FloatField(default=0.0) class Meta: db_table = 'order' class OrderDetail(models.Model): order = models.ForeignKey(Order,related_name='order_details') package = models.ForeignKey(Package) quantity = models.IntegerField(null=False) unit_price = models.FloatField(default=0.0) class Meta: db_table = 'order_detail' class Coupon(models.Model): order_detail = models.ForeignKey(OrderDetail,related_name='coupons') code = models.CharField(max_length=200, null=False, unique=True) maximum_usage_count = models.IntegerField(null=False) used_count = models.IntegerField(default=0) valid_from = models.DateTimeField(null=False) valid_to = models.DateTimeField(null=False) class Meta: db_table = 'coupon' My serializers for these are, class CouponSerializer(serializers.Serializer): class Meta: model = Coupon fields = ['id', 'code', 'maximum_usage_count', 'used_count', 'valid_from', 'valid_to', 'created_at', 'updated_at', 'is_active'] class OrderDetailSerializer(serializers.Serializer): coupons = CouponSerializer(read_only=True) class Meta: model = OrderDetail fields = ['id', 'package', 'quantity', 'unit_price', 'created_at', 'updated_at', 'is_active'] class OrderSerializer(serializers.ModelSerializer): order_details = OrderDetailSerializer(read_only=True,many=True) class Meta: model = Order fields = ['id','email', 'phone_number', 'shipping_address', 'coupon_code', 'gross_total','order_details'] In my listapiview, for fetching all orders, I have specified the order serializer. The api is working fine but is not able to serialize the reverse relation ship models. I am getting following response. { "id": 31, "email": "ff@b.com", "first_name": "ff", "last_name": "ff", "phone_number": "ff", "shipping_address": "", "coupon_code": "", "gross_total": 1.0, "payment_method": "ONLINE", "order_status": "PLACED", "created_at": … -
how to have "city" fields depending on "country" field in Django models, without creating their tables
I know there are several questions asked like this (such as this one), but non of them could help me with my problem. I wanna have a City and a Country field in my models, which the City choices is depended on Country; BUT I do not want to define City and Country as models classes. here is my code : from django.contrib.auth.models import User from django.db import models from django.forms import ChoiceField from django_countries.fields import CountryField class UserProfile(models.Model): user = models.OneToOneField(User, related_name="UserProfile") name = models.CharField(max_length=30, null=False, blank=False) picture = models.ImageField(upload_to='userProfiles/', null=False, blank=False) date_of_birth = models.DateTimeField(null=False, blank=False) country = CountryField() # city = ?? national_code = models.IntegerField(max_length=10, null=False, blank=False) email = models.EmailField() def __str__(self): return '{}'.format(self.user.username) def __unicode__(self): return self.user.username just like field "country" which is country = CountryField(), I wonder if there is a way that I could do the mission without defining the class Country(models.Model) or class City(models.Model) -
Django paginator not showing anything
Django paginator not showing anything no error . but still result is none . def question(request): objects = ['john', 'paul', 'george', 'ringo'] paginator = Paginator(objects, 2) pList = paginator.page(1).object_list return render(request, 'app/question_list.html', { 'pList ': pList , 'objects':objects}) and html <tbody> {% for name in pList %} <tr> <td>{{ name }}</td> </tr> {% endfor %} now the page should have a list of names but instead it has nothing it acts like empty list . i checked page number , range etc everything is right ex: <tbody> {% for name in objects %} <tr> <td>{{ name }}</td> </tr> {% endfor %} object are rendered fine but the issue is with Paginator do not know what i am missing . Using python 2.7 with django 1.10 on Window 10 -
How to get child objects field in django
I writing a django app and I need to access child objects field in admin and templates: my models: class House(models.Model): doc_code = models.IntegerField() ... def getGuardian(self): guardian = self.person_set.filter(membership=1) return guardian def __str__(self): return "Family: " + str(self.doc_code) class Person(models.Model): family = models.ForeignKey(House) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) ... def __str__(self): return self.last_name + ' ' + self.first_name in view: houses = House.objects.order_by('doc_code') in template: <li>{{house.doc_code}} {{house.getGuardian}}</li> I receive: 1 [<Person: Smith John>] How can I get rid of "[ < Person:....> ]" and just display the name? Also how can I change the title of field getGuardian in Admin Page? -
Django /admin/ Page not found (404)
I have the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Raised by: nw.views.post_detail But I can enter in example to http://127.0.0.1:8000/admin/nw/ And if I remove all post_detail functions/parts of the code then I can enter to http://127.0.0.1:8000/admin/ and it works, so something with this post_detail is wrong. nw.views.post_detail: def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) context = { "instance": instance, } return render(request, "post_detail.html", context) urls.py: urlpatterns = [ url(r'', include('nw.urls', namespace='posts')), url(r'^admin/', admin.site.urls), ] and urlpatterns = [ url(r'^$', post_list, name='list'), url(r'^create/$', post_create), url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'), url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'), url(r'^(?P<slug>[\w-]+)/delete/$', post_delete), ] post_detail.html: {% extends 'base.html' %} {% block head_title %}{{ instance.title }} | {{ block.super }}{% endblock head_title %} {% block content %} <div class="instance"> <h1>{{ instance.title }}</h1> <div class="date">{{ instance.published }}</div> <p>{{ instance.text|linebreaksbr }}</p> <a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"> Facebook </a> <a href="https://twitter.com/home?status={{ share_string }}%20{{ request.build_absolute_uri }}"> Twitter </a> <a href='https://plus.google.com/share?url={{ request.build_absolute_uri }}'>google</a> <a href="https://www.linkedin.com/shareArticle?mini=true&url={{ request.build_absolute_uri }}&title={{ instance.title }}&summary={{ share_string }}&source={{ request.build_absolute_uri }}"> Linkedin </a> <a href="http://www.reddit.com/submit?url={{ request.build_absolute_uri }}&title={{ share_string }}.">Reddit</a> </div> {% endblock %} models.py: class Post(models.Model): author = models.ForeignKey('auth.User', default=1) title = models.CharField(max_length=200) slug = models.SlugField(unique=True) text = models.TextField() published = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.title … -
Which is the better location to compress images ? In the browswer or on the server?
I have a Django project and i allow users to upload images. I don't want to limit image upload size for users. But want to compress the image after they select and store them. I want to understand which is better: Compress using java-script on the browser. Back end server using python libraries. Also it will be helpful if links can be provided to implement the better approach. -
Python Django: Opening and ending tag mismatch: link line 0 and head
Here the code with this error {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="IE=edge" http-equiv="X-UA-Compatible"> <meta content="width=device-width,initial-scale=1" name="viewport"> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/font-awesome.min.css' %}"> <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script> </head> #error line <body> .... Let me know if I am missing anything. or what should I do to resolve this issue. -
Filter model objects, then select a ForeignKey field
I have these models in Django: class Person(models.Model): ... class Group(models.Model): ... class Membership(models.Model): person = models.ForeignKey(Person, related_name='memberships') group = models.ForeignKey(Group, related_name='memberships') is_admin = models.BooleanField(default=False) I want a Group method that returns the admins, as a list of Person instances. These are the two solutions I found: class Group(models.Model): ... @property def admins1(self): admin_ids = list(self.memberships.filter(is_admin=True).values_list('person', flat=True)) return list(map(lambda ai: Person.objects.get(pk=ai), admin_ids)) @property def admins2(self): admin_memberships = list(self.memberships.filter(is_admin=True)) return list(map(lambda am: am.person, admin_memberships)) Do you have a better idea, e.g. a QuerySet method like values_list that keeps Person instances instead of person_ids? -
Can not access Highcharts chart from container, so I can't change data in a chart dynamically
I rendered a chart to container in $(document).ready(). After that, I used the method mentioned here(How can i get access to a Highcharts chart through a DOM-Container), But it said that the chart is not defined. Below is my javascript code. $(document).ready(function () { $('#container').highcharts({ // ignore some option here series: [{ data: [] }] }); }); function draw_plot(original_data) { var chart = $("#container").highcharts(); // chart is not defined chart.series[0].setData(original_data, false); } I am using django as my web framework. Below is my html code. {% load static %} <head> <!-- load .js here --> </head> <body> <div id="container"></div> <script> draw_plot({{ original_data }}) </script> </body> And my views.py def index(request): template = loader.get_template('plot_example/example.html') x, y = synthesize_data() original_data = np.column_stack((x, y)).tolist() context = { 'original_data': original_data, } return HttpResponse(template.render(context, request)) My primary purpose is to change the chart data dynamically. So are there any other solutions if this problem can't be solved. -
Assign field from related model as default in another model
How can i assign the default value of current_amount as minimum_price? class Auction(models.Model): minimum_price = models.PositiveIntegerField() ..... class Bid(models.Model): product = models.ForeignKey(Auction, related_name='auction') # i want to set this field's default to value of minimum_price from Auction model current_amount = models.PositiveIntegerField(default=product__minimum_price) #also tried default=product.minimum_price How can i achieve this? -
No module named django-extensions
I need help.I am trying to run a django project that requires django-extensions module.i did pip install django-extensions and also in settings.py INSTALLED_APPS = ( .... 'django_extensions', ) but when i try to run the server it says "Import Error,No module named django-extensions.What could be the problem ? -
django.db.utils.ProgrammingError: relation already exists on OenBSD vps
I am getting this error. I tried with migrate --fake default but it doesn't seems to be working. attached is output of "python manage.py migrate" My set up is Django 1.6 + celery3.1.12 + postgresql + gunicorn on OneBSD VPS. Running migrations for users: - Migrating forwards to 0007_auto__del_field_profile_weekly_digest__del_field_profile_daily_digest_. > users:0001_initial FATAL ERROR - The following SQL query failed: CREATE TABLE "users_user" ("id" serial NOT NULL PRIMARY KEY, "password" varchar(128) NOT NULL, "last_login" timestamp with time zone NOT NULL, "email" varchar(255) NOT NULL UNIQUE, "name" varchar(255) NOT NULL, "is_active" boolean NOT NULL, "is_admin" boolean NOT NULL, "is_staff" boolean NOT NULL, "type" integer NOT NULL, "status" integer NOT NULL, "new_messages" integer NOT NULL, "badges" integer NOT NULL, "score" integer NOT NULL, "full_score" integer NOT NULL, "flair" varchar(15) NOT NULL, "site_id" integer NULL) The error was: relation "users_user" already exists Error in migration: users:0001_initial Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/home/jay/biostar-central/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/home/jay/biostar-central/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/jay/biostar-central/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/home/jay/biostar-central/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute output = self.handle(*args, **options) File "/home/jay/biostar-central/lib/python2.7/site-packages/south/management/commands/migrate.py", line 111, in handle ignore_ghosts = ignore_ghosts, File "/home/jay/biostar-central/lib/python2.7/site-packages/south/migration/__init__.py", line 220, in … -
Hook in oauth2 code with DRF
I am trying to build an app which has user login and signup functionality. I can create login and signup both from django and DRF but could not hook in oAuth2 with DRF to make it functional. I have no idea where should i use it. Should i generate token on signup or login? How can i make it functional? Here is my code serializers.py class UserSerializer(ModelSerializer): class Meta: model = User class UserCreateSerializer(ModelSerializer): email = EmailField() username = CharField() first_name = CharField(required=False) last_name = CharField(required=False) password = CharField() confirm_password = CharField() class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'password', 'confirm_password' ] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data['username'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] email = validated_data['email'] password = validated_data['password'] confirm_password = validated_data['password'] user_obj = User( username = username, first_name = first_name, last_name = last_name, email = email ) user_obj.set_password(password) user_obj.save() return validated_data class UserLoginSerializer(ModelSerializer): username = CharField() class Meta: model = User fields = [ 'username', # 'email', 'password', # 'token', ] extra_kwargs = {"password": {"write_only": True} } def validate(self, data): return data views.py class UserCreateAPI(CreateAPIView): serializer_class = UserCreateSerializer queryset = User.objects.all() permission_classes = [AllowAny] class UserLoginAPI(APIView): permission_classes = … -
Sync Django models with REST API
I'm working on a Django project where I have models replicating the data provided by a REST API to store this information in a database. I've been searching what would be the best way to do a one-direction sync with this JSON-response. So if the data changes at the external source, the local data should be updated. But I won't be changing the data myself. Although I would suspect this is a fairly common programming problem, I can't find the best way to build this synchronisation between the external source and local database. I've been looking at the Django Rest Framework but can't figure out how to use this for my purpose. -
Align ordered list elements paragraph indent google doc (by using Django i am rendering to google doc)
I am rendering below html to google doc. While I tested in html to document converters it works fine but while am doing with my code same html is align's wrong. <!DOCTYPE html> <html> <body> <p></p> <p>&nbsp;</p> <p>{% if DiffuserType == "AFD270" or DiffuserType == "AFD350" %}</p> <p style="text-align: center;"><strong>SECTION 46 51 31 </strong></p> <p>&nbsp;</p> <p style="text-align: center;"><strong>MEMBRANE DISC FINE BUBBLE RETRIEVABLE DIFFUSED AERATION SYSTEM RETRIEVABLE</strong></p> <p>{% endif %} {% if DiffuserType == "AFTS2100" or DiffuserType == "AFTS3100" %}</p> <p style="text-align: center;"><strong>SECTION 46 51 33 </strong></p> <p>&nbsp;</p> <p style="text-align: center;"><strong>RETRIEVABLE MEMBRANE TUBE FINE BUBBLE RETRIEVABLE DIFFUSED AERATION SYSTEM</strong></p> <p>{% endif %} {% if DiffuserType == "Wide Band" or DiffuserType == "Relia-Ball" %}</p> <p style="text-align: center;"><strong>SECTION 46 51 21</strong></p> <p>&nbsp;</p> <p style="text-align: center;"><strong>RETRIEVABLE COARSE BUBBLE DIFFUSED AERATION SYSTEM</strong></p> <p>{% endif %}</p> <p>{{ NamedVendors }}<br /> SSI Aerations</p> <p>PART 1 GENERAL</p> <ol> <li>SCOPE OF WORK <ol type="A"> <li>Furnish all labor, materials, equipment and incidentals required to install,complete and prepare for operation a {% if DiffuserType == "Wide Band" or DiffuserType == "Relia-Ball"%} non-clog {% endif %} diffused aeration system for installation in a {{Basintype}} of a wastewater treatment plant.</li> <li>The scope shall include but not be limited to: <ol type="a"> <li>Air distribution … -
Django - Getting 'Required argument 'year' (pos 1) not found' error when trying to use datetime
My model has this in it: start_date = models.DateField(default=datetime.date, blank=True) stop_date = models.DateField(default=datetime.date, blank=True) In my view I have: start_date = datetime.date(int(request.POST.get('start_year')), convert_month_to_int(request.POST.get('start_month')), int(request.POST.get('start_day'))) end_date = datetime.date(int(request.POST.get('end_year')), convert_month_to_int(request.POST.get('end_month')), int(request.POST.get('end_day'))) before I save to the DB. And the HTML is this: <label class="col-md-4"> Start Date: </label> <select class="selectpicker" data-width="auto" name="start_month" id="start_month" required> {% for month in month_list %} <option value="{{ month }}" {% if path_start and path_start.1 == month %} selected {% endif %}> {{ month }} </option> {% endfor %} </select> / <select class="selectpicker" data-width="auto" name="start_day" id="start_day" required> {% for day in day_list %} <option value="{{ day }}" {% if path_start and path_start.2 == day %} selected {% endif %}> {{ day }} </option> {% endfor %} </select> / <select class="selectpicker" data-width="auto" name="start_year" id="start_year" required> {% for year in year_list %} <option value="{{ year }}" {% if path_start and path_start.0 == year %} selected {% endif %}> {{ year }} </option> {% endfor %} </select> </div> <div class="row"> <label class="col-md-4">End Date: </label> <select class="selectpicker" data-width="auto" name="end_month" id="end_month"> {% for month in month_list %} <option value="{{ month }}" {% if path_end and path_end.1 == month %} selected {% endif %}> {{ month }} </option> {% endfor %} </select> / <select class="selectpicker" … -
Python web services using Django
I have a project in which the user will send an audio file from android/web to the server. I need to perform speech to text processing on the server and return some files to the user back on android/web. However the server side is to be done using Python. Please guide me as to how it could be done? -
How to render a uploaded file in django?
I made a django app that takes input image from the user and provides the path as to where the file is.I want this image to be rendered on a html page.Any comments/ideas -
How to call a view function with argument from template and return a python object in Django?
Here is the questions now I want call a view function from template/html with argument the function most like def function(PageToken,ID): '''Do Something Here''' comments = [[User1,Comment1],[User2,Comment2]] return comments And how I call this function and Use like {%for comment in comments %} <li> {{comment.1}} {{comment.2}} </li> {%endfor%} And I dont want Reload the page how to do that -
Django and wordpress on nginx 404 error
I have a django running on example.com, i need add a Wordpress to my server, would be example.com/blog, perhaps doesnt work (404 error): listen 80; server_name www.example.com; location ^~ /blog/ { root /www/blog; index index.html index.htm index.php; try_files $uri =404; location ~ \.php { root /www/blog; fastcgi_split_path_info ^(.*\.php)(.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; fastcgi_pass 127.0.0.1:9000; } } location / { uwsgi_pass unix:/tmp/myapp.sock; include /www/webapp/system/uwsgi_params; # the uwsgi_params file you installed uwsgi_read_timeout 300; }