Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use celery with Django-regristration-redux to email users on signup
I'm using django-registration-redux for registration and wandering where I can add celery into it so it doesn't block and hold up the page when a user signs up? Thanks -
Mixins for Permissions Django REST ListCreateAPIView
I'm sorry if I may have wrong code but I havent really been doing django rest much. I want to detect permissions from django's built in User model. I added a permission to a user model but for some reason has_perm doesn't work. I instead use user_objects.all() and detect if the permission object is there. I want to return an error 400: Unauthorized if the user does not have permission. Heres my current solution(not working): class ProgramListCreateView(PermissionRequiredMixin,ListCreateAPIView): permission_required = Permission.objects.get(name="Can CRUD") permission_classes = (IsAuthenticated,) queryset = Program.objects.all() serializer_class = ProgramSerializer def check_user(self,request): if self.permission_required in request.user.user_permissions.all(): return True return Response(status=400) when I send a json with the user token without the permission, it still creates the object Heres my mixin: class PermissionRequiredMixin(object): user_check_failure_path = 'auth_login' permission_required = None def check_user(self, user): return user.has_perm(self.permission_required) note: has_perm always returns false for some reason even if I add it using user.user_permissions.add(permission_object) -
Django access to database from another process
I create a new Process from django app. Can i create new record in database from this process? My code throws exception: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Create Modelformset with a form for all objects of another Model
I have the following two models: class Category(models.Model): name = models.CharField(max_length=64) class Budget(models.Model): category = models.ForeignKey(Category) month = models.DateField() amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) I want to create a modelformset for all categories for a given month, with only the amount editable. My current solution is to get all budgets, and then get all categories that are not yet referenced in a budget for that month and then use a modelformset with the budgets as the queryset and the remaining categories as a dict as initial values. budgets = Budget.objects.for_month(month) ids = [budget.category_id for budget in budgets] # unassinged categories categories = [{'category': c} for c in Category.objects.exclude(id__in=ids)] BudgetFormset = modelformset_factory(Budget, fields=('amount', 'category'), extra=len(categories)) context['form'] = BudgetFormset(queryset=budgets, initial=categories) It works but has a couple of drawbacks: I have to add the category to the form, otherwise I have to write more code to check the ids of the inputs I didn't find a nice way to display the category in the template. I don't want to display the input for the category but instead just display the text for the selected option. Do you know a better approach to this? I also don't want to save budgets to the database … -
How to change a default looking forget password template in django
plz note the below codings! urls.py url(r'^reset-password/', auth_views.PasswordResetView.as_view(template_name='frgt_pswd.html'), name='reset_password'), url(r'^reset-password/done/', auth_views.PasswordResetDoneView.as_view(template_name='pswrd_sent.html'), name='reset_password_done'), url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>,+)/', auth_views.PasswordResetConfirmView.as_view(template_name='enter_new_pswd.html'), name='password_reset_confirm'), url(r'^reset-password/complete/$', auth_views.PasswordResetCompleteView.as_view(template_name='pswd_reset_cmplte.html'), name='password_reset_complete'), As you can see the above code, i have added the templates which i wanted too! But only first page is appearing. HTML code <fieldset class="module aligned"> <div class="form-row field-email"> <label for="id_email">Email address:</label> <input type="email" name="email" maxlength="300" required id="id_email" /> </div> <input type="submit" value="Reset my password" /> </fieldset> Please help! -
How to login a user during a unit test in Django REST Framework?
This is my DRF view: @api_view(['GET']) @permission_classes([IsAuthenticated]) def check_user(request): user = request.user # use user object here return JSONResponse({}) And this is my unit test for said view: class CheckUserViewTest(TestCase): def test_check_user(self): user = User.objects.create_user('username', 'Pas$w0rd') self.client.login(username='username', password='Pas$w0rd') response = self.client.get(reverse('check_user')) self.assertEqual(response.status_code, httplib.OK) But I always get a 401 UNAUTHORIZED response from my view. I have logged in the user in my test. What am I doing wrong? -
How to get FormPreview from Django FormTools to work?
I have tried to create a minimal working example of FormPreview of Django FormTools, but it did not work. forms.py This is a very simple form. from django.forms import CharField, Form, Textarea class TextForm(Form): text = CharField(widget=Textarea) preview.py This is with slight adjustments just copied from the documentation. It is of curse incomplete but I did not changed it because I did not even got to a preview page of any kind. from django.http import HttpResponseRedirect from formtools.preview import FormPreview class TextFormPreview(FormPreview): def done(self, request, cleaned_data): # Add stuff later, once I get to a preview. return HttpResponseRedirect('/') urls.py Here must be some mistake, but I don't know how it should be correct. Should I remove the first URL? How does FormPreview know what the correct view to use is? from django.conf.urls import url from django import forms from .forms import TextForm from .preview import TextFormPreview from . import views urlpatterns = [ url(r'^$', views.textform), url(r'^post/$', TextFormPreview(TextForm)), ] views.py My simple views.py. from django.shortcuts import render from .forms import TextForm def textform(request): if request.method == 'POST': form = TextForm(request.POST) if form.is_valid(): text = form.cleaned_data['text'] print(text) if request.method == 'GET': form = TextForm context = { 'form': form } return render(request, … -
Check if user is authenticated with django TokenAuthentication
I'm trying to develop a REST API with DRF that uses TokenAuthentication. This will be used in an android app. I was able to authenticate a user and retrieve it's token. The problem I'm having now is with the following view: @csrf_exempt def foo(request): if request.method == 'GET': if request.user.is_authenticated(): ... do stuff ... return HttpResponse(data, "application/json") else: return HttpResponse(status=401) Basically the user should be authenticated in order to receive the data, otherwise he will receive a 401 response. I'm making a GET request to the proper url with the following parameters in the Header: content-type : application/json authorization : Token <user token> Which is basically what I'm doing for other Viewsets (this is not a Viewset) I have - and it works. In this case it's always sending the HTTP response with 401 code (user isn't authenticated). I can't figure out if the problem is with the Header values I'm passing or if this is not the proper way to check if the user is authenticated. Edit: if I do: "print request.user" i get AnonymousUser Thanks! -
what is the difference between Django form and html form
I am working my django projects based on html form submission method . But recently, I came to know that there exist django forms. Please let me know what is the difference between them. -
Django displaying filtered model instance objects in views and html templates
I believe my notification system is setup correctly. I have a model for each notification that gets generated (a like, a comment), and in the view I am passing in all that info and filtering it depending on if the currently logged in user matches up with who each notification is directed at. Then in the template I have a loop that should display all the instances that are returned. However, while I know there are instances that should be shown, nothing is showing up on the site. I am not getting any errors, just nothing shows up. Here is my model: class UserNotification(models.Model): fromUser = models.ForeignKey(User,related_name='user',null=True) post = models.ForeignKey('feed.UserPost',related_name='post') toUser = models.CharField(max_length=6,default='user') timestamp = models.DateTimeField(auto_now_add=True) notify_type = models.CharField(max_length=6) read = models.BooleanField(default=False) def get_absolute_url(self): return reverse('notify:user_notifications') def __str__(self): return str(self.fromUser) View that creates notification instance (I know this works because new instances are shown in the admin): class LikePostToggle(RedirectView): def get_redirect_url(self,pk): obj = get_object_or_404(UserPost,pk=pk) user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) notification = UserNotification.objects.create( fromUser = self.request.user, toUser = obj.author, post = obj, notify_type = "like", ) return obj.get_absolute_url() View that should be showing the notification instances: User = get_user_model() class UserNotifications(LoginRequiredMixin, ListView): login_url = … -
Invalid column name 'Last_Changed_Date'
Hello I'm currently using Python 3.6 and Django 1.11, when defining my view as: def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) applicationdetail = QVReportAccess.objects.get(ntname='HCA\HFA9592') print(applicationdetail) args = {'user':owner.formattedusername, 'user':owner, 'applicationaccess':applicationdetail.report_name} return render(request, 'accounts/profile.html', args) I'm greeted with the following error message, why doesn't Django like the name Last_Changed_Date: ProgrammingError at /account/profile/ ('42S22', "[42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'Last_Changed_Date'. (207) (SQLExecDirectW)") Request Method: GET Request URL: http://127.0.0.1:8000/account/profile/ Django Version: 1.11.5 Exception Type: ProgrammingError My model is a pre-existing database table defined as: class QVReportAccess(models.Model): user_status = models.CharField(db_column='User_Status', max_length = 20) # Field name made lowercase. ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='NTName', max_length=7,primary_key=True, serialize=False) # Field name made lowercase. report_name = models.CharField(db_column='Report_Name', max_length=50, blank=True, null=True) # Field name made lowercase. report_name_sc = models.CharField(db_column='Report_Name_SC', max_length=30, blank=True, null=True) # Field name made lowercase. datareduce_report_code = models.IntegerField(db_column='DataReduce_Report_Code', blank=True, null=True) # Field name made lowercase. role_based_id = models.IntegerField(db_column='Role_Based_ID', blank=True, null=True) # Field name made lowercase. report_id = models.OneToOneField(QvReportList,db_column='Report_ID', max_length=100, blank=True, null=True) # Field name made lowercase. report_group_id = models.IntegerField(db_column='Report_Group_ID', blank=True, null=True) # Field name made lowercase. report_access = models.CharField(db_column='Report_Access', max_length=50, blank=True, null=True) # Field name made lowercase. sr_datareduce_summary_code = models.CharField(db_column='SR_DataReduce_Summary_Code', max_length=10, blank=True, null=True) # Field name made lowercase. sr_datareduce_patient_code = models.CharField(db_column='SR_DataReduce_Patient_Code', max_length=10, blank=True, null=True) # Field name … -
1366, "Incorrect string value:
I have DB with charset latin-1. When I'm getting some data from user, i encrypt it by pycrypto. It returns some strange string (for example, ��w0o4�Bd�), which is decoded by latin-1 as well. When I try to write it in my DB, I'm getting error: ERROR 1366 (HY000): Incorrect string value: '\xEF\xBF\xBD\xEF\xBF\xBD...' for column 'access_key' at row 1 What's wrong with it? -
reusing similar kind of views in django
class SupervisionView(MyBaseView, TemplateView): template_name = 'research/a1.html' def get_context_data(self, **kwargs): context = super(SupervisionView, self).get_context_data(**kwargs) context['supervisions'] = list1 return context def post(self, request, *args, **kwargs): if 'confirm_supervision1' in request.POST: return redirect(reverse_lazy('t_app:dept1', kwargs={'year': self.kwargs['year']})) class SupervisionView2(MyBaseView, TemplateView): template_name = 'research/a2.html' def get_context_data(self, **kwargs): context = super(SupervisionView2, self).get_context_data(**kwargs) context['supervisions'] = list 2 return context def post(self, request, *args, **kwargs): if 'confirm_supervision2' in request.POST: return redirect(reverse_lazy('t_app:dept2', kwargs={'year': self.kwargs['year']})) I have some 20 odd functions doing the same thing again. only change is the context variable and redirect url in each view. What is the best way to compress this? -
get_user_model() returns all my users
I am trying to link only one user at a time to my model. But I am using many to many because I want to enable the option to link multiple users at a time in the future. When I run this code it assigns all my users to the Company model, I need it to assign only one. Any help will be appreciated. Model: class Company(models.Model): user = models.ManyToManyField(get_user_model()) name = models.CharField(max_length=265) def __str__(self): return self.name def get_absolute_url(self): return reverse('nodisoapp:home') View class CreateCompany(LoginRequiredMixin, generic.CreateView): login_url = '/scrty/login/' form_class = forms.Companyform template_name = 'nodiso/create_company.html' Form class Companyform(forms.ModelForm): class Meta: model = models.Company fields = ['name'] -
how to check the status of boolean field in django views
use django 1.11.3 model.py file class Corso(models.Model): titolo = models.CharField(max_length=100) progressivo= models.BooleanField(default=False) f1= models.BooleanField(default=False) f2= models.BooleanField(default=False) def __str__(self): return str(self.titolo) views.py file def edit_iscrizioni(request, corso_id): corsi = Corso.objects.filter( pk=corso_id) tabella= Iscrizione.objects.filter(user=request.user) iscrizione=get_object_or_404(Iscrizione, pk=tabella) f1=CreaCorsi.objects.values_list("f1") print f1 if request.method == "POST": form = IscrizioneForm(request.POST, instance= iscrizione) if form.is_valid(): iscrizione = form.save(commit=False) iscrizione.user = request.user iscrizione.published_date = timezone.now() iscrizione.corso1_id= corso_id iscrizione.save() return redirect('privata') else: form = IscrizioneForm(instance= iscrizione) return render(request, 'corsi/edit.html', {'form':form, 'corsi':corsi}) how to make a view.py with this logic? if Corso.f1==True: i know x=Corso.objects.filter(f1=True) but I don't want to use it. apologize for my horror English. -
How to deploy Django app VPS using Apache2?
I'v followed this tutorial which is recommended by various tutorial to deploy Django. https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04 This is the content of my 000-default.conf file .. <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com Alias /static /home/myproject/static <Directory /home/myproject/static> Require all granted </Directory> <Directory /home/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/myproject:/home/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/myproject/myproject/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog /home/error.log CustomLog /home/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is … -
Allow user modify only objects created by this user
Is there a way in Django to give user access to admin privileges by allow only editing of objects that were created by this particular user? For example I want to give the user permission to create other users but I don't want to allow them to modify users created by admin or other users with this privileges. I'm using django-admin so the question is in context of it. -
Dynamic filter in Django
In my app, I have a form. Depending of the form, one or many filters could be configured by the user. In my view, I have for exemple : querry= Test.objects.filter(filter1=request.post['filter1'], filter2=request.post['filter2'], filter3=request.post['filter3']) So, sometimes filter1, filter2 or filter3 could not exist. If any filters doesn't exist, I just want to ignore the filter. I could do a script with many "IF" conditions but may be there is a smart solution ? Thanks for your help ! -
How to reduce SQL queries in Django using prefetch_related?
I am trying to optimize a Django project (vers. 1.8.6) in which each page shows 100 companies and their data at once. I noticed that an unnecessary amount of SQL queries (especially with contact.get_order_count) are performed within the index.html snippet below: index.html: {% for company in company_list %} <tr> <td>{{ company.name }}</td> <td>{{ company.get_order_count }}</td> <td>{{ company.get_order_sum|floatformat:2 }}</td> <td><input type="checkbox" name="select{{company.pk}}" id=""></td> </tr> {% for contact in company.contacts.all %} <tr> <td>&nbsp;</td> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td>Orders: {{ contact.get_order_count }}</td> <td></td> </tr> {% endfor %} {% endfor %} The problem seems to lie in constant SQL queries to other tables using foreign keys. I looked up how to solve this and found out that prefetch_related() seems to be the solution. However, I keep getting a TemplateSyntaxError about being unable the parse the prefetch, no matter what parameter I use. What is the proper prefetch syntax, or is there any other way to optimize this that I missed? I've included relevant snippets of model.py below in case it's relevant. I got prefetch_related to work in the defined methods, but it doesn't change the performance or query amount. model.py: class Company(models.Model): name = models.CharField(max_length=150) def get_order_count(self): return self.orders.count() def get_order_sum(self): return … -
django admin actions adding css
how i can add class to django admin action select box with bootstrap? action select box or set the default form input in django admin with bootstrap class, so when i create new model and render it to admin site, the form show the input with bootstrap class without modify it before this is my model class ArtikelAdmin(admin.ModelAdmin): def gambar_tag(self, obj): return u'<img src="/%s" width="200" height="auto"/>' % obj.gambar.url gambar_tag.allow_tags = True list_display = ('judul', 'kategori') list_filter = ('judul', 'tanggal', 'kategori') search_fields = ['judul'] form = ArtikelAdminForm -
How to limit Choices for ForeignKey field in Django CreateView?
I have a model structure along those lines: # models.py class Foo(models.Model): ... class Bar(models.Model): foo = models.ForeignKey(Foo) ... class Baz(models.Model): bar = models.ForeignKey(Bar) ... Now, on the DetailView for Foo instances, I have a link to create Baz instances that belong to the Foo instance (via one of its Bar instances). That Link points to the following CreateView: class BazCreateView(CreateView): model = Baz fields = ['bar', ...] As the Baz Instance to be created shall belong to one of foo's Bar instances, I'd like to limit the choices for that field to the Bar instances belonging to foo. So far, I've found ForeignKey.limit_choices_to which seems to be for use in the Model and This question which is 9 years old and thus probably has an outdated answer. If it isn't outdated I'd like some advice on how to access the form object mentioned in the accepted answer and how to pass the Bar id to the CreateView. -
How to Use get_absolute_url() with a foreign key object in Django template
Am relatively new to django and I have searched for this problem but couldn't find a solution. Forgive me if the solution is obvious but I just can't seem to get it right. So, this is the issue. I have two models Parishioner and Community. Parishioner has a many-to-one relationship with Community. On the parishioner_detail page, I am trying to display the community name as a link to the community_detail page. I feel I am not using the get_absolute_url() method correctly. Any help would be appreciated. Models: from django.db import models from django.core.urlresolvers import reverse class Community(models.Model): name = models.CharField(max_length=41) description = models.TextField() leader = models.CharField(max_length=41) email = models.EmailField() phone_number = models.CharField(max_length=20) slug = models.SlugField(max_length=31, unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('people_community_detail', kwargs={'slug': self.slug}) class Parishioner(models.Model): name = models.CharField(max_length=41) date_of_birth = models.DateField('date of birth', blank=True) email = models.EmailField() phone_number = models.CharField(max_length=20) start_date = models.DateField('date posted') societies = models.ManyToManyField(Society, blank=True, related_name='parishoners') communities = models.ForeignKey(Community, blank=True, related_name='parishoners') sacraments = models.ManyToManyField(Sacrament, blank=True, related_name='parishoners') slug = models.SlugField(max_length=31, unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('people_parishioner_detail', kwargs={'slug': self.slug}) class meta: ordering = ['name'] verbose_name_plural = "parishioners" Views: from django.shortcuts import get_object_or_404, render, redirect from .models import Society, Community, Sacrament, Festival, Parishioner def … -
Django Rest Framework Model Serializer
experimenting with django+drf. trying to parse the below json data to create a new product with variants in the database using serializers. how do i validate the incoming json data and then map it to my model classes and save them to the database. the attributes 'Size' and 'Color' are stored in a separate table and their ids are referenced in the product_variant table { "title": "third product", "description": "third product description", "sku": "TP3", "price": "1290.50", "category": 1, "variants": [{ "value": "XS", "sku": "TP3XS", "attribute": "Size" }, { "value": "BLK", "sku": "TP3BLK", "attribute": "Color" }] } below are the serializers and the models that i am using in my app Serializers: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name') class ProductAttributeSerializer(serializers.ModelSerializer): class Meta: model = ProductAttribute fields = ['attribute_name'] def __unicode__(self): return '%s' % self.attribute_name class ProductVariantSerializer(serializers.ModelSerializer): attribute = ProductAttributeSerializer() class Meta: model = ProductVariant fields = ('id', 'value', 'sku', 'attribute') class ProductSerializer(serializers.ModelSerializer): variants = ProductVariantSerializer(many=True) class Meta: model = Product fields = ('id', 'title', 'description', 'sku', 'price', 'category', 'variants') Models: class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=45, blank=True, null=True) active = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'category' class DjangoMigrations(models.Model): app = … -
Remove old permissions in django
In my Django site there are some permissions entries linked to applications that I've removed. For example I have permissions entries linked to "Dashboard" and "Jet" applications. How can you remove them? -
Django Rest Framework: Generate a unique obfuscated ID from ID field
I'm currently learning how to build an API for my company. I haven't been doing this for very long at all so I'm basically a junior developer at this point. Following some tutorials, I got my API up and running on a very basic level using class based views. Previously, I had 'id' as one of the fields for several of my serializers. My manager didn't like this, and he pointed out it would reveal potentially sensitive information about our business (if you get customer_id = 13 for your JSON, then you can infer there are 12 other customers, if you get job_id = 5433 then you can infer there are 5432 other jobs, etc). I'm trying to figure out how to add "id" to my serializers' fields without revealing such information, to help with the lookup_args and the urls. Previously, a customer's URL on the API would have been www.example.com/api/customer/5, 5 being the "pk" in the database, and would return JSON data for that customer. I'm not sure how to go about using the pk but obfuscating it somehow. Customer model on models.py class Customer(models.Model): company_name = models.CharField(max_length=100) contact_name = models.CharField(max_length=100) contact_email = models.CharField(max_length=100) user = models.OneToOneField(User) @staticmethod def …