Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve 404 Error for an AJAX call in Django
I am getting a 404 Error for an AJAX call in Django Here's my code: jQuery Script: $('#cluster-id').change( function(){ $.ajax({ url: '/ajax_demo/', type: 'get', dataType: 'json', complete: function( jqXHR, textStatus ){ console.log("complete " + textStatus); }, success: function( data, jqXHR, textStatus ){ console.log("success " + data); }, error: function(jqXHR, textStatus, errorThrown ){ console.log("error: " + errorThrown ); } }); I am trying to get the data( in json ) form this function: from django.http import JsonResponse def ajax_demo( request ): cluster = request.GET.get('cluster', None) data = { 'name' : 'abc' } return JsonResponse(data) I have set the url correctly too: urlpatterns = [ url( r'^$', views.main_page_demo, name = 'main_page_demo' ), url( r'^demo/', views.ajax_demo, name = 'ajax_demo'), ] I am new to AJAX and jQuery and i don't know what's the issue. -
Use own html template or forms in Django 1.10
I have to use a form in a template. But i have the HTML markup already. How can i replace the inputs on my html without loosing my styles? forms.py class contactForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'required': True, 'class': 'validate', 'label_tag': 'Your name: '})) email = forms.EmailField() message = forms.CharField() form.html <form action="." method="post"> <div class="row jsSubmit_button"> <div class="input-field col-md-6"> <input id="contact_name" type="text" class="validate" name="name" required> <label for="contact_name"> <i class="zmdi zmdi-account"></i>Your name <span>*</span> </label> </div> <div class="input-field col-md-6"> <input id="contact_email" type="email" class="validate" name="email" required> <label for="contact_email"><i class="zmdi zmdi-email"></i>Your email <span>*</span> </label> </div> <div class="input-field col-md-12"> <textarea id="textarea1" name="comments" class="materialize-textarea" required></textarea> <label for="textarea1"><i class="zmdi zmdi-border-color"></i>Write your message here <span>*</span> </label> </div> <div class="col-md-12"> <button type="submit" class="th_bt btn waves-effect" name="submit_btn"> Send<i class="zmdi zmdi-mail-send"></i> </button> </div> </div> </form> I tried something like this: {% for field in form %} <div class="input-field col-md-6"> {{ field }} <!--<input id="contact_name" type="text" class="validate" name="name" required>--> <label for="contact_name"> <i class="zmdi zmdi-account"></i>Your name <span>*</span> </label> </div> {% endfor %} but i cant make "label" appear where i want. -
Django elastic beanstalk deploy ignore subfolder in media folder
I have soemthing like this βββ media βββ djangoapp βββ .gitignore under media folder: βββ element βββ portrait Once after I deploy everything to AWS, I want to ignore portrait folder on the server, so i don't overwrite the picture user upload in there. However, no matter what I tried, each deploy is either overwrite the file inside portrait or deleting portrait folder. -
Getting "This field is required" error even though I set null=True and blank=True
I have a Post model for users submitting posts. I've given the content field of Post an attribute of blank=True. But for some reason django tells me content is still required. form_post.errors prints this: <ul class="errorlist"><li>content<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Here's my code: models class Post(models.Model): ... user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=76) content = models.TextField(null=True, blank=True) category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1') forms class PostForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget) title = forms.TextInput(attrs={'placeholder': 'title'}) class Meta: model = Post fields = [ 'title', 'content', 'category', 'image', 'id', 'user' ] views def post(request): allauth_login = LoginForm(request.POST or None) allauth_signup = SignupForm(request.POST or None) if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): print('valid') instance = form_post.save(commit=False) instance.user = request.user category = form_post.cleaned_data['category'] for a, b in CATEGORY_CHOICES: if a == category: category = b form_post.save() return HttpResponseRedirect('/%s' % category) else: print(form_post.errors) form_post = PostForm() context = { 'allauth_login': allauth_login, 'allauth_signup': allauth_signup, 'form_post': form_post } return render(request, 'post.html', context) else: return HttpResponseRedirect("/accounts/signup/") html ... <form method="post" action="" enctype="multipart/form-data">{% csrf_token %} <div class="submitContainer"> <div class="article_title_div"> {{ form_post.title|add_class:"article_title" }} </div> <div> </div> {{ form_post.category }} </div> <div class="submitButton"> <button class="submitArticleSubmit" type="submit">Post</button> </div> </form> ... Any idea why I'm getting this error? -
How to write sync api for rest framework or tastypie?
I have the below scenario. Person A has some friends. Person A can update only some tables of his friends. For example, School, Certifications of his friends can be added/updated by Person A because they are connected. All these updates whether to name change of Person A(by person A) as well as School/Certificate details of Person A or his friends by Person A need to be done by single api call - Sync api. We are using "last_modified" field to determine whether local record is newer or older. Can anyone suggest me best way to write this Sync api(permissions also should work) ? I am using tastypie but if you know about rest framework only, please explain in rest framework way. Please let me know for any questions. -
how to create website using Django
I have one Django App. I want to get this app on World Wide Web. Can anyone please help me with steps. Like Some server addition(e.g. Apache or Nginx),Configuration of server,Integrating with Django,Web Hosting,etc. Thanks -
I can't create login in django 1.10.1 version
I know it is basic to create login User Authentication. And I am a newbie here in using Django. I have a problem in creating User Authentication: Views.py def Logins(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) return HttpResponseRedirect('music/login') return HttpResponseRedirect('music/login') form = Userlogin return render(request, 'music/login.html', {'Login_form': Userlogin}) urls.py url(r'^login/$', views.Logins, name='login'), It shows It shows MultiValueDictKeyError at /music/login/. "'username'" Request Method: POST Request URL: http://127.0.0.1:8000/music/login/ Django Version: 1.10.4 Exception Type: MultiValueDictKeyError Exception Value: "'username'" login.html {% block body %} {% if form.errors %} <p>Something is wrong</p> {% endif %} <form action="" method="post"> {% csrf_token %} <label for="email">Login:</label> <label for="password">Password:</label> <input type="password" name="password" value="" id="username"> <input type="submit" value="login" /> </form> {% endblock %} Thanks in advance. -
Functional permissions in Django
Is there a built in way to assign functional permissions to users in Django? From documentations looks like Dajngo permissions are bound to Models. For example, what I want is to create is 4 types of user groups: Normal users, Managers, Admins and Superadmin. By default users in different groups will have access to perform different kinds of actions. For example users in Admin group can perform Task1, Task2 and Task3, but users in Managers group can only perform Task1 and Task2(no matter in which app these Tasks are). Further, user permissions can be modified for a user to revoke access from performing certain task. For example, by default all Admins can perform Task1, Task2 and Task3, but a particular admin's permission can be modified to perform only Task1 and Task3. Can this be achieved by build in Django permissions and groups or will need to write own permission system(or is there third-party Django app to do this)? If it will be better to write own permission and group system, any suggestion for design to follow. Thanks! -
Advertisements for Django App on Heroku
I have a django app that is hosted on heroku. I am very low on money, and need some source of revenue to pay for it. I want to implement ads on the website, but I cannot figure out how to do this. I have found django ad packages, but they seem to be outdated. Is there any way to do this, and use google adsense or something similar? -
Accessing django project outside LAN systems
I want to configure Django project such that I can access the data from outside world(from any computer or mobile which is connected to internet). But not connected on LAN or same WiFi network. Can someone help with the steps. Regards Neha -
How to include context variable in a wagtail cms field?
I am looking for a way to render a variable that will be available in the context of the the page where the cms page will be rendered. Ex: I have in the context the logged in user and I also have the last transaction he made on the website. I would like the text in the rich text field in Wagtail to be like this so that the marketing team can tweak the copy. Hello ||firstname|| thanks for your purchase. ||productname|| will be shipped to you soon. The expected delivery date is ||expected_delivery_date|| To be less confusing I replace the double brackets by double pipes to show that the templating system does not need to be django templates for those ones. Simple templating is enough maybe using https://docs.python.org/3.4/library/string.html#template-strings I think I can achieve this by doing: A stream field that would have blocks of rich text field and a custom block with the possible context variable they can use A custom render function that would regex and replace the merge tags in the rich text block with the context values Create a new filter for simple templating. ex: {{ page.body|richtext|simpletemplate }} Is there any more obvious way or out β¦ -
Django Class BasedView - UpdateView with multiple models and multiple forms
I have a list of users or users/roles type. I want to be able to click a link to Update their respective profiles users. When I perform click in Profile user, I should be able to edit the associated data to respective user according to profile that handle each of them. Each data profile is the simple page or template and manage for the same UpdateView class based view. In detail my scenario is the following: I have the User (inherit from AbstractBaseUser) model and here I manage the account data of the all users, this mean all data in common to all users roles or types which I want manage in my application such as: user student user professor user executive This users/roles type have their own model in where I define the respective fields to each of them. So, I have too, StudentProfile ProfessorProfile and ExecutiveProfile models, of this way: My User model is: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True) slug = models.SlugField( max_length=100, blank=True ) is_student = models.BooleanField( default=False, verbose_name='Student', help_text='Student profile' ) is_professor = models.BooleanField( default=False, verbose_name='Professor', help_text='Professor profile' ) is_executive = models.BooleanField( default=False, verbose_name='Executive', help_text='Executive profile', ) other fields ... def β¦ -
Migrate Django models to external database
I'm trying to set up an environment where users will be able to provide authentication for their SQL databases and allow me to run queries. Is there a way to migrate a Django model that I have designed onto their database? For example, I would have a Django model that stores their authentication info: class Oracle(models.Model): host = models.CharField(maxlength=20) user = models.CharField(maxlength=20) pass = models.CharField(maxlength=20) ... And I would want to migrate and manage this model on their DB: class Item(models.Model): title = models.CharField(maxlength=20) ... How do I generate the query code to create the table, and everything else Django models can provide (retrieve, modify, etc.)? -
Django-SQL Throwing error while fetching more records
Setup - Django 1.9 + MSSQL I have a situation in which my data selection from MSSQL is crashing when the records are going high (Say above 2000). Action performed is - Download data in CSV. Logs are mentioned below. Any clue will be helpful. Thanks. Error: ('07002', '[07002] [Microsoft][ODBC Driver 13 for SQL Server]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') -
How to change default Django forms?
I would like to change the default fields generated in Django forms. Googled it and found it but realized that I will have to do this procedure on all forms in my application (there are MANY forms). I have something in mind but don't know how to do it, it is create a file that will be loaded in every page, will contains code that defines a default field () for every Model field like TextField, DateField, TimeField ... This files must add two classes for each type of field (bootstrap form-control and other to validate based on the type), and then it will be just load the form with all these default configurations. Any idea? -
Sorted/searchable StackedInline options
I have three classes: Person Publication AuthorOrder Publication has a m2m field to Person through AuthorOrder. This is done to enable making it possible to set the order of authors, which matters for academic publications. However, the list of Persons is getting long, and it would therefore be nice if it was searchable or at least sorted. However, if I use the obvious method of setting a Meta class to Person, this causes the Persons to be sorted everywhere, including where I don't want them to be. Is there a way to make it searchable (best) or at least sorted without ruining the order elsewhere (ok)? Looks like this: -
Protecting my django source code on Heroku
I am determining my business model to deploy my django app to customers. So far in order to be competitive I want to deploy my app to customers Heroku account for 1 time fee and upgrade the app if customer decides to get the upgrade. I plan to deploy only .pyc binary files . I know it can reverse engineered but I hope it should be sufficient against hones customers. Is there more effective approach then this? -
Delete m2m through field from admin panel
I searched and could not find a way to do this. Here's my situation: I have 3 classes: Publication Person AuthorOrder The last is a through class that allows me to specify the author order for a publication, as this does not normally seem possible to do. Initially, I made Author a mandatory field (blank=False) for Publication and added a placeholder Person object to add Publications to that don't have a proper author. However, a better solution seems to be to just handle missing authors in Views appropriately. Now, I've changed the field to be optional, but I cannot seem to set the authors to empty via the admin panel. It gives me a "This field is required." error. My guess is that this is because the Person is required of the through class, but setting the Person to null/empty in the admin panel does not set the through object to null/empty. I found a workaround. One can delete the placeholder Person object. This unsets the through class from the Publications without deleting them via cascade as they are no longer mandatory. However, this is not always a good workaround, so I hope there's a better method. models.py There is β¦ -
django + nginx server gives 502 when switching to mysql
i currently have a django project that i have setup using vagrant and nginx as the web server. my web application serves to localhost:3000 and my nginx config is as follows. server { listen 80 default_server; listen [::]:80 default_server; location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } i then have my vagrant set up to forward port 80 to 8080, so that i can view my application on my host machine at http://localhost:8080 ALL of this works so far, until i switched my project from sqlite3 to MySQL. I am able to complete the migrations and my MySQL database shows all the tables created by django. After switching to MySQL i get a 502 gateway error on all pages. I even tried to vagrant ssh, and curl -i http://localhost:3000 and I get 'Connection Refused' -
Getting a 500 Internal Server error when trying to login a user
These are my URLS: url(r'^custom-api-auth/login$', views.login_view.as_view()), url(r'^custom-api-auth/logout$', views.logout_view.as_view()), These are my views: class login_view(APIView): def post(self, request): user = authenticate(username=request.data["username"], password=request.data["password"]) # return whatever you want on failure if not user or not user.is_active: content = {'credentials': ['The username or password you entered is correct. Please try again.']} return Response(content, status=status.HTTP_400_BAD_REQUEST) login(request, user) return Response(status=status.HTTP_204_NO_CONTENT) class logout_view(APIView): def post(self, request): logout(request) return Response(status=status.HTTP_204_NO_CONTENT) This is my HTML (using AngularJS): <form ng-submit="ctrl.loginUser()" name="myLoginForm"> <div class="form-group"> <label>Username</label> <input type="text" name="uname" class="form-control" ng-model="ctrl.loginuser.username" required> </div> <div class="form-group"> <label>Password</label> <input type="password" name="pwd" class="form-control" ng-model="ctrl.loginuser.password" required> </div> <input type="submit" value="Login"> </form> And this is my home.js JS: self.loginUser = function() { BaseService.loginUser(self.loginuser) .catch(function(errorResponse) { self.cerrorMessages = errorResponse.data; }); }; and this is my base.js (BaseService): self.loginUser = function(loginuser) { console.log('here'); return $http.post("/custom-api-auth/login", loginuser) .then(function(response) { $location.path("/"); }); }; When I click the login button in my form, it does print "here" in the console, which means it reaches BaseService.loginUser() however, it gives an error saying: angular.js:9866 POST http://127.0.0.1:8000/custom-api-auth/login 500 (INTERNAL SERVER ERROR)(anonymous function) @ angular.js:9866sendReq @ angular.js:9667serverRequest @ angular.js:9383processQueue @ angular.js:13248(anonymous function) @ angular.js:13264$eval @ angular.js:14466$digest @ angular.js:14282$apply @ angular.js:14571(anonymous function) @ angular.js:21571dispatch @ jquery-1.11.3.min.js:4r.handle @ jquery-1.11.3.min.js:4 It's hard for me to debug this issue β¦ -
Get index of element iterating thgrough multiple choices field django for in loop
I have MultipleChoiceFieldfield OPTIONS = ( ("AUT", "Austria"), ("DEU", "Germany"), ("NLD", "Neitherlands"), ) countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={"name": "select_0","class": "fff"}), choices=OPTIONS) I build my own html structure for this field and this is simplified code: {% for value, text in simple_search_form.countries.field.choices %} {{value}} {{text}} {% endfor %} How do I get and index of each element here? I need to have {{value}} {text}} {{index}} -
Django python change multipleChoiceField html output
I have multipleChicesField: OPTIONS = ( ("AUT", "Austria"), ("DEU", "Germany"), ("NLD", "Neitherlands"), ) countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={"name": "select_0","class": "fff"}), choices=OPTIONS) Right now it produces following html: <ul id="id_countries"> <li><label for="id_countries_0"><input class="fff" id="id_countries_0" name="countries" type="checkbox" value="AUT"> Austria</label></li> <li><label for="id_countries_1"><input class="fff" id="id_countries_1" name="countries" type="checkbox" value="DEU"> Germany</label></li> <li><label for="id_countries_2"><input class="fff" id="id_countries_2" name="countries" type="checkbox" value="NLD"> Neitherlands</label></li> </ul> How do I change my code to produce html structure something like: <div class="someClass"> <input class="fff" id="id_countries_0" name="countries" type="checkbox" value="AUT"> <label for="id_countries_0">Austria</label> </div> <div class="someClass"> <input class="fff" id="id_countries_1" name="countries" type="checkbox" value="DE"> <label for="id_countries_0">Germany</label> </div> -
How do I retrieve Email-ID from auth_user table in Django?
How do I retrieve Email-ID from auth_user table in Django? I am getting only id and username if I access the auth_user table. -
order_by creates duplicate entries
I have 4 models: User, Stack, Article and Rating and I want to get a set of all articles of a specific stack ordered by the current users rating, but this leads to duplicate entries in my QuerySet because the ratings are not only from the user itself: qs = stack.article_set.all().order_by("ratings__rating", "-pk") Users can create stacks, add articles, put them on a stack and rate the articles. Because the stacks can be shared between the users the rating model has two ForeignKeys: first to the article and second to the user class Rating(models.Model): article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name='ratings' ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='ratings' ) rating = models.IntegerField() class Stack(models.Model): title = models.CharField(null=True, max_length=100) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Article(models.Model): stack = models.ForeignKey(Stack, null=True, blank=True, on_delete=models.CASCADE) text = models.TextField(null=True, blank=True) With my query I get duplicate articles if the stack is shared and an article is rated by another user. How can i order them without the duplicates? -
Navigation Title is not well aligned and the navbar is a bit too thick?
For some reason the title is not properly aligned and the navbar is too thick? How will I be able to let it show properly aligned and smaller size? I am sure it can be done using Bootstrap itself, without additional css, right? Sorry, I can't post the image directly here, need higher reputation. Screenshot of the navbar {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <!-- This link is just added for support on StackOverflow. --> <link href="http://157.97.56.42:8000/static/css/bootstrap.css" rel="stylesheet"/> <style> html, body { margin-top: 65px; } </style> {% block base.head %} {% endblock %} </head> <body> {% block base.header %} <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <span class="navbar-brand">Developity</span> <ul class="nav navbar-nav"> <li><a href="/index" class="navbar-text">Home</a></li> <li><a href="/projects" class="navbar-text">Projects</a></li> </ul> </nav> {% endblock %} {% block base.body %} {% endblock %} {% block base.footer %} {% endblock %} <script src="{% static 'js/jquery.js' %}"></script> <script src="{% static 'js/bootstrap.js' %}"></script> <!-- This link is just added for support on StackOverflow. --> <script src="http://157.97.56.42:8000/static/js/jquery.js"></script> <script src="http://157.97.56.42:8000/static/js/bootstrap.js"></script> </body> </html>