Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
following button on site not working
Hey guys I am writing a following system for my site and when I go into the admin page and force the user to follow it works fine but my following button doesnt work, it just refreshes the site and just wondering if anyone could help me with it please. Thanks in advance. urls.py urlpatterns = [ url(r'^profile/(?P<username>[\w.@+-]+)', views.UserDetailView.as_view(), name="viewprofile"), url(r'^profile/(?P<username>[\w.@+-]+)/follow', views.UserFollowView.as_view(), name="follow"),] views.py class UserFollowView(View): def get(self, request, username, *args, **kwargs): toggle_user = get_object_or_404(User, username__iexact=username) if request.user.is_authenticated(): is_following = UserProfile.objects.toggle_follow(request.user, toggle_user) return redirect("accounts:viewprofile") models.py class UserProfileManager(models.Manager): use_for_related_fields = True def all(self): qs = self.get_queryset().all() try: if self.instance: qs = qs.exclude(user=self.instance) except: pass return qs def toggle_follow(self, user, to_toggle_user): user_profile, created = UserProfile.objects.get_or_create(user=user) if to_toggle_user in user_profile.following.all(): user_profile.following.remove(to_toggle_user) added = False else: user_profile.following.add(to_toggle_user) added = True return added def is_following(self, user, followed_by_user): user_profile, created = UserProfile.objects.get_or_create(user=user) if created: return False if followed_by_user in user_profile.following.all(): return True return False class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile') following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='followed_by') objects = UserProfileManager() def __str__(self): return str(self.following.all().count()) def get_following(self): users = self.following.all() return users.exclude(username=self.user.username) -
How to set token authentication via AJAX in Django to secure the API url
I am using Django REST framework to have data available in JSON and using them to refresh the page via AJAX. How can I secure the URL that page is being updated with data and no one can access the API url. The url is visible in AJAX in html so it can be accessed but I would like to prevent it by token or any other proper authentication that only access to it has website. The URL is '/api/item/' (see in the AJAX code) serializers.py from rest_framework import serializers from .models import Item class ItemModelSerializer(serializers.ModelSerializer): class Meta: model = Item fields = [ 'title', 'value', ] views.py (in API) from rest_framework import generics from .serializers import ItemModelSerializer from .models import Item class ItemListAPIView(generics.ListAPIView): serializer_class = ItemModelSerializer def get_queryset(self): return Item.objects.all().order_by('sort') urls.py urlpatterns = [ #...urls... url(r'^api/item/', include('apps.item.api.urls', namespace='api-item')), url(r'^admin/', admin.site.urls), ] template - ajax setInterval(function() { $.ajax({ method: "GET", url: "/api/item/", success: function(data) { $("#items tbody").empty(); $.each(data, function (key, value) { var itemKey = key; var itemTitle = value.title; var itemValue = value.value; $("#items tbody").append( "<tr><td class='left'>" + itemTitle + "</td><td>" + itemValue</td></tr>" ) }) }, error: function(data) { console.log("error") console.log(data) } }) }, 3000) -
Django: Database returned an invalid datetime value. Are time zone definitions for your database and pytz installed
I currently execute the following code: statistics = Statistic.objects .filter(id=1) .annotate(timestamp=Trunc('timestamp_start','day', output_field=DateTimeField())) .values('timestamp') .annotate(usage_start = Min('usage_start')) I have 1 record in that statisitc table, the value for timestamp_start is: 2016-12-22T06:00:00+02:00 I do have pytz installed. I'm running sqlite database. Any idea how to resolve this? -
Django- Query filter, with a foreign relationship
I've got a querying problem in Django, using a MySQL Database, that I'm having trouble solving, due to being new to this. I have 2 models, Area and Form. An Area might have 1 or more Forms associated with it, so it has a foreign relationship with Forms: form = models.ManyToManyField(Form) In one of my Django Views, I want to get all the Forms that are "area-less", i.e. not associated with any Areas, from the Database, and use them in a template. For example, if I query the DB like this (polls being the app name): SELECT `polls_area_form`.`id`, `polls_area_form`.`area_id`, `polls_area_form`.`form_id` FROM `myproject`.`polls_area_form`; I get: id area_id form_id 1 1 1 2 1 3 3 2 3 Showing that in this example scenario, Area 1 is associated with Forms 1 and 3. Area 2 is associated with Form 3. So, here I'd want to retrieve Form 2 due to not being associated with any Areas. In my Views, in a simple situation where someone wanted to retrieve all Forms no matter what, I'd simply use all_forms = Form.objects.filter() (Python) and then use that to render my response to the request. I'm having trouble figuring out what the filter should be in … -
Creating Many-Element Form Field in Django
I want to allow users to fill out information about themselves upon sign up. A couple examples would be what languages they know, and what business skills they have. I want them to be able to type in skills like "Finance", press enter, and have it added to their list. Then on the same page they can type in "Accounting" and also enter it, without having to press a submit button each time. How do I create a field that users can add multiple elements to? The functionality I'm thinking of is similar to LinkedIn's "skills" section, where you can add as many things as you want but also delete ones you already have. I'd like to be able to query my database and match to any of the words in these fields. Here is an example of what I would like it to look like after a user has edited and submitted, just to give you an idea of what I'm talking about. -
How to access an array index by its value in a Django Template?
I have an step array and a method to access in which step the process is. This method returns the process name. I need to get the position of the array where the value is equal to the step I am at. Example: Models # models.py steps = ['passo_open','passo_edit','passo_add_file','passo_judge'] step = process.get_current_step() print step #prints 'passo_edit' Template # mytemplate.html {{ step }} # prints 'passo_edit' {{ steps }} # prints ['passo_open','passo_edit','passo_add_file','passo_judge'] What I need is to get 1 instead: myStep = 1 I know I can get the step by index, for example: {{ steps.3 }} ## prints 'passo_judge' I have a bunch of links for the steps but I have to print only if it's lower than the next_step. That's why I have to get the number so I can print the links in the template until myStep. How can I get the index of the array by its value inside the Django Template? -
In Django How determine or log the num of db calls in one view?
How i can determine the number of calls does by my app in one view call. I intent to make a decorator with this intention. @trace_db_calls def my_view(request): #code return HttpResponse('done') At this moment I am investigating how to do it, regards -
Error in viewing extended DetailView in Django
I'm extending a DetailView to show a list of item in the detailed view of an object. Even there are no errors, no output is shown. Here is the code listing. In the extended View class Developer_detail(DetailView): model = Developer template_name = 'en/public/developer_detail.html' def get_context_data(self, **kwargs): def get_context_data(self, **kwargs): context = super(Developer_detail, self).get_context_data(**kwargs) tasks_dev = Task.oblects.filter(developer=self.object) context['tasks_dev'] = tasks_dev return context In urls.py url(r'developer-detail_(?P<pk>\d+)/$', Developer_detail.as_view(), name='developer_detail'), In the template {% extends 'en/public/base.html' %} {% block title_html %} Developer Details {% endblock %} {% block h1 %} Developer Details - {{ object.name }} {% endblock %} {% block article_content %} <h4>{{ object.name }}</h4> <span>Login: {{ object.login }}</span><br /> <span>Email: {{ object.email }}</span> <h3>Tasks</h3> <table> {% for task in tasks_dev %} <tr> <td>{{ task.title }}</td> <td>{{ task.importance }}</td> <td>{{ task.project }}</td> </tr> {% endfor %} </table> <p> {{ object.description }} </p> {% endblock %} Above template rendering not showing either object or tasks_dev data. -
waitress can not found static file (django)
I have set the STATIC_ROOT and STATIC_URL correctly. I run 'python manage.py collectstatic', It work. BUT when I visit the web site, the waitress server Print the Error: Not Found: /static/cm/img/main_menu_hover_bg.png WARNING: django.request: Not Found: /static/cm/img/main_menu_hover_bg.png ... the web site content is no problem, but the js, css, img file not found, so the style is not the same as when I develop it using "manage.py runserver" I deploy it in windows. How to solve this problem? -
Serialize objects and parents in one-to-one relationship in django
I have two models : domain and speciality, where domain is a foreignkey in speciality: class Domain(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Speciality(models.Model): domain = models.ForeignKey(Domain, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name In my views, I do a filter on speciality, so I would obtain a queryset with all specialities and their domains, each object individually. I would like to serialize to obtain something like this: { object1 : { 'domain' : 'Computer science', 'specialities' : { {'pk': '1', 'name':'Programming'}, {'pk': '2', 'name':'Networking'} } }, object2 : { 'domain' : 'Mathmatics', 'specialities' : { {'pk': '3', 'name':'Algebra'}, {'pk': '4', 'name':'Geometry'} } } } So basically, I want to serialize from the child to the parent, instead of what I usually see: from parent to child. I can't see to do that with django ModelSerializer. Is there a way of doing it, or should I do it manually. -
One chart cant display the data
This chart shows correctly like so: But this one does not display the bar: It displays this line as incorrect where default2 is: Unresolved variable default2 EDIT I have commented down below for you to see and added a picture where this error displays: EDIT How do I make the chart above appear with bar like the other one? Been doing these for days and hours and looked for answers here with no luck. Hopefully you can see where I went wrong. Newbie to this so I appreciate all your help, folks! chart.js var endpoint = '/api/chart/data/'; var defaultData = []; var labels = []; var defaultData2 = []; var labels2 = []; $.ajax({ method: "GET", url: endpoint, success: function (data) { labels = data.labels; defaultData = data.default; setChart() }, error: function (error_data) { console.log("error"); console.log(error_data) } }); $.ajax({ method: "GET", url: endpoint, success: function (data) { labels2 = data.labels2; defaultData2 = data.default2; # default2 displays error/as incorrect??? setChart2() }, error: function (error_data) { console.log("error"); console.log(error_data) } }); function setChart2(){ var ctx = document.getElementById("myChart5"); var myChart5 = new Chart(ctx, { type: 'bar', data: { labels2: labels2, datasets: [{ label: 'Total', data: defaultData2, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, … -
django REST ldap authentication with Cassandra
I am writing a rest api using django rest framework. I store my data in Cassandra. I am using django-cassandra-engine as my backend. My api works fine, but now I need add LDAP authentication. I intend to use this package called django-auth-ldap. From what I understand django-cassandra-engine doesn't support django-auth module on which django-auth-ldap rely on? I have never worked with Cassandra before, and I consider myself a Django newbie. Can someone be so kind and give me few hints how can I do this? Much appreciated. Thanks in advance! -
Django: How to make the slug in a URL a "wildcard" such as in the stackexchange.com URL?
For my homepage I want the URL to have the structure homepage.com/primary_key/slug but I don't want a wrong slug to result in a 404. Also, a wrongly inputted slug should automatically correct itself, just as stackoverflow.com/questions/43823098/XXXXXXXXXXXXXdjango-how-to-make-the-slug-in-the-url-a-wildcard-such-as-in-the-stackexchang automatically corrects itself to stackoverflow.com/questions/43823098/django-how-to-make-the-slug-in-the-url-a-wildcard-such-as-in-the-stackexchang. How do I go about implementing this? -
Django comparing timezone with object field pub_date time
from django.http import HttpResponseRedirect def detail_view(request, pk): question = Question.objects.get(pk=pk) if question.pub_date >= timezone.now(): return HttpResponseRedirect(reverse('polls:index')) else: return render(request,'polls/detail.html', context{'question':question}) i tried in many ways but it did'nt work im sure the comparison statement does'nt work -
Rename/add prefix to third party app template tags?
Is it possible to add prefix or rename third party app template tags? Explanation: We use django_tables2 in our project. For performance purposes, we decided to migrate from django_tables2 to django_datatable (https://github.com/shymonk/django-datatable). We want to use django_tables2 for a couple of tables and migrate rest of them to django_datatable. The problem is that both django_tables2 and django_datatable uses the same template tag {% render_table table %}. And maybe there will be more problems when we go deeper. -
Django CreateView and UpdateView
I need to change the format of the rating field to display stars using JS instead of a text box. How do I access the id etc when using Createview and updateview? -
Using an attribute from a Model in a Django template
I have a Model called Game and in that model i have the attribute game_image where i store a name of an image i want to search in a folder, for example: example.jpg, and i wanted to use that atributte inside a form this is the Game Model code class Game(models.Model): game_image = models.CharField(max_length=200, default='DEFAULT VALUE') i wanted to use the attribute here, instead of example.jpg i wanted to get game_image and search for the image in the folder according to the attribute this is the code i have: <img src="{% static 'app/images/example.jpg' %}" /> i wanted something like this: <img src="{% static 'app/images/game.image' %}" /> I understand that this question is probably really dumb but i would aprecciate any help, if you need more code just say, thanks -
How to override template_name in SelectDateWidget (Django 1.11)
I need to wrap the fields in div. In Django 1.10: class CustomSelectDateWidget (SelectDateWidget): def render(self, name, value, attrs=None): ... output = [] for field in self._parse_date_fmt(): if field == 'year': output.append('<div class="input-field col s4">' + html['year'] + '</div>') elif field == 'month': output.append('<div class="input-field col s5">' + html['month'] + '</div>') elif field == 'day': output.append('<div class="input-field col s3">' + html['day'] + '</div>') return mark_safe('\n'.join(output)) It dosn`t work in Django 1.11. I tried to override 'django/forms/widgets/select_date.html': class CustomDateWidget(SelectDateWidget): def get_template_names(self): return ['accounts/custom_select_date.html'] But Django include 'django/forms/widgets/select_date.html'. No error messages are displayed. -
select all records from the parent table assuming something is present in the child
I'm tying to traverse up a one-to-many relationship to efficiently select all records from the parent table assuming something is present in the child table. from models.py class Meter(models.Model): deal = models.ForeignKey(Deal, on_delete=models.CASCADE) company = models.IntegerField() class Deal(models.Model): dealinfo = models.IntegerField() in English, select all of the deals that have meters from company #2 in SQL: select * from Deal where Deal.id in ( select distinct Deal_id from Meter where Meter.company = 2 ); I don't know how to do this without two queries. I can't even think of a good way to google for a solution. I tried this: result = Deal.objects.filter(meter__company=2) that I found here: How do you access parent and children relationships through the ORM with a conditional on the parent where record child exist? but it's an inner join and doesn't implement the "unique" phrase, so I get multiple records. -
How can I add addition or edit button like those in django admin
I want to add Add button beside every input in form from django form class to be like those in django admin How can I add those buttons to a ModelForm in django -
TemplateDoesNotExist at /lab/
In the dashboar.html, i extends the base.html, and it pop up a error that TemplateDoesNotExist at /lab/, and if i commen out the {% extends "base.html" %}, it can work, isuppose there is something wrong with my base.html. and here is my directory base.html <div id="header"> <span class="logo">Bookmarks</span> {% if request.user.is_authenticated %} <ul class="menu"> <li {% if section =="dashboard" %}class="selected"{% endif %}> <a href="{% url 'dashboard' %}">My dashboard</a> </li> <li {% if section =="images" %}class="selected"{% endif %}> <a href="#">Images</a> </li> <li {% if section =="people" %}class="selected"{% endif %}> <a href="#">People</a> </li> </ul> {% endif %} <span class="user"> {% if request.user.is_authenticated %} Hello {{ request.user.first_name }}, <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Log-in</a> {% endif %} </span> </div> dashboard.html {% extends "base.html" %} {% block title %}Dashboard{% endblock %} {% block content %} <h1>Dashboard</h1> <p>Welcome to your dashboard.</p> {% endblock %} views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth import authenticate, login from .forms import LoginForm from django.contrib.auth.decorators import login_required from .models import User, Device def lab_list(request): return render(request, 'lab/details/index.html') def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not … -
Button acting funny in Django
I've been trying to get a better understanding of DeleteView in Django following this turorial and everything works fine except that my button tag doesn't seem to be acting as it should. Instead, I had to use an input tag to make it work, which makes it impossible to place a glyphicon-trash(bootstrap) inside a submit button. I wonder if it has something to do with me running it on pythonanywhere.com as some websites suggest that a button tag won't work properly as an alternative for <input type="submit"> under certain conditions. Here's my code. (I kept both the button tag and the input tag for comparison purposes.) <ul> {% for card in all_cards %} <li>{{ card.front }} <form action="{% url 'delete-card' card.id %}" method="post"> {% csrf_token %} <input type="hidden" name="card_id" value="{{ card.id }}" > <input type="submit" class="btn btn-default" value="DELETE"> <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-trash"></span></button> </form> </li> {% endfor %} </ul> What puzzles me the most is that when the button tag is clicked, it gives me this error message. Failed to load resource: the server responded with a /like_treasure/ status of 404 (Not Found) *like_treasure is a name of a directory used in a completely different Django project. Any advice … -
Python Django: How to read from a hidden api
As seen above I've got a project where I need to read from an API that the above weather site populates its data from. How do I deal with such cases where the API is not exposed? A bit confused. I kindly request you to write me a simple demo like it would appear(url especially) in views.py with django. I'm new to Django and APIs in general. -
Save data in one to one model Django
I have two different Django apps. 1. geolocations 2. listings When the user or the admin create a new listing I need to update the geolocations model. So far this is what I have geolocations/models.py from django.db import models from apps.listings.models import Listing from geopy.geocoders import Nominatim # Create your models here. class ListingGEOLocations(models.Model): class Meta: # Set DB name db_table = 'livelocal_listing_geo_location' # Admin backend listing name verbose_name = 'Listing GEO Location' verbose_name_plural = 'Listings GEO Locations' geo_location = models.CharField( max_length=100, db_column='geo_location', unique=True, blank=False, null=False, verbose_name='Geo Location' ) listing = models.OneToOneField( Listing, db_column='listing', blank=False, unique=True ) def save(self, *args, **kwargs): geolocator = Nominatim() pass def __str__(self): return self.geo_location In my listings/models.py from django.db import models import uuid from django.template.defaultfilters import slugify class ListingRootCategory(models.Model): class Meta: # Set DB name db_table = 'local_root_category' # Admin backend listing name verbose_name = 'Root Category' verbose_name_plural = 'Root Categories' root_category = models.CharField( max_length=100, db_column='root_category', unique=True, blank=False, null=False ) slug = models.SlugField( blank=True, db_column='slug', null=False, unique=True, verbose_name='Slug' ) def save(self): self.slug = slugify(self.root_category) super(ListingRootCategory, self).save() def __str__(self): return self.root_category class ListingSubCategory(models.Model): class Meta: # Set DB name db_table = 'local_sub_category' # Admin backend listing name verbose_name = 'Sub Category' verbose_name_plural = 'Sub Categories' # … -
django apache wsgi multiple sites error RuntimeError: populate() isn't reentrant in Django
i have one site in a server.it run well now ,i want to run another site(different project ) in the same server. when i start the apache, only one site can work well.another will get the error (error says RuntimeError: populate() isn't reentrant in Django)