Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Registration not getting reset email
Followed this question: Django registration email not sending but realized this is for https://github.com/macropin/django-registration not https://github.com/ubernostrum/django-registration which is what I need. Unfortunately, there is nothing about this in their docs about SMTP: http://django-registration.readthedocs.io ve is my app and I've tested my SMTP creds on a 3rd party app and I got an email just fine. Tried on localhost and live site as well. settings.py INSTALLED_APPS = [ 'registration', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 've', 'widget_tweaks', ] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend EMAIL_HOST = '***' EMAIL_HOST_PASSWORD = '***' EMAIL_HOST_USER = '***' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'noreply@***' urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'', include('ve.urls', namespace='ve')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Accessing kwargs['initial'] within a formset form
I am creating a formset from a form. One of the form's fields is a ForeignKey to another model, Transaction. In each form, I want the choices for the 'old_transaction' field to be Transaction objects - excluding the 'new_transaction'. To fill the choices, I pass the new_transaction to the Form through a get_form_kwargs method. The Problem When I retrieve that object in the SoldTransactionForm.init() method, it gives me a KeyError. However when I pdb at that point, the object is there in the kwargs['initial']['transaction'] as it should be. What is throwing the KeyError when the object is there? The Form/Formset class SoldTransactionForm(forms.ModelForm): num_sold = forms.IntegerField( min_value=0) class Meta: model = SoldTransaction fields = [ 'old_transaction', 'num_sold', ] def __init__(self, *args, **kwargs): super(SoldTransactionForm, self).__init__(*args, **kwargs) new_transaction = kwargs['initial']['new_transaction'] self.fields['old_transaction'].queryset = Transaction.objects.filter( user=new_transaction.user).exclude(identifier=transaction.identifier) CompoundFormset = formset_factory( SoldTransactionForm, formset=forms.BaseFormSet, extra=3) The Model class SoldTransaction(TimeStampedModel): new_transaction = models.ForeignKey(Transaction, related_name="new") old_transaction = models.ForeignKey(Transaction, related_name="old") num_sold = models.IntegerField() The View class SellTransactionsView(LoginRequiredMixin, SetHeadlineMixin, CreateView): form_class = SoldTransactionForm model = SoldTransaction headline = "Sell Transaction" transaction_status = "sell" class_url = 'transactions' def get_object(self): return Transaction.objects.get( user=self.request.user, identifier=self.kwargs['identifier'] ) def get_form_kwargs(self): kwargs = super(SellTransactionsView, self).get_form_kwargs() kwargs['initial']['transaction'] = self.get_object() return kwargs def get_context_data(self, *args, **kwargs): context = super(SellTransactionsView, self).get_context_data(*args, … -
Defer() Queryset in Django is not working
I am trying to do a queryset request to my database that I would like to exclude a entire column from the response, in this case the column weigth. But the response is returning all columns from the database. I am trying to use defer but it is not working. What I am doing wrong? Views.py def product_table(request): width = request.GET['width'] length = request.GET['length'] prod_filter = Product.objects.filter(length=length,width=width).defer('weigth') data_prod =serializers.serialize('json', prod_filter) return JsonResponse({'data_prod':data_prod}) Html ... <div> <table id="id_prod" class="table table-striped table-bordered table-hover"></table> </div> <script> $(document).ready(function(){ ... $.get('{% url "prod_table" %}',function (data_prod) { var data_json = JSON.parse(data_prod['data_prod']); var data_array = []; for(var i = 0; i < data_json.length; i++) { var arr = $.map(data_json[i]['fields'], function(el) { return el }); data_array.push(arr); } $('#id_prod').DataTable({ destroy: true, data: data_array, columns: [ { title: "Name" }, { title: "width" }, { title: "length" }, { title: "volume" }, ] }); }); -
How can I get an access to url paramaters in django rest framework permission class?
I have a view: class DealsView(APIView): permission_classes = (IsAuthenticated, IsOwnerOrCuratorOrDirectorOrNotAllowed, ) def get(self, request, user_pk): ... But in order to check the permissions correctly I need to pass user_pk url argument to permission: class IsOwnerOrCuratorOrDirectorOrNotAllowed(permissions.BasePermission): def has_permission(self, request, view): ... By default it doesn't have any arguments except self, request, and view. How can I go through it? -
Django model: Conversation between two users
I'm trying to create a Model which represents a conversation between two users (only two). Can't figure out how to create two fields because users are equivalent. class Conversation(models.Model): user_one = ForeignKey('auth.User') user_two = ForeignKey('auth.User') class Meta: unique_together = ('user_one','user_two') Is this the best way I can design a model? And then manager method: def get_conversation(user_one,user_two): c = Conversation.objects.filter(Q(user_one=user_one,user_two=user_two)|Q(user_one=user_one,user_two=user_two)) return c Or is there a more comfortable way to handle such model? For example using ManyToManyField and check if there are two and only two users?: users = ManyToManyField('auth.User') -
How to transfer session variables throught domain django?
I have an multidomain app in django. mx.myapp.com nz.myapp.com hn.myapp.com and it works well. The problem is when I login in mx.myapp.com and some link have to redirect to nz.myapp.com the session variables are not set. How do I keep logged whith my account throught the diferent domains? I think I have to transfer de session variables to another subdomain or something like that but I don't know how to do it. Please help. -
Enforcing unique tuple condition in Django Rest Framework Model
So I have a Django Rest Framework model named Rating I am using as so: class Rating(models.Model): id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) event = models.ForeignKey(Event, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) rating_for = models.TextField(choices=RATING_FOR) rating = models.IntegerField(choices=RATING_NUMS) class Meta: unique_together = (("person", "event", "rating_for"),) I wish to enforce a validation condition that checks that one person cannot have more than one rating for one event. Basically, a duplication check. What I tried doing, as you see, was enforce a unique_together because the way I thought unique_together works is that it forms a tuple of these values and doesn't allow duplicate tuples. What I mean by that is that if the hacker id is 1, event id is 2 and rating_for is 'food event', it (figuratively) forms a tuple 12food_event and disallows this particular 12food_event combination to be used. This would allow a 12networking_event. Apparently, this is not the way unique_together works. If I have a combination 12food_event , I cannot use food_event with anything else in the future, same for 1 and 2. Is there any way of enforcing tuple uniqueness at the Model level or will I have to run a separate validation check in the … -
How do I save a jinja variable to a list in javascript?
I am using Django to create a web app for running a ranked election system. I have created a template for saving the ranking of the ballot paper. Here is what I have so far in the template: <div id='main'> {% for candidate in candidates %} <div class='box'> <h3>{{candidate.UserID}}</h3> <input type=text> </div> {% endfor %} </div> <button id='send' type="submit">Submit</button> <script type="text/javascript"> $(document).ready(function() { var button = $("#send"); $(button).click(function() { var vals = []; $("#main :input").each(function(index) { vals.push(this.value); }); vals = JSON.stringify(vals); console.log(vals); }); }); </script> At the minute, the list just puts the values that the user inputs to the box into the list in order. What I want to do now is create a separate list that stores the name or the id of the candidate, an entry on a table which I queried and passed to the template using Django and rendered above using Jinja. This is so that I can relate the rank to the candidate that has been ranked. I am doing this using JavaScript so that I can then process the two lists and return to Django (possibly with Ajax) a new list with the candidateIDs in the order the candidates were ranked. I will … -
Django. Generate a lot of initial data (Factories ? )
I am interested in generate a lot of dumb data in Django using my models and I wonder if It could be possible to do this using something like Factories in Laravel. Any ideas ? Thanks -
Django - passing multiple views to a django template
Django template with "Three Forms" , seeking input from user. All "Three Forms" have TWO Float Input fields each. All "Three Forms" have their own SUBMIT buttons. User may Submit any One of the Three Forms or Two or all Three at the same time. My challenge - need to separately call Three functions to process the inputs. 1st Function - will as an example - ADD the TWO Float inputs. 2nd Function - will as an example - SUBTRACT First Float from Second. 3rd Function - will as an example - again do something else to TWO Floats Tried to create more than 1 views and point at the same template - not possible. Tried to use def get_context_data(self, *args, **kwargs): and get the result of the Three Functions into One Context and **return** context , no success yet . Kindly advise. -
Django production using Heroku on windows local hosting error
As windows doesn't work with gunicorn, the heroku documentation suggest that you host it locally for production. https://devcenter.heroku.com/articles/deploying-python#the-procfile To do this, it says that i must add psycopg2==2.5.3 to my requirements.txt file. My requirements.txt now reads: Django==1.8 psycopg2==2.5.3 However, it then says to run pip install -r requirements.txt, which is returning an error. (venv) C:\Users\fdot\Desktop\venv\Store>pip install -r requirements.txt Requirement already satisfied: Django==1.8 in c:\users\fdot\desktop\venv\lib\site-packages (from -r requirements.txt (line 1)) Collecting psycopg2==2.5.3 (from -r requirements.txt (line 2)) Using cached psycopg2-2.5.3.tar.gz Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info\psycopg2.egg-info writing dependency_links to pip-egg-info\psycopg2.egg-info\dependency_links.txt writing pip-egg-info\psycopg2.egg-info\PKG-INFO writing top-level names to pip-egg-info\psycopg2.egg-info\top_level.txt writing manifest file 'pip-egg-info\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\fdot\AppData\Local\Temp\pip-build-qx2oza81\psycopg2\ Any ideas? Thanks -
Using SQL IN condition in django
I am trying to fetch data where the column value "tag" belongs to list from the table "UserBookmark". UserBookmark.objects.filter(tag__in = ['Java','Android']) but this returns QuerySet[](null set) whereas I do have data matching this query in table <QuerySet [<UserBookmark: 21 user12 http://careers.bankofamerica.com/ [u'Java']>,<UserBookmark: 22 user12 http://aehlke.github.io/tag-it/examples.html [u'Data Science,Python']>,<UserBookmark: 23 user13 https://github.com/Azure/azure-quickstart-templates [u'Android']>, <UserBookmark: 24 user14 https://github.com/sunnykrGupta/Bigquery-series [u'Python']>, <UserBookmark: 25 user14 https://github.com/ctfs/write-ups-2017 [u'Data Analytics']>]> -
How to get object name and object count using Django
I want this kind of thing to display in HTML page Location name Count London 10 Manila 8 Location Name is in the database. I want to display the location name and how many times that location name was repeated. view.py... class MapListView(ListView): model = Map map_list.HTML... {% for object in object_list %} <tr> <td>{{object}}</a></td> <td><a href="{{object.get_absolute_url}}">{{ object.LocName }}</a></td> <td><a href="{{object.get_absolute_url}}">{{ object.LocName_count }}</a></td> </tr> {% endfor %} I used like above but it not working Please help -
create and update timestamp
Getting errors on migrate. When I don't set any default, i get an error match = datetime_re.match(value) TpyeError: expected string or buffer created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) When I set a default or tried it as null=True or blank=True, i get an error The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may be present. Okay, so I should remove it, but then I run into the above error. created_at = models.DateTimeField(auto_now_add=True, default=None) updated_at = models.DateTimeField(auto_now=True, default=None) Any help is appreciated -
Django Rest Framework - NoReverseMatch
I'm using Django 1.11.7 with DjangoRestFramework 3.7.3 I have a app meals meals/urls.py app_name = 'meals' urlpatterns = format_suffix_patterns([ url(r'^$', views.api_root), url(r'^food/$', views.FoodList.as_view(), name='food-list'), url(r'^food/(?P<pk>[0-9]+)/$', views.FoodDetail.as_view(), name='food-detail'), ]) meals/views.py @api_view(['GET']) def api_root(request, format=None): return Response({ 'Foods': reverse('food-list', request=request, format=format), }) When I run, I'm getting the error NoReverseMatch. But if I removed app_name = 'meals' in urls.py, it works # app_name = 'meals' urlpatterns = format_suffix_patterns([ url(r'^$', views.api_root), url(r'^food/$', views.FoodList.as_view(), name='food-list'), url(r'^food/(?P<pk>[0-9]+)/$', views.FoodDetail.as_view(), name='food-detail'), ]) How do I get it working while keeping app_name? -
Translate on Serializing Django Rest Framework
I want to Translate a variable that is on my database in the language requested, when serializing. `from rest_framework import serializers from api.models import Category from django.utils.translation import ugettext_lazy as _ class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'image', 'description')` Is the serializer method field a good aproach? -
Django adding related fields in admin interface
Currently in my admin I have many excerpts in which admin users can create and then go into the "women" interface and attach the excerpt. Is it possible to add a selection field in the excerpt admin where the user could select which woman the excerpt belongs to rather than creating the excerpt and going into the "women" interface to create the relationship? class Excerpt(models.Model): extract = models.CharField(max_length=2000, null=True, blank=True) audio_url = models.IntegerField(null=True, blank=True) start_time = models.IntegerField(null=True, blank=True) end_time = models.IntegerField(null=True, blank=True) def __unicode__(self): return self.extract class Women(models.Model): name = models.CharField(max_length=100) location = models.ForeignKey(Location, null=True, blank=True) excerpt = models.ManyToManyField(Excerpt, blank=True) -
django admin asynchron reloading form for foreignkey fild
How refresh django admin form when a value change in the browser? I searched and found a similar question: How refresh django admin form when a value change in the browser?. But the problem is that I can not use one library because I need to change the model. Another library djano-flexselect is not supported for python3(( class Country(m.Model): ...................... class Region(m.Model): company = m.ForeignKey(Country) name = m.CharField(max_length=80) class City(m.Model): region = m.ForeignKey(Region) country = m.ForeignKey(Country) When adding a new city, I need to select a country and then the form with the region will automatically reload all the regions associated with the selected country. Can anyone help? -
How to call python function from Django
I am trying to call python functions with parameters from django. But cannot call any function from the view. also no python simple code like print or variable initialization work in view. How can i call python function from django? -
Django Admin: Executing a command after the objects have been saved without post_save signal
I have some code that needs to be executed after new/changed data has been saved but it is not dependent on any one particular change. Thus, I'd rather not have it executed for every single change as would be the case using the post_save signal. The save_model method, however, executes too early for my purpose. Is there any other way to hook into the admin's save process after the changes have been persisted to the database except for the post_save signal? -
DRF: related field name throwing error column ambiguously defined
I have models like class Profile(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=1024, blank=True, null=True) class Meta: managed = False class ResourceMgmt(models.Model): id = models.BigIntegerField(primary_key=True) profile = models.ForeignKey(Profile, models.DO_NOTHING, related_name='cpe_mgmt_profile') class Meta: managed = False Serializer like class ResourceMgmtSerializer(serializers.ModelSerializer): profile_name = serializers.StringRelatedField(source='profile.name', read_only=True) class Meta: model = ResourceMgmt fields = (<tuple of fields including profile_name>) View like class RunningSchedules(generics.ListCreateAPIView): serializer_class = ResourceMgmtSerializer model = ResourceMgmt filter_backends = (filters.OrderingFilter, filters.SearchFilter,) ordering_fields = (<tuple of fields including profile_name as profile__name>) ordering = ('-schedule_start_time',) search_fields = ordering_fields Now when I hit url like ?ordering=profile__name I get an error ORA-00918: column ambiguously defined. I know what this is error is, but can't seem to figure out why is it happening with Django ORM -
Django xadmin for three-layers site-menus
I use django and django-xadmin,my site-memu just like this: enter image description here and my models like this : # _*_ encoding:utf-8 _*_ from __future__ import unicode_literals from datetime import datetime from django.db import models # Create your models here. class indexnav(models.Model): nav_name = models.CharField(max_length=50,verbose_name=u"首页导航") url_nav = models.URLField(max_length=200,verbose_name=u"导航链接") add_time = models.DateTimeField(default=datetime.now, verbose_name=u"更新时间") class Meta: verbose_name = u"问答" verbose_name_plural = verbose_name def __unicode__(self): return '{0}'.format(self.nav_name) class ask(indexnav): question = models.CharField(max_length=200,verbose_name=u"问题描述") answer = models.CharField(max_length=200,verbose_name=u"回答描述") class Meta: verbose_name = u"问答列表" verbose_name_plural = verbose_name class nextNav(models.Model): indexNav = models.ForeignKey(indexnav,verbose_name=u"上级目录") nav_name_next = models.CharField(max_length=50,verbose_name=u"二级导航") url_nav_next = models.URLField(max_length=200,verbose_name=u"导航链接") add_time_next = models.DateTimeField(default=datetime.now, verbose_name=u"更新时间") class Meta: verbose_name = u"二级导航" verbose_name_plural = verbose_name def __unicode__(self): return '{0}'.format(self.nav_name_next) but , I want the site-menu has three-layers,just like : -menu-header1 --one-layer menu1 --second-layer menu --second-layer menu --second-layer menu --one-layer menu2 --second-layer menu --second-layer menu --second-layer menu -menu-header2 --one-layer menu1 --second-layer menu --second-layer menu --second-layer menu --one-layer menu2 --second-layer menu --second-layer menu --second-layer menu How can I to write my models or other files?thanks so much! -
I have created many apps in my project. how can I group them now?
If I have created many apps in the root directory, how to group them ? In SO, I find a method to group apps: How do I create sub-applications in Django? They all are create the folder first, then startapp like: python manage.py startapp sub_app1 app/sub_app1 The app/ is the folder to group the apps. But my case is I have created many apps in my project. how can I group them now? -
UpdateView doesnt save the avatar field?
I have abstract User with avatar field. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) And views.py @method_decorator(login_required, name='dispatch') class UserUpdateView(UpdateView): model = User fields = ('first_name', 'last_name', 'email', 'bio', 'location', 'birth_date', 'avatar', ) template_name = 'my_account.html' success_url = reverse_lazy('my_account') def get_object(self): return self.request.user I can see fields and can save all of it except avatar . What to do? -
Connection timeout error in sending an smtp mail through zoho
Am getting a connection time out error when am trying to send a django mail through smtp. Below is my configuration - EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'smtp.zoho.com' # Port for sending e-mail. EMAIL_PORT = 587 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = 'cs@amaze.com' EMAIL_HOST_PASSWORD = 'amaze123' EMAIL_USE_TLS = True And the code which am using is : from django.core.mail import send_mail >>> send_mail('Order Confirmation', 'Order placed successfuly', 'cs@amaze. com', ['check@gmail.com']) Error - Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/django/core/mail/__init__.py", li ne 61, in send_mail return mail.send() File "/usr/local/lib/python2.7/dist-packages/django/core/mail/message.py", lin e 292, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python2.7/dist-packages/django/core/mail/backends/smtp.py ", line 100, in send_messages new_conn_created = self.open() File "/usr/local/lib/python2.7/dist-packages/django/core/mail/backends/smtp.py ", line 58, in open self.connection = connection_class(self.host, self.port, **connection_params ) File "/usr/lib/python2.7/smtplib.py", line 256, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python2.7/smtplib.py", line 316, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket return socket.create_connection((host, port), timeout) File "/usr/lib/python2.7/socket.py", line 571, in create_connection raise err error: [Errno 110] Connection timed out