Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Celery register task from module
I'm confused about how can I register only subset of tasks from one django app. For example we have 2 apps with set of tasks but we need to register 1 app and subset of tasks from second app. How can I achieve that? -
Django Regular expression many slugs
I have the regular expression in my url that accepts pass one slug to my view, exemple: 127.0.0.1/cart/product_slug1 But I need a regex that accept pass one or more slugs, example: 127.0.0.1/cart/product_slug1/product_slug2/product_slug3/.../product_slugN urls.py from django.conf.urls import url from . import views urlpatterns = [ url( r'^cart/add/(?P<slug>[\w_-]+)/$', views.create_cartitem, name='create_cartitem' ), It's possible send many slugs? -
functions with arguments in Django's template
I have formally construct the function in my models.py file : from datetime import datetime from django.template.defaultfilters import date as datefilter from django.utils import translation def date_customerprofile(language): now_ = datetime.today() if language == 'English': translation.activate('en') return datefilter(now_, 'l, F j, Y') else: translation.activate('fr') return datefilter(now_, 'l, j F Y') I would like to use this function in a template, but it is unclear it will work fine. I'd like to use {{ date_customerprofile('French') }}, but it didn't work. Any suggestions? Thanks in advance! -
Django to_field for ManytoMany?
(Using Django 1.10) If I have a model Person that has a field person_state with a ManytoMany relationship with model State, can I store actual names of the State in person_state instead of pk? person_state = models.ManyToManyField(State, blank=True,related_name='person_state') Looks like I can't have a to_field in ManytoManyField (which this post and the docs confirm) but I'd guess this to be a pretty common use case (i.e entities referring to other entities (in a manytomany relationship) by their names instead of pk's). Please let me know if I am thinking it incorrectly. -
Python/django display images
I'm new in django and i'm trying to create a project and i got a problem, i can't display image on next page after submit button. All i get is broken icon. Could anyone help me? ( I'm using django 1.10) selected.html {% extends 'tag/base.html' %} {% block title %}Selected{% endblock %} {% block body %} {% for tags in all_tags %} <div class=" col-md-4"> <div class="panel panel-default"> <div class="panel-body"> <img src="{{ MEDIA_URL }}{{ tags.tag_image.url}}" class="img-responsive" style="width: 60px; height:80px; margin:auto;" /> </div> </div> </div> {% endfor %} {% endblock %} urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Why heroku is deleting objects in database?
I am deploying on heroku and i sucessfully did it. but wehenever i post some data in my form and sign up the database saves the result but after a few hours it is gone here is my settings.py-(code) and here is my view function " def SignUpAction(request): if request.method == 'POST': form = Add(request.POST,request.FILES) if form.is_valid(): username = form.cleaned_data['Username'] password = form.cleaned_data['Password'] age=form.cleaned_data['age'] email = form.cleaned_data['Email'] language = form.cleaned_data['Languages'] description = form.cleaned_data['Description'] Profile_pic=form.cleaned_data["Profile_Picture"] user = User.objects.create_user(username, email, password) Person.objects.create(Name=username,age=age,Description=description,ProfilePic=Profile_pic) for i in language: Language.objects.create(user=user,Language=i) user=authenticate(username=username,password=password) login(request,user) return redirect("/home") -
Displaying more than one Google Map V3 on child templates
I have a problem displaying multiple google maps on child templates. Only first initialized map in the script is displaying, second seems to be ignored. If I place two maps on one child template everything works fine, but adding second map to an additional template is making second map not working. base.html: {% block body %} <h1>Base</h1> {% endblock %} <script> function initMap() { var uluru = {lat: 12, lng: 23}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 6, center: uluru var uluru2 = {lat: 13, lng: 24}; var map2 = new google.maps.Map(document.getElementById('map2'), { zoom: 6, center: uluru2 }); child.html: {% extends 'base.html' %} {% block body %} <div id="map"></div> {% endblock %} child2.html: {% extends 'base.html' %} {% block body %} <div id="map2"></div> {% endblock %} -
Django REST overrride destroy method to make user inactive
I'm trying to override the RetriveUpdateDestroy API view's destroy method to change the status of the user to inactive instead of deleting them. I can't seem to access the is-active field of the in built User database. views.py class UserUpdateApiView(RetrieveUpdateDestroyAPIView): queryset = UserInformation.objects.all() serializer_class = UserInformationUpdateSerializer lookup_field = 'pk' lookup_url_kwarg = 'id' serializers.py class UserSerializer(ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}, write_only=True) email = serializers.EmailField(validators=[required]) class Meta: model = User fields = ['username', 'email', 'password', 'is_active'] extra_kwargs = {'password': {'write_only': True}, 'is_active': {'read_only': True}} def validate(self, data): email = data.get('email', None) user = User.objects.filter(email=email).distinct() if user.exists(): raise ValidationError("That email is already registered!") return data class UserInformationUpdateSerializer(ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = UserInformation fields = ['user', 'first_name', 'middle_name', 'last_name', 'phone', 'date_of_birth'] models.py class UserInformation(BaseModel): user = models.OneToOneField(User, related_name='user_id') first_name = models.CharField(max_length=45) middle_name = models.CharField(max_length=45, null=True) last_name = models.CharField(max_length=45) vendor = models.BooleanField(default=False) phone = models.CharField(max_length=100, validators=[ RegexValidator(regex=r'^\+?8801?\d{9}$', message="Phone number must be entered in the format: '+8801*********'") ], blank=False, unique=True) date_of_birth = models.DateField() confirmation_token = models.CharField(max_length=45, null=True) confirmation_exp = models.DateTimeField(null=True) pw_reminder_token = models.CharField(max_length=45, null=True) pw_reminder_exp = models.DateTimeField(null=True) profile_pic = models.ImageField(blank=True, null=True, upload_to='profile_images/', default='Images/none/no_images.jpg') cover_photo = models.ImageField(blank=True, null=True, upload_to='cover_images/', default='Images/none/no_images.jpg') thumbnail_pic = models.ImageField(blank=True, null=True, upload_to='thumbnail_images/', default='Images/none/no_images.jpg') phone_verified = models.BooleanField(default=False) email_verified = models.BooleanField(default=False) reward_points = … -
Is it possible to set 2 urls in get_absolute_url?
I have next task and dont know how to make it. Web page shows to user list of objects. Every object has 2 button with urls like function_detail and function_change_history. First url need open the page about details of the object and the second url need to open the page about change history. I used get_absolute_url to make second url but dont know how to create first url cause I need to use get_absolute_url again. models.py: @reversion.register() class Function(models.Model): ***FIELDS*** def get_absolute_url(self): return reverse('project:function_change_history', args=[self.project_id, self.code]) urls.py: url(r'^(?P<project_code>[0-9a-f-]+)/(?P<function_code>[0-9a-f-]+)/change_history/$', function_change_history, name='function_change_history'), url(r'^(?P<project_code>[0-9a-f-]+)/(?P<function_code>[0-9a-f-]+)/detail/$', function_detail, name='function_detail'), Is it possible to set 2 url in get_absolute_url? -
How to perform nested list with input field in Django
class table_A (models.Model): FieldA = models.CharField(max_length=40) FieldB = models.CharField(max_length=40) # devuelve el valor del campo name y no el objeto def __str__(self): return '{}'.format(self.FieldA) I need form field (LIST table_A.FieldA) Description (INPUTTEXT table_A.FieldB)** **Depending on the value selected in the list I show the field B description -
Query Filter Django
i want to call nilai into a table in my template this is my model : class AlternatifJalur(models.Model): nama = models.CharField(max_length=100) def __str__(self): return self.nama class KriteriaJalur(models.Model): TIPE_KRITERIA_CHOICES = ( ('benefit', 'Benefit'), ('cost', 'Cost'), ) nama = models.CharField(max_length=100) bobot = models.DecimalField(max_digits = 20, decimal_places = 2) keterangan = models.TextField() tipe = models.CharField(max_length=100, choices=TIPE_KRITERIA_CHOICES, default='Benefit') def __str__(self): return self.nama class Matriks(models.Model): kriteria = models.ForeignKey(KriteriaJalur) alternatif = models.ForeignKey(AlternatifJalur) nilai = models.DecimalField(max_digits = 20, decimal_places = 2) def nilai_float(self): return float(self.nilai) this is my view : def index(request): kriteria = KriteriaJalur.objects.all() alternatif = AlternatifJalur.objects.all() matriks = Matriks.objects.all() krite = KriteriaJalur.objects.get(nama='Jarak') return render(request, 'index.html', {"kriteria":kriteria, "alternatif":alternatif, "matriks":matriks}) how to call nilai from Matriks class in my model that kriteria in my Matriks class equal to nama in my kriteria class and alternatif in my Matriks class equal to nama in my alternatif class ? -
How to fill the variables in html template in django?
I want to pass "name" to html file and get the response instead of rendering the page. I want to send this html page via email after adding the "name". <!DOCTYPE html> <html> <body> <var>{{name}}</var> </body> </html> Here is the django views code: def sending(request): -- passing request.user -- return_page = html_page(request.user) send_email(--email content--) Can someone suggest me how to do this? -
How nginx webserver is configured in open edx Cypress
I went through the etc/nginx/sites-available/default file but didn't find the configuration setup. In many Documentations explained about application but not how the webserver is configured. https://openedx.atlassian.net/wiki/display/OpenOPS/Open+edX+Operations+Home http://edx.readthedocs.io/projects/edx-installing-configuring-and-running/en/latest/index.html -
Django get_or_create returning models.DoesNotExist while importing a CSV
I have spent quite sometime to figure this out. I am simply trying to import a CSV file using Python's csv module and Django's get_or_create(). This is my simple code (built upon this code): import csv from .models import Person def import_data(): with open('/path/to/csv/people_list.csv') as f: reader = csv.reader(f) for row in reader: _, created = Org.objects.get_or_create( name=row[0], p_id=row[1], current_status=row[2], ) I get the following error when I run import_data() on the shell peoplelisting.models.DoesNotExist: Person matching query does not exist. Yes, this particular Person does not exist but isnt that the whole point of using get_or_create()? If it doesnt exist, create it? -
add action to button in crispy form
I have a django app where I am using crispy forms to create a form where the user can select a file from the hard drive and upload it to the server. I wanted to create a form with a CharField which will get updated with the file path that the user selects and an Upload button. My Django model looks like: class ZipFileModel(models.Model): zip_file = models.CharField(max_length=1000) class Meta: db_table = "uploads" The idea is that the zip_file field will get updated with the path to the file on the server. The form itself looks like: class DocumentForm(ModelForm): class Meta: model = ZipFileModel fields = ['zip_file'] def __init__(self, *args, **kwargs): super(DocumentForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( FieldWithButtons('zip_file', StrictButton('Browse', css_class="btn-primary"), StrictButton('Upload', css_class="btn-success"))) Now this shows me the fields and the buttons but I am now not sure how I can program this button. For example, how can I program the Browse button to show be a FileDialog and basically get the path to the file and update the form CharField? -
Django: one-to-one through relationship
I am aware of the existence of many-to-many through relationships, i.e: class A(models.Model): b = models.ForeignKey('B') c = models.ManyToManyField('C', thorugh='B') class B(models.Model): c = models.ManyToManyField('C') But what if the relationship between B and C was not a many-to-many relationship, but a one-to-one? class B(models.Model): c = models.ForeignKey('C') How can we set up a one-to-one through relationship between A and C? class A(models.Model): b = models.ForeignKey('B') c = models.ForeignKey('C', through='C') # this does not exist in Django Or is this not implemented at all because we can just do a.b.c and b__c in queries just fine? -
Access variables returned from function in django view with name of variable
I have a view in django that has a filter that uses two dates. I want to calculate the dates in a separate function to tidy it up a bit and return them to the view. def index(request): function = month() objectcount = Entry.objects.filter(entrydate__range=(function[0], function[1])).count() #bleurgh! context = { "objectcount": objectcount, } return render(request, 'entry/index.html', context) def month(): today = datetime.datetime.now().date() first_of_month = "{}-{}-01".format(today.year, today.month) last = calendar.monthrange(today.year, today.month)[1] last_of_month = "{}-{}-{}".format(today.year, today.month, last) return first_of_month, last_of_month This works fine, but I have to access the variables using function[0] and function[1]. How can I pass these variables so they are accessed from the index view using names - like first_of_month and last_of_month? -
Django: relationship with multiple intermediaries
I have the following relationships: +---------------+ | | | HomeVenue | | | +-------+-------+ * | | | | 1 | | +-------+-------+ +-------------------+ +--------------+ | | 1 1 | | 1-* 1 | | | Team +----------+ Registration +------------+ Season | | | | | | | +---------------+ +-------------------+ +--------------+ I know I can set up a many-to-many relationship thorugh an intermediary model. For example, I could get the teams in a season through registration: class Season(models.Model): teams = models.ManyToManyField('Team', through='Registration') However, I am trying to go a step further: is it possible to set up such a relationship with two intermediary models? I am trying set up a relationship between the HomeVenue model and Season. I could define a @property to get the value I am after, but it would be convenient to have it as a field in order to be able to use it in queries. I cannot do the following, because the Team model is between them. class HomeVenue(models.Model): season = models.ManyToManyField('Season', through='Registration') So, is what I am asking even possible? PS: some of you might comment the Team and Registration model can be merged into one because of the one-to-one relationship. And I agree, … -
show a html for Password Reset in django rest framework
I'm trying to do a password reset. I'm using this here from Djoser. The point is that I have to pass an URL where the user should enter his new pass. URL: /password/reset/confirm/ exactly: http://127.0.0.1:8000/#/password/reset/confirm/Mg/4kh-420dd9606aa6d481bd4a where Mg is an id and 4kh... is a token I get the email with the uri, but I don't know how to show it on Django Rest Framework... I thought it would be easy, but I'm not getting it. I followed this part of the docu. And tried this: views.py class PassReset(viewsets.ModelViewSet): renderer_classes = [TemplateHTMLRenderer] queryset = User.objects.all() # This is just testing serializer_class = UserSerializer # This is just testing template_name = 'pass_reset.html' permission_classes = (permissions.AllowAny,) pass_reset.html <html><body> <h1>Profiles</h1> <ul> Hello World! </ul> </body></html> settings.py TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, "html_templates/")], ... ], }, }, ] and I'm trying to get the page so: http://127.0.0.1:8000/users/pass-reset/ Just for seeing if it works, and I get this error: ValueError: dictionary update sequence element #0 has length 7; 2 is required But is not about the error, I think I should do it in other way I don't know. Maybe someone there had to do something like that. -
Limit Django database table size and transfer data to another table
So, I have a Django app which parses data from couple of websites (every 1-2 seconds it receives JSON array ~20-50 Kb) and writes it to default Django SQLite3 database table. For my purposes I need only 15-20 last records in this table and I'm afraid that it will be too large very soon because, for example, even after 24 hours it will be at least 800 Mb. How can I make my app automatically transfer records that are older than last 15-20 to another table (let's call it archive table)? Thank you! -
Ploting pie chart in django by highcharts
I am trying to plot pie chart in django.My Django model "Results" has two filed like below: +--------+------------+ | result | date | +--------+------------+ | passed | 2017-03-30 | | passed | 2017-02-30 | | passed | 2017-03-30 | | failed | 2017-03-30 | | failed | 2017-03-29 | | passed | 2017-03-29 | | passed | 2017-03-30 | ----------------------- I would like to count following way and show this in pie chart as total number of passed and failed value. 2017-03-30 passed-4 and failed-1 chart_test.html: {% extends "base.html" %} {% load staticfiles %} {% block content %} <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script src="http://code.highcharts.com/highcharts.js"></script> </head> <body> <script type="text/javascript"> $(function () { $('#chart_container').highcharts({ chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, type: 'pie' }, title: { text: 'hello' }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {point.percentage:.1f} %', style: { color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black' } } } }, series: [{ name: 'Brands', colorByPoint: true, data: [ {% for cat in responses_pie %} [ {{ cat.count }} ], {% endfor %} ] }] }); }); </script> <div id="chart_container" style="height: 300px"></div> </body> {% endblock %} views.py: def chart_test(request): responses_pie … -
Django : sort by distance, spatialite does not load C extentions
I want to filter results according to their distance so I used GeoDjango and added a field PointField to my model: from django.contrib.gis.db import models location = models.PointField(u"longitude/latitude", geography=True, blank=True, null=True) However, I have this error in my browser when trying to launch the index (my web site) ImproperlyConfigured at / The pysqlite library does not support C extension loading. Both SQLite and pysqlite must be configured to allow the loading of extensions to use SpatiaLite. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.10.6 Exception Type: ImproperlyConfigured Exception Value: The pysqlite library does not support C extension loading. Both SQLite and pysqlite must be configured to allow the loading of extensions to use SpatiaLite. Exception Location: /Users/mac/ostadienv/lib/python3.5/site packages/django/contrib/gis/db/backends/spatialite/base.py in get_new_connection, line 52 Python Executable: /Users/mac/ostadienv/bin/python Python Version: 3.5.0 and this in python: 'The pysqlite library does not support C extension loading. ' django.core.exceptions.ImproperlyConfigured: The pysqlite library does not support C extension loading. Both SQLite and pysqlite must be configured to allow the loading of extensions to use SpatiaLite. Knowing that I'm working on a MAC -
Alternative for wsgiref for python 3
I am new to Django development. The project which I am working is using wsgi and wsgiref. While upgrading python2 to python3 I am facing issue with wsgiref module. It not installing properly because of the syntax error. Is there any solution for this . Or do I need to use alternative for this ?? -
using django authentication and session on remote front end
I have a website that front-end and back-end are on different servers. Front-end part is on angular 2 and webpack and gets dynamic data from back-end using ajax. Back-end uses django framework for database management and ORM. Is it possible to use django authentication and session management and Auth.User model for the front-end in back-end part? -
How to properly hyperlink class-based views in Django documentation generator?
Django documentation shows information on how to make link to the view, but not class-based view. When I do: """ Redirects to :view:`accounts.ProfileDetailView` """ It shows link with url to: /admin/doc/views/accounts.profiledetailview/, but the actual docs page for the class-based view is /admin/doc/views/accounts.views.ProfileDetailView/ (i.e. with good case sensitivity and also .views in the middle). I can easily add .views into the string, but cannot force the case sensitivity. Am I able to fix it? How?