Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I pass a user in a POST request to a django view?
I have a view AccountRegister that creates a new user. Every time I enter values into the Registration Form, a verification email is sent to the user if a user has registered with email, and verification token is sent to the user if a user has registered with a phone, and both if a user has registered with both. After successful registration, User is redirected to a Token Verification Page. To verify a token, I need to access the user from TokenVerificationView. How do I send user via request? How do I access the same user from TokenVerificationView? class AccountRegister(CreateView): model = User form_class = forms.RegisterForm template_name = 'account/signup.html' success_url = reverse_lazy('account:verification') def form_valid(self, form): self.user = form.save(self.request) if self.user.email: send_email_confirmation(self.request, self.user) if self.user.phone: device = self.user.verificationdevice_set.create( unverified_phone=self.user.phone) device.generate_challenge() message = _("Verification Token sent to {phone}") message = message.format(phone=self.user.phone) messages.add_message(self.request, messages.SUCCESS, message) return super().form_valid(form) -
how to import Bootstrap
I saw some examples,bu it don't solve my problem! Any help will be Appreciated.... -
Interpolating dates between start/end dates: Best to do in Django's view or D3?
I am new to D3 and am trying to build a stacked date series plot with around 10 elements. Initially I will linearly distribute the costs over each time period (however, other distributions would be nice to consider in the future). My goal is to have pages which display time-series plots with use either all series' or just a subset. My Django model has the parameters of each stored in the (SQLite) database like this: class Project(models.Model): #... S1_start=models.CharField(max_length=8, blank=True) S1_end=models.CharField(max_length=8, blank=True) S1_cost=models.DecimalField(max_digits=9, decimal_places=2) #S2_start ... From what I've been reading, I can see two possible ways of doing this. My question is: Are either of the below approaches recommended over the other? For each of these S groups: Interpolate Panda Dataframe When any updates are made to a Project entity, create elements for each date (date_range()) and divide the costs over the number of days Store each S in a Pandas DataFrame and pickle it to a static file On requests to a graphic's URL, unpickle the DataFrame and send over the required elements (as JSON array?) Interpolate with D3 When any updates are made to a Project entity, just save the three parameters for each S (start,end,cost) back … -
How to create a one to many relationship betwee users and sessions where user is on one's side and session on many's side?
Hi I am creating a django application where I wanted to save some dictionaries for each log in session of a user.I am saving these dictionaries in django Sessions. Now I need to associate these sessions with the user like the following. When the user logs in a list of his past sessions should be shown and he can either select to load one of them or create a new session. When he logs out he is asked whether save current session or not. What is the best way to achieve this? -
Django can't recognize bash variable even if I export it
I have an environment variable exported in bash. Project is in localhost. OS is Debian 9 Stretch. When I run, in command line: python -c "import os; print(os.environ.get('EMAIL_PASSWORD'))" I get the variable value. But, inside Django, calling os.environ.get('EMAIL_PASSWORD') returns None. In settings: EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') Already find n similar questions, but in general the problem is that the variable wasn't exported to environment. What I am missing? -
Django graphene mutation mapping error
I'm playing with django and graphene, and when I execute python manage.py runserver I get the following exception: class Tire(models.Model): width = models.IntegerField() def __str__(self): return self.width class TireType(DjangoObjectType): class Meta: model = Tire interfaces = (relay.Node,) class CreateTire(relay.ClientIDMutation): tire = Field(TireType) class Input: width = Int(required=True) @classmethod def mutate_and_get_payload(cls, input, context, info): tire = Tire( width=input.get('width') ) # tire.save() return CreateTire(tire=tire) class Mutation(ObjectType): new_tire = CreateTire.Field() ... class Mutation(data.schema.Mutation, graphene.ObjectType): # This class will inherit from multiple Queries # as we begin to add more apps to our project pass schema = graphene.Schema(query=Query, mutation=Mutation) When I remove the mutation code and just work with the query (don't include) the server is running and I can query the GraphQL API. What am I doing wrong? -
Django: How to return queryset where item attribute choice_set IS NOT empty?
FILE models.py # Create your models here. import datetime from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('data 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 FILE views.py class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): """ Excludes any questions that aren't published yet. """ return Question.objects.filter(pub_date__lte=timezone.now()) Create Question in database using python: from django.utils import timezone from polls.models imoprt Question, Choice q1 = Question.objects.create(pub_date=timezone.now(), question_text="1+1=?") q1.choice_set.create(choice_text="A. 1") q1.choice_set.create(choice_text="B. 2") q2 = Question.objects.create(pub_date=timezone.now(), question_text="8+2=?") In Function get_queryset, how to return queryset that question does have choices ? For example, Queryset INCLUDE q1(two choices), but EXCLUDE q2(without choice). THX! -
try except not working in forms.py in virtuaenve django+mod_wsgi
Whenever I put try except block in forms.py my website doesn't work . Its hosted on vps with django+mod_wsgi in virtual env using django1.11 and python 3.6. However views.py try except is not a problem The moment i comment the try and except in forms.py it works fine. Its working fine in dev environment without mod_wsgi Any advice/suggestions how do i handle exceptions. Pls guide Thank you -
How can I use a multidate picker widget in django 1.11.3?
I am trying to implement a functionality which requires me to have multiple dates stored in a model field. Let me know if it is possible -
Trouble with webpack on digitalocean server
I'm trying to set up webpack so I could use reactjs as my front end-framework on a Django Application. So far, I've successfully set up my django app and got everything working fine. However, I'm now having trouble just bundling my webpack. I keep getting this error when typing node_modules/.bin/webpack --config webpack.local.config.js Error: Deprecation notice: CommonsChunkPlugin now only takes a single argument. Either an options object *or* the name of the chunk. Example: if your old code looked like this: new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js') You would change it to: new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' }) The available options are: name: string names: string[] filename: string minChunks: number chunks: string[] children: boolean async: boolean minSize: number at new CommonsChunkPlugin (/usr/local/lib/node_modules/webpack/lib/optimize/CommonsChunkPlugin.js:10:10) at Object.<anonymous> (/home/django/django_project/webpack.base.config.js:22:5) at Module._compile (module.js:410:26) at Object.Module._extensions..js (module.js:417:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Module.require (module.js:354:17) at require (internal/module.js:12:17) at Object.<anonymous> (/home/django/django_project/webpack.local.config.js:6:14) at Module._compile (module.js:410:26) root@django-1gb-nyc3-01:/home/django/django_project# node server.js /home/django/django_project/webpack.base.config.js:22 var path = require("path") ^^^ SyntaxError: Unexpected token var at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:374:25) at Object.Module._extensions..js (module.js:417:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Module.require (module.js:354:17) at require (internal/module.js:12:17) at Object.<anonymous> (/home/django/django_project/webpack.local.config.js:6:14) at Module._compile (module.js:410:26) at Object.Module._extensions..js (module.js:417:10) This how my webpack.local.config.js looks var path = require("path") var webpack … -
Erro while running Django project in python files
I am trying to run a django app, un a virtualenv, but by running python manage.py runserver I face this error: File "/home/sahar/Rtis/rtisenv/local/lib/python2.7/site-packages/tinymce /widgets.py", line 16, in from django.forms.utils import flatatt ImportError: No module named utils could anyone help to solve this problem? I've been searchin through the net a long time and steel no change! -
Write JSON into Excel and send in response API
I am stuck in a problem that I need to send the excel file in the response of an API but the data is a huge amount. The data is coming from Django model query and then I am iterating it and saving to a variable like: data=[ { 'title': 'xxxx', 'website': 'xxxx', 'state': 'CA ', 'second_followup': None, 'fourth_followup': datetime.datetime(2017-5-3-0-0-tzinfo=<UTC>), 'first_followup': None, 'first_reponse': '', 'type': 'a', 'email_status': 'xxx', 'team_size': 0, 'second_reponse': '', 'bed_count': 0, 'created_at': datetime.datetime(2016-8-30-0-0-tzinfo=<UTC>), 'aum': 0, 'bounce': None, 'lead_status': 'xxxx', 'founded_year': '0000', 'third_followup': None, 'last_name': 'xxxx', 'address': 'xxxx', 'email': 'xxxx', 'created_by': 'xxxx', 'specialties': 'xx', 'response_date': None, 'first_name': 'xxxx ', 'zip': 'xxxx', 'company_source': 'xxxx', 'revenue': 5.0, 'company_name': 'xxxx', 'fax_number': '0', 'inital_contact': datetime.datetime(2017-5-3-0-0-tzinfo=<UTC>), 'contact_number': '0', 'domain1': 'xxx', 'city': '0', 'country': 'USA', 'industry': 'xxx', 'department': 'a', 'domain2': 'xxx', 'contact_source': 'xxx', 'fifth_followup': None }, { 'title': 'xxxx', 'website': 'xxxx', 'state': 'CA ', 'second_followup': None, 'fourth_followup': datetime.datetime(2017-5-3-0-0-tzinfo=<UTC>), 'first_followup': None, 'first_reponse': '', 'type': 'a', 'email_status': 'xxx', 'team_size': 0, 'second_reponse': '', 'bed_count': 0, 'created_at': datetime.datetime(2016-8-30-0-0-tzinfo=<UTC>), 'aum': 0, 'bounce': None, 'lead_status': 'xxxx', 'founded_year': '0000', 'third_followup': None, 'last_name': 'xxxx', 'address': 'xxxx', 'email': 'xxxx', 'created_by': 'xxxx', 'specialties': 'xx', 'response_date': None, 'first_name': 'xxxx ', 'zip': 'xxxx', 'company_source': 'xxxx', 'revenue': 5.0, 'company_name': 'xxxx', 'fax_number': '0', 'inital_contact': datetime.datetime(2017-5-3-0-0-tzinfo=<UTC>), 'contact_number': '0', 'domain1': … -
Set maximum default value for a Django model FloatField
How can I set the maximum value an FloatField can hold in a Django model? price_upper_bound = models.FloatField(null=True, blank=True, default=0) Here I want to set maximum float value as a default value for this field. I can set it up manually as any random maximum like 2147483647 (https://www.postgresql.org/docs/9.1/static/datatype-numeric.html). Is there any default maximum constant? -
django - use urlpattern name in forms.ValidationError()
I have the following statement. raise forms.ValidationError({'product_type': [mark_safe('Product type <a href="/group/detail/%d/">N/A already exists</a> for this combination.' % na[0].product_group.id) ]}) This app has the following named url url(r'^detail/(?P<pk>[0-9]+)/$', views.ProductGroupDetail.as_view(), name='group_detail'), Is there a way to use {%url 'group_detail' %} format in the href rather than hard-coded urls? Thanks. -
Django rest framework update RelatedField
I have two models: class PrdLine(models.Model): name = models.CharField(max_length=256, verbose_name='name', unique=True) comment = models.CharField(max_length=256, null=True, blank=True, verbose_name='comment') class Meta: verbose_name = 'prdline' verbose_name_plural = verbose_name class Project(models.Model): name = models.CharField(max_length=256, verbose_name='name') prdline = models.ForeignKey(PrdLine, on_delete=models.CASCADE, verbose_name='prdline') comment = models.CharField(max_length=256, null=True, blank=True, verbose_name='comment') class Meta: unique_together = (('name', 'prdline'),) verbose_name = 'project' verbose_name_plural = verbose_name And I implement a custom relational field "PrdLineField": class PrdLineSerializer(ModelSerializer): links = serializers.SerializerMethodField() # id = serializers.IntegerField(required=False) class Meta: model = PrdLine fields = ('id', 'name', 'comment', 'links') def get_links(self, obj): request = self.context['request'] return { 'self': reverse('prdline-detail', kwargs={'pk': obj.pk}, request=request) } class PrdLineField(serializers.RelatedField): def to_representation(self, value): return {'id': value.id, 'name': value.name} def to_internal_value(self, data): return data def get_queryset(self): queryset = self.queryset if isinstance(queryset, (QuerySet, Manager)): queryset = queryset.all() print(queryset) return queryset class ProjectSerializer(ModelSerializer): links = serializers.SerializerMethodField() prdline = PrdLineField(label='prdline', ) class Meta: model = Project fields = ('id', 'name', 'prdline', 'comment', 'links') def get_links(self, obj): request = self.context['request'] return { 'self': reverse('project-detail', kwargs={'pk': obj.pk}, request=request) } def create(self, validated_data): prdline = validated_data.pop('prdline', None) project = Project(**validated_data) project.prdline_id = prdline project.save() return project def update(self, instance, validated_data): prdline_id = validated_data.pop('prdline', None)['id'] setattr(instance, 'prdline_id', prdline_id) for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() return instance If … -
Django - place differently every second item in for loop
Inside my well i have a list that splits to left and right. I want to place users in that list. I want to order them like: Firs one in the left list, second one in the right, third one in the left list, forth in the right... So every second user would be placed in the right list. Here is the html of the well: <div class="well"> <h4>Users</h4> <div class="row"> <div class="col-xs-6"> <ul class="list-unstyled"> <li><a href="#">User1</a> </li> <li><a href="#">User3</a> </li> </ul> </div> <div class="col-xs-6"> <ul class="list-unstyled"> <li><a href="#">User2</a> </li> <li><a href="#">User4</a> </li> </ul> </div> </div> </div> Now i cant do it just with classic for loop, because if i do as the below code shows, it would load the whole second list many times: <div class="col-xs-6"> <ul class="list-unstyled"> {% for user in users %} <li><a href="#"> {{ user }}</a> </li> </ul> </div> {% if forloop.counter|divisibleby:2 %} <div class="col-xs-6"> <ul class="list-unstyled"> <li><a href="#">{{ user }}</a> </li> </ul> </div> {% endfor %} </div> I would probably have to use forloop.counter|divisibleby:3 but i dont know how to load just users in the second unordered list , without the whole list being copied for every user. Maybe soulution would use javascript too? I … -
django audio file not playing
I am trying play audio file using filefield but it is not playing and i don't know what is wrong here,can anyone please suggest what is wrong with these code and i can correct it. models.py from django.db import models class Weekly_Top(models.Model): song_name = models.CharField(max_length=20) movie_name = models.CharField(max_length=20, null= True) song_track = models.FileField() def __str__(self): return self.song_name class Meta: ordering = ['song_name'] views.py from django.shortcuts import render_to_response from .models import Weekly_Top from django.conf import settings def Homepage(request): weekly_list = Weekly_Top.objects.all() return render_to_response('homepage/index.html',{'weekly_list':weekly_list}) setting.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' index.html <ol type="1"> {% for item in weekly_list %} <li> <div id="name"> <a href="{{ item.song_track.url }}"><h4>{{ item.song_name }}</h4></a> <audio controls> <source src="{{ item.song_track.url }" type="audio/ogg"> Your browser does not support the audio tag. </audio> </div> <h6>{{item.movie_name}}</h6> </li> {% endfor %} </ol> -
How to display the contents of a manytomanyfield in a template using DetailView
I am making an photo album in which each album contains an array of photos. This is just a part of the blog i am making. Here are the models: class Photo(models.Model): image = models.ImageField(upload_to='photos') class Album(models.Model): name = models.CharField(max_length=128) image = models.ImageField(upload_to='photos', blank=True) timestamp = models.DateTimeField(auto_now_add=True) photo = models.ManyToManyField(Photo) def __str__(self): return str(self.name) I need to specifically use django admin for CRUD operations. I am looking for a way display the photos on a separate template which works like a generic DetailView whereas the Album model will provide the detail view. Provide me with a sample template. -
ImportError: No module named graphite.app_settings
i want to install graphite on mac but i take some errors. ytu-berat-atli:graphite ytu$ python manage.py migrate Could not import graphite.local_settings, using defaults! Traceback (most recent call last): File "manage.py", line 13, in execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/init.py", line 307, in execute settings.INSTALLED_APPS File "/Library/Python/2.7/site-packages/django/conf/init.py", line 56, in getattr self._setup(name) File "/Library/Python/2.7/site-packages/django/conf/init.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Library/Python/2.7/site-packages/django/conf/init.py", line 110, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/opt/graphite/webapp/graphite/settings.py", line 174, enter code herein from graphite.app_settings import * # noqa ImportError: No module named graphite.app_settings -
Switch language in jinja template
I'm migrating a multi lingual Django application from Django's template engine to Jinja2. In the templates I currently switch the active language on a per object basis using Django's language template tag i.e.: {% load i18n %} <h1>{% trans 'Page title' %}</h1> <ul> {% for obj in object_list %} {% language obj.language_code %} <li><a href="{{ obj.get_absolute_url }}">{% trans 'view' %}: {{ obj.title }}</a> {% endlanguage %} {% endfor %} </ul> We also use i18n_patterns so the urls of each object are language specific as well. I'm stuck on how to convert this to Jinja. I cannot use Django's i18n template tags and cannot find something equivalent for Jinja. I was also looking at Babel to help with extracting messages from the templates. So a solution that works with Babel as well as with Django would be preferred. -
ensure that current user can make changes only to his data django/python
I want that only current user can make changes only to his data in django for example activate/desactivate content tha he created.. this my view function for activating a product : def Activer(request, produit_id): produit = Produit.objects.get(pk=produit_id) produit.etat = "active" produit.save() return JsonResponse({'success':True}) and this is my code in produit.html : {% if produit.etat == "active" %} however this is accessible for all user .. -
Is this a bug in Django test?
I am aware that dictionary is pass by reference. Therefore I use copy method from dictionary. I also tried copy.deepcopy() but the error is the same https://youtu.be/8xwLQLW209Q -
How can I open another websites in django?
enter image description here Let the url saved in the database is - "www.github.com" When the user click on "Visit Link" it should redirect it to the url saved in the database. But instead of redirecting it to the url saved in the database it is redirecting it to the (http://127.0.0.1:8000/all_projects/www.github.com) [enter image description here] -
Only protocol 3 supported
I try to configure Django with PostgreSQL on Windows 10. When I run server usually I get an error only protocol 3 supported but sometimes the server starts properly. I installed 32-bit Postgres 9.6 and psycopg2 2.7.1. In settings.py I have DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'django', 'PASSWORD': 'django', 'HOST': 'localhost', 'PORT': '5432', } } Do you know any solutions for the problem? -
how to show Filefield validation error django instead of raising exception?
I'm trying to add validation to a filefiled, I used this snippet and it works, but the problem is that it raises an exception when the file extension does not match, but I just want it to show form validation errors, not raising errors. How can I do that?