Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Url NoReverseMatch, reverse with key arguments not found
I have a trouble with URl mapping. I want that title of the post to be in the url and have NoReverseMatch error when trying to do this. Here is app/urls.py file from django.conf.urls import url from .views import PostsListView, PostDetailView app_name = 'era' urlpatterns = [ url(r'^$', PostsListView.as_view(), name='posts_list'), url(r'^post/(?P<title>[\w-]+)/$', PostDetailView.as_view, name='post_details') ] app/views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class PostsListView(ListView): model = Post class PostDetailView(DetailView): model = Post context_object_name = 'post_details' template_name = 'era/post_details.html' and finally era/post_list.html {% extends 'era/base.html' %} {% block content %} {% for post in post_list %} <div class="post-block" style="width: 27%;float: left; margin: 3%; background-color: rgba(169, 169,169,0.5); padding: 2%; border-radius: 15px"> <h3>{{ post.title }}</h3> <br> {{ post.image_title }} <br> {{ post.short_description }} <br><br> <a href="{% url 'era:post_details' title=post.title %}" class="btn btn-primary" style="float: right">Read more</a> </div> {% endfor %} {% endblock %} Will be very gratefull for help! -
Django method in JavaScript causes TemplateSyntaxError
I am using ajax in javascript to send and receive database information that populate the html page. When I receive the data, I append it to the div elements. Every object I append should have a delete function. So I create a onclick method that passes along the unique id of that object My problem is that I can't seem to properly format the django url method with quotes for this call: onclick='removeFile("{% url 'delete_file' model['pk'] %}");' The full line look like this: $('#gallery tbody').append("<tr><td><a href='" + object['url'] + "'>" + object['file'] + "</a><span style='float:right'><button type='button' id='delete_button' class='btn btn-lg btn-danger' onclick='removeFile("{% url 'delete_file' model['pk'] %}");'></button></div></td></tr>") The error I get is a TemplateSyntax error Could not parse the remainder: '['pk']' from 'model['pk']' If I log the value of 'model['pk']' in the console, I get the correct ID. It loads correctly when I delete the onclick method (no delete function though). I have tried putting it in the html directly like this <button type="button" class="glyphicon glyphicon-remove-sign" onclick='removeFile("{% url 'delete_file' a.pk %}"); return false'> </button> where a is the model object from django and it works fine. How can I properly add the onclick method to the javascript append method? The full javascript … -
Updating Data: No Page Refresh
I'm trying to create a Like button, Here's what I tried, $('.like-click').on('click', function(e){ e.preventDefault(); var element = $(this); var quesURL = element.attr('like-href'); $.ajax({ url: quesURL, method: 'GET', data: {}, success: function (data) { var like_text = $(data).find('.like-click').html(); $(element).html(like_text); } }) }); Here's the HTML code for button, {% for data in datas %} ... <a class="like-click" like-href="URL">{% if user in Likes %}Liked{% else %}Like{% endif %}</a> ... {% endfor %} This code is working fine only for the First like button on webpage only not for others. How can I solve that problem? Thanks in advance! -
How to implement video call between users on django app
I have a django based website running, and want to allow my users to have video calls between them. Is there an API for that ? -
Django: How Do I load CSV data into a html template?
I'm building my first Django Web App and I'm trying to load data from a csv file into my html template. I've tried searching for a solution for the past hour but cannot find what I'm looking for. I would just like to load a row of data from a csv file and put it into my html template. I've no idea where to start. Any help would be greatly, greatly appreciated. -
Target WSGI script '/home/ubuntu/Django/bot/wsgi.py' cannot be loaded as Python module
i'm trying to devloping Django project. and i'm beginner. suddenly, today my server does not work. i think i do nothing. so i don't understand what is the problem. this is my /var/log/apache2/error.log mod_wsgi (pid=27808): Target WSGI script '/home/ubuntu/Django/bot/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=27808): Exception occurred processing WSGI script '/home/ubuntu/Django/bot/wsgi.py'. and when I try to enterd my server http://MYURL, 500 Internal Server Error occur. this is my wsgi.py code import os import sys sys.path.append('/home/ubuntu/Django') #sys.path.append('/home/ubutu/Django/bot') sys.path.append('/home/ubuntu/Django/myvenv/lib/python3.5/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bot.settings") application = get_wsgi_application() since i create my project, i have done anything on my wsgi.py however the error occurred now. -
How to send room name in connect function in Django Channels
I have several rooms in my programs. Each user can connect to these rooms and send messages. for each room, I have a group. I want to specify a room name for these group in connect function. but I don't know how to send room name in connect function. @channel_session_user_from_http def chat_connect(message): message.reply_channel.send({'accept': True}) @touch_presence @channel_session_user def chat_receive(message): data = json.loads(message['text']) myRoom = data['room'] messageChat = data['messagechat'] if not message.user.is_authenticated(): return Group(myRoom).add(message.reply_channel) Room_channels_presence.objects.add(myRoom, message.reply_channel.name, message.user) message.channel_session['room'] = myRoom #store in db try: room = Room.objects.get(slug=myRoom) message_model = Message( user = message.user, room = room, text = messageChat ) message_model.save() except: pass my_dict = { 'user': message.user.username, 'messagechat': messageChat } Group(myRoom).send({'text': json.dumps(my_dict)}) -
Zurb foundation Interchange with Django templates?
Is Zurb Foundation's Interchange compatible for use with Django templates? I can't see a way to get them to work together, though the issue is just a technical one - Interchange seems to want html file paths, while Django's html templates render inline. I suppose it would be possible to render the necessary templates each request into temporary files and hand those to Interchange, but that's not a very clean solution and would require a lot of boilerplate. I'm looking for a cleaner solution or for an alternative within Foundation and Django. -
Get sub-key's count in admin list-filter
Here is my models.py: class Category(models.Model): category = models.CharField(max_length=50, verbose_name=u"文章分类", default="") add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间") class Meta: verbose_name = u"文章分类" verbose_name_plural = verbose_name def __unicode__(self): return self.category class Article(models.Model): category = models.ForeignKey(Category, verbose_name=u"文章分类") title = models.CharField(max_length=100, verbose_name=u"文章题目", default="") content = UEditorField(width=1000, height=500,imagePath="media/", filePath="media/",verbose_name=u"文章内容") read_nums = models.IntegerField(default=0, verbose_name=u"阅读量") comment_nums = models.IntegerField(default=0, 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 self.title Now I need to show how many articles in category at django-admin page, in this page: How should I do? -
Django UpdateView get blank values?
So I'm creating a django website and I have an Edit Button. The edit shows a pop up with a few forms to edit. The problem is that the forms to edit are blank! instead of having the previous data. e.g- ServerName="Yossi" When I click edit instead of having "Yossi" in the form I have nothing. What do I need to add to the index.html or to the Class of PostEdit so I will have the previous data in the forms and not blank forms? models.py - from django.db import models # Create your models here. class serverlist(models.Model): ServerName = models.CharField(max_length = 30) Owner = models.CharField(max_length = 50) Project = models.CharField(max_length = 30) Description = models.CharField(max_length = 255) IP = models.CharField(max_length = 30) ILO = models.CharField(max_length = 30) Rack = models.CharField(max_length = 30) Status = models.CharField(max_length = 30) #date = models.DateTimeField(auto_now=True) views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query … -
Django load static
When I'm trying to change anything in css files, I can't see any changes. Like if I once built project, he saves this style, so if change background color in default.css from white to black and run the project, background still will be white. I think it comes from {% load static %} in html file but not quite sure. The only way I found to apply changes in css is to create new css file and link html with it. Any ideas how to fix it? -
Django Multiple User profiles (design decision)
The title might seem very familiar (lots of related questions but I couldn't find relevant to my use case). Here's my app info: Two types of user profiles (Basic & Professional) Basic user is an instance of User with an addition field (phone) Basic user posts questions (needs help with stuff) Pro users provid various services (help/answer the questions posted by basic users) Pro users belongs to an Organisation class, basic users don't. Also, Pro represents its own org, so an Organisation belongs to one profile (hence OneToOneField) Question: So I need help with deciding whether to create two separate profiles (BasicProfile & ProProfile) for each type or create a single Profile and use a boolean field that says whether a profile is_proor not (much like the django's is_superuser boolean field) Approach 1: class Organisation(models.Model): name = models.CharField(_('Name'), max_length=50) profile = models.OneToOneField(ProProfile, on_delete=models.CASCADE) ... class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone = models.CharField(_('Phone'), max_length=200, null=True, blank=True) class Meta: abstract = True def __str__(self): return self.user.get_full_name() class UserProfile(Profile): pass class ProProfile(Profile): verified = models.BooleanField(default=False, verbose_name=_('Verified')) Approach 2: class Organisation(models.Model): name = models.CharField(_('Name'), max_length=50) profile = models.OneToOneField(Profile, on_delete=models.CASCADE) class ProfileManager(models.Manager): def basic(self, **kwargs): return self.filter(is_pro=False, **kwargs) def pro(self, **kwargs): return self.filter(is_pro=True, **kwargs) … -
creating custom messages/exceptions creating account
I'm creating a Sign up view, and would like to create some custom messages, for instance if email is already taken or username is already taken. i've so far created a custom_exception_handler, but i'm not sure how to implement so that it is returning the UsernameInUse view class AccountViewSet(viewsets.ModelViewSet): lookup_field = 'username' queryset = Account.objects.all() serializer_class = AccountSerializer def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return (permissions.AllowAny(),) if self.request.method == 'POST': return (permissions.AllowAny(),) return (permissions.IsAuthenticated(), IsAccountOwner(),) def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): Account.objects.create_user(**serializer.validated_data) return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response({ 'status': 'Bad request', 'message': 'Account could not be created with received data.' }, status=status.HTTP_400_BAD_REQUEST) serializer class AccountSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(write_only=True, required=False) class Meta: model = Account fields = ('id', 'email', 'username', 'created_at', 'updated_at', 'first_name', 'last_name', 'password', 'confirm_password',) read_only_fields = ('created_at', 'updated_at',) def create(self, validated_data): return Account.objects.create(**validated_data) def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.save() password = validated_data.get('password', None) instance.set_password(password) instance.save() return instance exception_handler from rest_framework.views import exception_handler def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response is not None: response.data['status_code'] = … -
Save origin ration django easy thumbnails
Django and easy-thumbnails. Is it possible to change the image when saving it to the db? But I need to save origin aspect ratio, one thing to do is to decrease image size. For example, when user upload photo with 2400x1600 it become 1200x800 3200x2000 -> 1600x1000 but: 500x300 -> 500x300 So, actually I don`t know what exactly to do, but I need to decrease image size. -
How to create admin for each group in Django Admin?
I want to to make an (special,custom) admin for each group in Django Admin. The superadmin can manage all of users and groups and the admin of one group can manage only users who are in this group. How can I make it? Thanks! -
Django migrations old database, forgot one model before
I have existing database/production system pre-migration support for Django. We did start to use Djangos migration 2 years back it turns out I did forget to install migrations for one model that now causes problems. 2 years back I had the following models; Location, Tool and a third Log that points to instances of Location and Tool. The 0001_inital.py for Log model has a dependency to Tool for 0001_inital but for Locations it points to _ first _ Now, today I am trying to get Location to use migration (so I later can add things to it, needed now) for the first time... Running makemigration Location works and generates a new clean migration directory and all, but then when doing migrate --fake I get the following django.db.migrations.exceptions.InconsistentMigrationHistory: Migration log.0001_initial is applied before its dependency locations.0001_initial on database 'default'. Understand this is caused by the mistake earlier by forgetting to get migrations done for Locations when we started to use this in Django - any ideas how to resolve this in a good way? -
Django model request array
I am new to python and Django. I haven't found anything in documentations so I have to write here. I have such problem. I have cars table where you can find it's make, model. year and so on. Usually i make request by just Cars.objects.filter(make=x, model=y, year=z) I want to make search and all params are in array. There are many params and is it possible to make something like Cars.objects.filter(array) -
Django how to loop through objects and display variables in a template
I'm working with boto3 to display various data about my s3 buckets in AWS. I have the following code in views.py to display s3 page: class s3(TemplateView): template_name = 'project/s3.html' def get_context_data(self, **kwargs): context = super(s3, self).get_context_data(**kwargs) aws = boto3.resource('s3') buckets = aws.buckets.all() for bucket in buckets: totalSize = 0 bucketName = bucket.name createdAt = bucket.creation_date fileBuckets = boto3.resource('s3').Bucket(bucketName) for file in fileBuckets.objects.all(): totalSize += file.size context['buckets'] = buckets context['bucket'] = buckets context['createdAt'] = createdAt context['bucketName'] = bucketName context['totalSize'] = totalSize return context I'm trying to display these variables in a template like this: <div class="s3Items"> {% for bucket in buckets %} <div class="s3Name"> <div id="left"> <h4 id='s3ItemName'>{{ bucketName }}</h4> </div> <div id="right"> <ul id='s3ItemDesc'> <li>{{ createdAt }}</li> <li>{{ totalSize }}/4GB</li> <li> <button type="button" name="button" class='button delete'>Delete</button> </li> </ul> </div> </div> {% endfor %} But obviously this doesn't work. How can I iterate through those buckets in template? I also tried the below and it worked but not completely as I cannot get the total sizes of all files in each bucket: <div class="s3Items"> {% for bucket in buckets %} <div class="s3Name"> <div id="left"> <h4 id='s3ItemName'>{{ bucket.name }}</h4> </div> <div id="right"> <ul id='s3ItemDesc'> <li>{{ bucket.creation_date}}</li> <li>{{ ??? }}/4GB</li> <li> <button … -
django rest framework and forms: How to do
I have a model in my Django App as below. I am using ReactJs as frontend and pass data using Django Rest Framework. class Ingredient(models.Model): MUNITS_CHOICES = ( ('kg', 'Kilogram'), ('ltr', 'Liter'), ('pcs', 'Pieces'), ) name = models.CharField(max_length=200,unique=True,null=False) slug = models.SlugField(unique=True) munit = models.CharField(max_length=10,choices=MUNITS_CHOICES,default=KILOGRAM) rate = models.DecimalField(max_digits=19, decimal_places=2,validators=[MinValueValidator(0)],default=0) typeofingredient = models.ForeignKey(TypeOfIngredient, related_name='typeof_ingredient',null=True, blank=True,on_delete=models.PROTECT) density_kg_per_lt = models.DecimalField(max_digits=19, decimal_places=2,verbose_name='Density (kg/lt)',null=True,blank=True,validators=[MinValueValidator(0)]) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) As you see the model fields have lot of parameters like max_length, choices, ForeignKey(which is also kind of choices), DecimalField, CharField, DateTimeField etc I was creating and rendering forms using Django Forms. Also the validaton is done in the Form class. The advantage of this is the form is inserted very easily in the template using {{ form }}. and it takes care of all the parameters like max_length, choices, fieldtypes etc. Also we can validate the form and the errors are send back etc. So most the job is done automatically. But since i am using DRF i created a serializer class to create or update: class IngredientCreateUpdateSerializer(ModelSerializer): class Meta: model = Ingredient fields = [ 'name', 'munit', 'rate', 'typeofingredient', 'density_kg_per_lt', ] Here again i have to write the validation logic which i … -
Django, Elixir or NodeJS?
Quick question, I'd just like to know your opinions. Now, what should I learn? Django, Elixir or NodeJS. Which one is the best? Thx! -
Retrieving ID to use in a query, Django
I have a simple question I guess: I am trying to query my data base in order to retrieve the number of team members linked to a specific team, linked to a specific project. team_member_count = Project.objects.get(id = id).team_id.members.count() The query is for the project detail view using a url like : localhost/website/project/141/ In the shell my query is Project.objects.get(id = 141).team_id.members.count() but in the views I get : TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' My view is the following (retrieving data for chart.js) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None, *args, **kwargs): user_count = MyUser.objects.all().count() project_count = Project.objects.all().count() team_member_count = Project.objects.get(id = id).team_id.members.count() labels = ["Users", "Projects", "Team_number", "Green", "Purple", "Orange"] default_items = [user_count, project_count,team_member_count,28,12,32] data = { "labels":labels, "default":default_items, } return Response(data) -
Understanding Django Admin
I am building a web application using Django, let's say I have apps such college and department. my URL looks like below for the end users. urlpatterns = [ url(r'^add/$', collegeCreate.as_view(), name="college_create"), url(r'^(?P<college_id>[0-9]+)/info', collegeDetail.as_view(), name="college_detail"), url(r'^(?P<college_id>[0-9]+)/activate/', college_activate, name="college_activate"), url(r'^(?P<college_id>[0-9]+)/deactivate/', college_deactivate, name="college_deactivate"), url(r'^$', collegeList.as_view(), name="college_list"), url(r'^add/', departmentCreateView.as_view(), name="department_create"), url(r'^(?P<department_id>[0-9]+)/update/', departmentUpdateView.as_view(), name="department_update"), url(r'^(?P<department_id>[0-9]+)/info/', departmentDetailView.as_view(), name="department_detail"), url(r'^$', departmentListView.as_view(), name="department_list") ] How can i add views and urls for admin like above,currently i am achieve that by overiding get_urls in Model Admin ,and create separate views for admin but i am repeating same block, so what is the best way to achieve this -
Django - check email matching while registering
I am making a register page and want users to double check their email address. The second email is not in the User model, so I did this: class RegisterForm(forms.ModelForm): email = forms.EmailField(label="Email") email2 = forms.EmailField(label="Confirm Email") password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [#fields are going to be shown here 'username', 'password', 'email', 'email2', ] def clean_email(self): email = self.cleaned_data['email'] email2 = self.cleaned_data['email2'] if email != email2: raise forms.ValidationError("Emails must match") return email when I click on submit button, it raises a KeyError on "email2" and it goes to email2 = self.cleaned_data['email2'] Appreciate for any help! -
Modal Django Popup forms for User Input
I have a page which shows the portfolio of the user, in that page ,I have an 'Add New' button. I want that the add new button should popup instead of opening in new window and then user could save the new entry and after saving, the main portfolio page should display the new data too. I know it is possible with ajax, but even after looking for 2 days, I could not come up with a solution. My portfolio(base page) html is :- {% block stylesheet %} <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <<link rel="stylesheet" href="{% static 'css/portfolio.css' %}"> {% endblock %} {% block body %} <div class="container"> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-4"> <h2>My<b>Portfolio</b></h2> </div> <div class="col-sm-4"> <div class="search-box"> <div class="input-group"> <input type="text" id="search" class="form-control" placeholder="Search by Code"> <span class="input-group-addon"><i class="material-icons">&#xE8B6;</i></span> </div> </div> </div> </div> </div> <div class="mb-4"> <a shref="{% url 'add_new_form' %}" class="btn btn-primary">Add New</a> </div> <table class="table table-striped"> <thead> <tr> <th>#</th> <th>NSE Code</th> <th>Quantity</th> <th>Average Buy Price</th> <th>Total Buy Value</th> <th>Today's Change</th> <th>Today's Change %</th> <th>Overall Change</th> <th>Overall Change %</th> <th>Current Value</th> <th>Actions</th> </tr> </thead> {% for myportfolio in myportfolios %} <tbody> <tr> <td>1</td> … -
Django + Chart.js rendering issues
I am having some troubles figure out my issue. I am using Chart.JS in order to use graphs + data within my app. I followed a tutorial on youtube but I am getting an error that I do not know how to fix: I get a message error that t is nul .. but don't really know what it means ............................................................................................................................................................................................................................................................................................................ Chart.min.js:10 Uncaught TypeError: Cannot read property 'length' of null at Object.acquireContext (Chart.min.js:10) at t.construct (Chart.min.js:10) at new t (Chart.min.js:10) at (index):259 acquireContext @ Chart.min.js:10 construct @ Chart.min.js:10 t @ Chart.min.js:10 (anonymous) @ (index):259 here is my HTML: {% block extrajs %} <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js" integrity="sha256-vyehT44mCOPZg7SbqfOZ0HNYXjPKgBCaqxBkW3lh6bg=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js" integrity="sha256-N4u5BjTLNwmGul6RgLoESPNqDFVUibVuOYhP4gJgrew=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js" integrity="sha256-N4u5BjTLNwmGul6RgLoESPNqDFVUibVuOYhP4gJgrew=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js" integrity="sha256-c0m8xzX5oOBawsnLVpHnU2ieISOvxi584aNElFl2W6M=" crossorigin="anonymous"></script> <script> var endpoint = 'api/chart/data' var defaultData = [] var labels = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ console.log(data) }, error: function(error_data){ console.log("error") console.log(error_data) } }) var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, …