Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django NoReverseMatch Error with templates
friends, I'm struggling with a NoReverseMatch error for a few days, and I can't seem to find what is wrong with the code. I must say I am quite new to Django, So I would appreciate it very much if you explain your solution to the problem so I could learn from it :) The Error NoReverseMatch at /david/Physics/ Reverse for 'subcategory' with keyword arguments '{'subcategory_name': 'a'}' not found. 1 pattern(s) tried: ['david/([a-zA-Z_]+)/(?P<subcategory_name>[a-zA-Z_]+)/$'] category.html: <h1>The subcategories for {{ category }}</h1> {% if subcategories %} <ul> {% for subcategory in subcategories %} <li><a href="{% url 'subcategory' subcategory_name=subcategory %}">{{ subcategory }}</a></li> {% endfor %} </ul> {% else %} <h4>No subcategories for that category</h4> {% endif %} urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^search/$', views.search, name='search'), url(r'^browse/$', views.browse, name='browse'), url(r'^(?P<category_name>[a-zA-Z_]+)/$', views.view_category, name='category'), url(r'^([a-zA-Z_]+)/(?P<subcategory_name>[a-zA-Z_]+)/$', views.view_subcategory, name='subcategory'), url(r'^([a-zA-Z_]+)/([a-zA-Z_]+)/(?P<information>[a-zA-Z_]+)/$', views.view_information, name='information'), ] views.py: from django.shortcuts import render, get_list_or_404, get_object_or_404 from django.http import HttpResponse from .models import Category, Subcategory # Create your views here. def index(request): return render(request, 'basic_web/index.html') def search(request): return HttpResponse('Here you can search!') def browse(request): categories = Category.objects.all() context = {'categories': categories} return render(request, 'basic_web/browse.html', context) def view_category(request, category_name): category = get_object_or_404(Category,name__iexact=category_name) subcategories = get_list_or_404(Subcategory, … -
How combine (merge) several number of querysets?
Can someone say how to combine (merge) several number of querysets. The number of querysets are not fixed. I tried next code but it didnt work as I expected. How to fix this problem? first_list = [] for id in ids: products = Product.objects.filter(company=id) first_list.append(products) final_list = list(chain(first_list)) This code return: [<QuerySet [<1>, <2>]>, <QuerySet [<3>, <4>]>, <QuerySet [<5>, <6>]>] I need: [<QuerySet [<1>, <2>, <3>, <4>, <5>, <6>]>,] -
how to solve SMTPServerDisconnected in django email sending?
How I can solve this issue when I test this on my localhost it's work but it doesn't work in server. this is my code for email form. class ContactCleaningView(TemplateView): template_name = 'contact_cleaning.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['form'] = ContactCleaning() return self.render_to_response(context) def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) form = ContactCleaning(request.POST) if form.is_valid(): name = request.POST['name'] phone = request.POST['phone'] address = request.POST['address'] email = request.POST['email'] zipcode = request.POST['zipcode'] rooms = request.POST['rooms'] bathrooms = request.POST['bathrooms'] service = request.POST['service'] subject = 'Cleaning-' + request.POST['subject'] description = request.POST['description'] send_mail('From sams cleaning and hauling', "Name:"+name+"\nPhone:"+phone+"\nAddress:"+address+"\nZipcode:"+zipcode+"\nNumber Of Rooms:"+rooms+"\nNumber Of Bathrooms:"+bathrooms+"\nType Of Service:"+service+"\nSubject:"+subject+"\nDescription:"+description, email, [ settings.DEFAULT_FROM_EMAIL, ], fail_silently=False) # contact_form = ContactCleaning(name=name, email= email, phone=phone,address=address, subject=subject, message=message) # contact_form.save() # context['form'] = form # return self.render_to_response(context) return HttpResponseRedirect('/') and this is my settings.py configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = False EMAIL_HOST = 'mail.cleaningandhauling.us' EMAIL_PORT = 25 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
Serve a file for download with Django
I am trying to serve a download file in my django app, after a bit of research I made the code below but there is one problem, the file is opened in the browser instead of being downloaded. The files that I serve on my app are exe, and when they open it's just a bunch of random characters. So how can I specify that I want the file to be downloaded, not opened? Thank you with open(path_to_apk, 'rb') as fh: response = HttpResponse(fh) response['Content-Disposition'] = 'inline; filename=' + os.path.basename(path_to_apk) return response -
Dajaxice refresh part of website every 10 sec
I have django app (1.6) and my problem is that I want to write function with refresh every 10 sec. But now my problem is how to pass this part of website with <a data-calendar-id=...> to set_calendar function in my ajax.py file. Here is part of my html code: <dl id="calendar" class="dropdown"> <dt><a data-calendar-id="{{ request.session.current_calendar.id }}"><span>{{ request.session.current_calendar.name }}</span></a></dt> <dd> <ul> {% get_calendars_list as available_calendars %} {% for c in available_calendars %} <li><a href="{% url 'calendar_home' c.id %}" data-calendar-id="{{ c.id }}">{{ c.name }} <span class="value">{{ c.id }}</span></a></li> {% endfor %} </ul> </dd> </dl> My code in ajax.py file: @dajaxice_register(name='cal') def set_calendar(request): return simplejson.dumps({'calendar': 'I am looking here part of website with id=calendar'}) My js in api.js file: Dajaxice.cal(function(d){alert(d.calendar);}); Thanks for every help! -
Django: Dynamically set model instance attributes based on JSONField
I have a question on how to set model attributes dynamically when model instances are initiated. I am using a simple model with a native PostgreSQL JSONField: from django.db import models from django.contrib.postgres.fields import JSONField class Booking(models.Model): data = JSONField(blank=False, encoder=DjangoJSONEncoder) Is there any way to set attributes on the model instance based on the values stored in the 'data' field when the model is instantiated? I want to be able to do this: from .models import Booking b = Booking.objects.create(data={'foo':'bar'}) b.foo # this should yield 'bar' My initial thought was to override the model's init method and set the instance attributes with setattr(), but overriding a model's init method is strongly discouraged in the Django docs. Is there any other way to achieve this? Any help is appreciated. PS: I know that I can access the values stored in 'data' on a model instance like so: booking.data['foo'], so this is not what I am looking for. -
Foreign key field is not being created in the database
I'm trying to associate Comment with User models, but somehow the field is not being created in the database. When I try to access the page, the following error is shown: (1054, "Unknown column 'user_comments.user_id' in 'field list'") These are in the models.py: class User(models.Model): username = models.CharField(max_length=128) password = models.CharField(max_length=128) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) email = models.CharField(max_length=128) date_joined = models.DateField(auto_now_add=True) class Meta: db_table = 'auth_user' ordering = ('date_joined',) class Comment(models.Model): user = models.ForeignKey('auth.User', related_name='comments', on_delete=models.CASCADE) content = models.CharField(max_length=256) date_created = models.DateField(auto_now_add=True) class Meta: db_table = 'user_comments' ordering = ('date_created',) def __str__(self): return self.content def save(self, *args, **kwargs): content = self.content super(Comment, self).save(*args, **kwargs) If I name the user variable to user_id, an error saying user_id_id wasn't found will show upon creating a new Comment in the admin panel. -
django F expression based on datetime object
My model is, class Test(): date1 = models.DateTimeField() date2 = models.DateTimeField() I can find out objects who's date2 is greater than date1. Using following query. Test.obejcts.filter(date2__gt=F('date1')) How can I find out objects based on difference of date1 and date2 , like find out all the objects who's date2 is greater than date1 by one year ? -
angular js post request converting / to %2F in params
so im trying to send a path via params using $http.post but the value is converting the / to %2F. controler.js $scope.actionFun = function(Script){ var data = $.param({command:Script.location });console.log(data); $http.post("http://127.0.0.1:8000/action/",data).success(function(data, status){ console.log(data); }) } console.log(data) gives output as command=%2Ffolder%2Ffilename but it should give /folder/filename Django view import urllib, json @api_view(['GET','POST']) def call(request): if request.method == 'POST': data = request.body.decode('utf-8') data1 = json.loads(data) return Response({"message":"Got Some Data","data":data1}) error received is JSONDecodeError at /action/ Expecting value: line 1 column 1 (char 0) and if i change the request.body to request.data JSON parse error - Expecting value: line 1 column 1 (char 0) im fairly new to DRF and Angularjs tried various methods like model.config($location) but no use. -
Django template - check if field has value in it or empty if ManyToManyField
This seems rather simple but I am not able to figure out a good solution from SO or Django docs (using Django 1.10) I am fetching a model object in the template and displaying only those fields that have values (i.e not blank or null) or not empty if ManyToManyField. I am not able to figure out a good way to do it apart from just using many if and else's to check the field type and then run the corresponding if condition. {% if model_name.field_name %} always returns true for ManytoManyFields (since its a ManyRelatedManager) {% if model_name.field_name|length > 0 %} always returns false for ManytoManyFields {% if model_name.field_name.all %} may work fine for ManyToManyFields but not for others (like CharField) Is there a one way to check whether a field has some usable value inside it (whether ManytoManyField or a simple CharField)? I can resort to using multiple if-else to check the field type first and then running the corresponding check, but it feels counter-intuitive to do so since this seems like a common use case to justify a template tag. -
django-guardian not affecting permissions
I'm trying to change one of the default action_modelname which django creates automatically. Specifically, I'm trying to set the delete_business permission of a GeneralUser (custom User model) to True. Below is shell session: >>> our_user = GeneralUser.objects.get(id=25) >>> our_biz = Business.objects.get(id=5) >>> assign_perm('delete_business', our_user, our_biz) <UserObjectPermission: UserObjectPermission object> >>> our_user.has_perm('delete_business', our_biz) False I also tried: >>> assign_perm('delete_business', our_user, our_biz).save() but .has_perm returns False no matter what. What gives? I've tried the following: By default django-guardian monkey patches the user model to add some needed functionality. This can result in errors if guardian is imported into the models.py of the same app where the custom user model lives. To fix this, it is recommended to add the setting GUARDIAN_MONKEY_PATCH = False in your settings.py and subclass guardian.mixins.GuardianUserMixin in your custom user model. Still no dice. -
Take list of all objects ids
I have model Product where as primary key use code field which is UUID. I want take list of ids of all products. I want list like this: ['14431ec4-3224-480f-85e2-b541891919b1', '6e54636b-7283-4504-a16f-f54d29db26f2'] I tried next code but it return me this: [UUID('14431ec4-3224-480f-85e2-b541891919b1'), UUID('6e54636b-7283-4504-a16f-f54d29db26f2')] models.py: class Product(models.Model): code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False) views.py: products = Product.objects.all() product_ids = [] for product in products: product_ids.append(product.code) print(product_ids) How to fix this problem? -
Large file in python model gunicorn + nginx
I have a python model that runs as a Django app on RedHat system. Everything ran fine until I uploaded a larger model (not touching the setup) which has a 500MB sparse matrix and now the worker timeouts. Judging from running top each gunicorn instance loads the matrix only when it is asked to evaluate the model. I have more than enough memory for each worker. Is there a way to preload the contents for each of the worker so it can only evaluate the request and does not load the inner things? Thanks a lot! -
redirect() is not working
The redirect function is not working properly.It is showing the error NoReverseMatch at /post/new/ Reverse for 'post_detail' with arguments '()' and keyword arguments '{'pk': 9}' not found. 0 pattern(s) tried: [] this is my views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User from django.views.generic import View from django.utils import timezone from django.contrib.auth import ( authenticate, get_user_model, login, logout, ) from .forms import UserLoginForm, UserRegisterForm, UserForm, PostForm from .models import Post def login_view(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] u = User.objects.get(username=username) posts = objects.for_user(request.user) if username and password: user = authenticate(username= username, password= password) if not user: return render(request, 'post/login.html',{'error_message': 'Incorrect username or password'}) if not user.is_active: return render(request, 'post/login.html', {'error_message': 'Your account has been disabled'}) if user.is_active: login(request, user) return render(request, 'post/home.html', {'u' : u, 'posts': posts}) return render(request, 'post/login.html') class register_view(View): form_class = UserRegisterForm template_name = 'post/register.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() new_user = authenticate(username= username, password= password) if new_user is not None: if user.is_active: login(request, new_user) return redirect('post/home.html') return render(request, self.template_name, {'form' : form}) def … -
user not logged in even self.request.user.pk is True
I want my user to logged in and redirect to his profile after he signup. but everything works except it wont logged in but redirect to his profile, please help me. this is the code class SignUpView(CreateView, SuccessMessageMixin): form_class = forms.SignUpForm template_name = "accounts/signup.html" def form_valid(self, form): user = form.save() login(self.request, user) return super().form_valid(form) def get_success_url(self, **kwargs): return reverse_lazy('profiles:profiles', kwargs={'pk': self.request.user.pk}) -
How to return single object in django GET api (rest framework)
I have a Table "Configuration". class Configuration(models.Model): inventory_check = models.BooleanField(default=False) refund = models.BooleanField(default=False) record_seat_number = models.BooleanField(default=False) base_url = models.URLField() This table will have a single entry. Below is the serializer : class ConfigurationSerializer(serializers.ModelSerializer): class Meta: model = Configuration fields = '__all__' I am using rest framework for the API. Below is the Views.py @api_view(['GET']) def get_configuration(request): m = Configuration.objects.all() serializer = ConfigurationSerializer(m, many=True) return Response(serializer.data, status=status.HTTP_200_OK) This works perfectly. But the problem is this would return object inside array. [ { "id": 1, "inventory_check": false, "refund": true, "record_seat_number": false, "base_url": "http://localhost:8000/" } ] All I want is to send only the object without array. How to achieve this? -
Server and application on two different git repositories
I want to use the IBM Bluemix DevOps Services, and more especially the automated pipeline to pass the last pushed commit through the build, the tests, then deploy in a test environment. All the guides I found recommend having one repo with the server and application together, and link this repo to the pipeline. While such a configuration works, I feel like it is against the Django standards. The application (what I develop) should be separated (ie: on another git repo) from the server (which is just a part to make the application work). I do not know how to manage this situation. Should I: Write a build script which uses git clone to retrieve a build-pack like https://github.com/fe01134/djangobluemix then modify the adequate files ; Find a way to attach two git repositories to one pipeline ; Forget the idea and go for the IBM recommended way to have the server and the application on the same repo? -
Django Q returning only one column
I am trying to get queryset with all columns, but am getting only titles column q=Q(title__icontains=str[0]) | Q(id__icontains=str[0]) I need to get Queryset with all columns. -
Django Web framework in Netbeans
Okay, I would like to get straightaway to this question which I wasn't convinced about so far with all the answers available online. As we've Python plug-in to work within Netbeans, is there anything as such Django plug-in too to work with Netbeans? Because I'm looking forward to work with Netbeans to develop web applications using Python, how can I do that? If at all there isn't any way to work with Netbeans, which is the best open source IDE to work with, in order to blend Django web framework for developing web apps? I need a free version ONLY. -
Django's LoginView uses old username attribute even with a custom User model
I wanted to customize Django's builtin authentication system to replace username with email (i.e. use an email/password combination instead of a username/password combination for login), so I made a custom User model by subclassing AbstractBaseUser and PermissionsMixin and a custom UserManager, then set settings.AUTH_USER_MODEL = 'myapp.User' to enable it. Everything works fine, but the problem is, the login form as generated by django.contrib.auth.views.LoginView uses name="username" type="text" and label id id_username for the email input field (in spite of using the correct label string "Email address"). The login form works regardless, but it's wrong semantically and the HTML5 client-side validation doesn't work this way. Note that this isn't a problem in the registration form; it names the email field as email rather than username, as expected. Here's the code: models.py: from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models from django.utils.translation import ugettext_lazy as _ from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), unique=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=False) verification_code = models.CharField(_('verification code'), max_length=32, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] class Meta: verbose_name = _('user') verbose_name_plural … -
Simple ajax request not being sent, Django
My ajax request not being sent/received. Although normal GET request works fine. html <a id="wish-add" href="javascript:" data-href="/plugins/e/wish/add/{{ object.id }}"> Add </a> js $('#wish-add').click(function(e) { e.preventDefault(); $.ajax({ url: $(this).attr('data-href'), success: function(data) { alert(data); }, failure: function(data) { alert('Got an error dude'); } }); return false; }); views.py class WishListAdd(FrontTemplateMixin, g.View): def get(self, request, *args, **kwargs): raise Exception('a') Exception('a) is never raised -
Check view method parameter name in Django class based views
I have created a decorator in my Django project to inject parameter values to the decorated method's parameters. I do this by using inspect.getargspec to check which parameters are present in the method and place them in kwargs. Otherwise I get an error due to the incorrect number of parameters in the method. While this works properly in individual view methods, it fails when it comes to Django's class based views. I believe this might be because the decorators are applied using @method_decorator at the class level to the dispatch method instead of the individual get and post methods. I'm a python newbie and might be overlooking something obvious here. Is there a better way to do what I'm doing? Is it possible to get the method parameter names in a class based view? I'm using Python 2.7 and Django 1.11 -
Cloning a div and changing the id's of all the elements of the cloned divs
I am working with a django project, and part of the requirement is to have a button on the html page which when clicked clones a particular div and appends it to the bottom of the page as shown in the screenshot: Screenshot of the Page I was successful in doing this applying the following code: var vl_cnt =1; //Initial Count var original_external_int_div = document.getElementById('ext_int_div_1'); //Div to Clone function addVL(){ var clone = original_external_int_div.cloneNode(true); // "deep" clone clone.id = "ext_int_div_" + ++vl_cnt; // there can only be one element with an ID original_external_int_div.parentNode.append(clone); var cloneNode = document.getElementById(clone.id).children[0].firstElementChild.firstElementChild; cloneNode.innerText = "External Interface "+vl_cnt; //Change the Header of the Cloned DIV $(clone).find('input:text').val('') //Clear the Input fields of the cloned DIV document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned window.scrollTo(0,document.body.scrollHeight); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div style="height:0px;clear:both"></div> <div style="float:right"> <span class="label label-primary" id="add_cp_button" style="cursor: pointer;" onclick="addVL()">+ Add VL </span> </div> <div style="height:0px;clear:both"></div> <div> <div id="ext_int_div_1"> <div class="section"> <fieldset class="scheduler-border"> <legend class="scheduler-border">External Interface 1</legend> <div class="sectionContent" style="border:0px solid grey;width:75%"> <div style="height:15px;clear:both"></div> <div class="form-group"> <div class="col-sm-4"> <label>Name</label> </div> <div class="col-sm-8"> <input type="text" class="form-control" name="vl_name_1" id="vl_name_1" placeholder="Name"/> </div> </div> <div style="height:15px;clear:both"></div> <div class="form-group"> <div class="col-sm-4"> <label>Connectivity Type</label> </div> <div class="col-sm-8"> <select class="form-control" name="vl_connectivity_type_1" id="vl_connectivity_type_1"> … -
Django: How to elegantly make user data inaccessible for the admin?
Lets imagine a case, where the user of a django application enter sensitive data into the application, which not even the admin should be able to see. What elegant way is there to achieve that? I image one could encrypt it with a key, that is unlocked by the user password. But I hope there are better or even build-in solutions. -
request is not sending to correct view in django urls
I am using Django rest framework for designing API, and I have below code urls.py from .views import UserView, UserDetails urlpatterns = [ url(r'^user/', UserView.as_view(), name = 'users'), url(r'^user/(?P<user_id>[0-9]+)/', UserDetails.as_view(), name = 'users_detail'), ] views.py from rest_framework.decorators import api_view from rest_framework import permissions class UserView(APIView): def get(self, request, format=None): print "I am in userview !!" ..... ..... return Response(users.data) def post(self, request, format=None): ..... ..... return Response(data) class UserDetails(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, *args, **kwargs): import ipdb; ipdb.set_trace() return Response('OK') And the endpoints that I am trying are below http://localhost:8000/api/user/ http://localhost:8000/api/user/1/ The problem what I am having is both the above URL requests are going to same UserView class, but actually http://localhost:8000/api/user/ should go to UserView class which is correct and happening now, and http://localhost:8000/api/user/1/ should go to UserDetails class which is not happening right now and the request was still going to 'UserView' class and I don't know why, can anyone please let me know what's wrong in my code?