Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to install latest version of Django using pip
I am trying to install latest Django version 2.0.1 as mentioned on https://www.djangoproject.com/download/ that this is the latest official release but when I run command pip install Django==2.0.1 I get error. Error is shown in Image below. How can I install latest version? -
django-markdown can not support bold or italic?
I use the django-markdown module to make the comments support the markdown, but there is a problem. The bold and italic are not supported. Others, such as pre, title and so on, work well. why? django user-define templatetags from django import template import markdown register = template.Library() @register.filter def markdown_change(content): content = markdown.markdown(content,extensions=['markdown.extensions.extra','markdown.extensions.codehilite','markdown.extensions.toc',]) return content template <p>{{comment.content|markdown_change|safe}}</p> views.py def contact(request): if request.method == 'POST': if request.user.username: form = CommentForm(request.POST) if form.is_valid(): form.save() form = CommentForm() comment_list = Comment.objects.all().filter(public = True).order_by('id').reverse() if len(comment_list) > 5: data,comment_list=comment_paginator(request,comment_list) else: data='' response = True context = {'form':form,'comment_list':comment_list,'response':response,'data':data} return render(request,'contact.html',context=context) else: form = CommentForm() comment_list = Comment.objects.all().filter(public = True).order_by('id').reverse() if len(comment_list) > 5: (data,comment_list)=comment_paginator(request,comment_list) else: data='' context = {'form':form,'comment_list':comment_list,'data':data} return render(request,'contact.html',context=context) -
How can I decouple my models?
Quick view: two Profile objects make up a Pair object. A Chat object has a FK to a Pair object and acts as the gateway to the chat-room between the two Profiles. A Message object references two Profile objects. Problem: My code is in such a way that the integrity of a site-feature is contingent on the objects of two models having matching Primary Keys. Given a model Pair(denoting a "pair" of Profiles), and model Chat(related_name="chat_room"), here is where I believe the coupling takes place: utils.py: def get_room_or_error(room_id, user): """ Tries to fetch a chatroom for a Pair(of users) object. """ if not user.is_authenticated(): raise ClientError("USER_HAS_TO_LOGIN") # Find the room they requested (by ID) try: room = Pair.objects.get(pk=room_id).chat_room # HERE except Pair.DoesNotExist: raise ClientError("ROOM_INVALID") if room.staff_only and not user.is_staff: raise ClientError("ROOM_ACCESS_DENIED") return room # the arg. being passed in, room_id, is the PK of a Pair object retrieved from a template And the models to provide background: user_profile.models.py: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='is_profile_to') class Pair(models.Model): requester = models.ForeignKey(Profile, related_name='is_requester') accepter = models.ForeignKey(Profile, related_name='is_accepter') chat.models.py: class Chat(models.Model): pair = models.OneToOneField(Pair, related_name='chat_room') class Message(models.Model): room = models.ForeignKey(Chat, related_name='messages', null=True) # Currently unused... recipient = models.ForeignKey(Profile, related_name='is_recipient', null=True) sender … -
Django Rest Auth with Facebook login?
I have seen a lot of answers online but never got any clarity about how to move forward. I have configured django-allauth and django-rest-auth as per the documentation and have also added appId and the accessKey from facebook as per the documentation. I don't understand what this error is all about? "non_field_errors": [ "Incorrect input. access_token or code is required." ] It works fine with the normal login. But what configuration am i missing to make it login via JWT tokens? -
How to save a ModelForm that has conditionally-declared fields in __init__ but not in the Meta class?
I have a ModelForm that I can't save properly: class FooForm(forms.ModelForm): foobar = forms.IntegerField(required=True) def __init__(self, *args, **kwargs): baz = kwargs.pop('baz', None) super(FooForm, self).__init__(*args, **kwargs) if baz: self.fields['baz'] = forms.IntegerField(required=False) class Meta: model = FooBar fields = ('foobar',) Running the debugger when I try to save shows that baz is present in fields and cleaned_data, but unless I declare it in the Meta.fields then it doesn't save this field. How do I proceed in this situation? I don't know if I need baz in my fields until the form in initialized - how can I express this condition in the Meta class? -
traefik + nginx + django with docker
I try to deploy a Django server with Gunicorn and Nginx (for static files). When I test the Nginx server without traefik, all work fine. But when i put behind traefik, it give me a "Gateway Timeout" error. And I don't know why the link doesn't work between traefik and nginx... My config files : docker-compose.yml: version: '2' services: gunicorn: restart: always build: ./web links: - postgres:postgres - redis:redis volumes: - /usr/src/app - /usr/src/app/static env_file: .env expose: - "8000" environment: DEBUG: 'false' labels: - "traefik.enable=false" command: /usr/local/bin/gunicorn karibox.wsgi:application -w 2 -b :8000 nginx: restart: always image: nginx ports: - "80" volumes: - /www/static - ./nginx/sites-enabled/django_project:/etc/nginx/conf.d/mysite.template volumes_from: - gunicorn links: - gunicorn:gunicorn labels: - "traefik.backend=karibox" - "traefik.frontend.rule=Host:karibox.example.com" command: /bin/bash -c "envsubst '$$NGINX_HOST $$NGINX_PORT' < /etc/nginx/conf.d/mysite.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'" networks: web: external: name: traefik_webgateway Nginx sites enabled server { listen 80; server_name karibox.example.com; charset utf-8; location /static { alias /data/web/mydjango/static; } location / { proxy_pass http://gunicorn:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } log_format logi '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"'; -
create a list ordered by a queryset
views.py def appelli(request, corso_id): corsi = Corso.objects.filter( pk=corso_id) fasca = Corso.objects.get( pk=corso_id) appello=[ list(Iscrizione.objects.filter(corso1_id=fasca)), ...] return render(request, 'corsi/appello.html', {'appello':appello}) in the html use {{appello.0}} and I render this: [<Iscrizione: VFEW>, <Iscrizione: VFFF>] how can delete "Iscrizioni" and make a ordinate list? -
IntegrityError NOT NULL constraint failed on updating custom user in Django
I tried to create my own user model in Django. The user creation form work as properly but not when I tried to update it. When I tried to update a data by admin (for example in this case updating email) in Django administration it always return me an IntegrityError: NOT NULL constraint failed: accounts_user.password. Here is my UserAdmin: from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms import UserAdminPostForm, UserAdminUpdateForm from .models import User class UserAdmin(BaseUserAdmin): form = UserAdminUpdateForm add_form = UserAdminPostForm list_display = ('email', 'created', 'admin') list_filter = ('admin',) fieldsets = ( ('Account', {'fields': ('email', 'password')}), ('Profile', {'fields': ()}), ('Permissions', {'fields': ('active', 'staff', 'admin',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'staff', 'admin',)} ), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () admin.site.register(User, UserAdmin) And this is my Form: from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User class UserAdminPostForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password Confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email', ) def confirm_password(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def … -
Celery 4.1 on Django. Do I still need celerycam? Flower?
So, I am running celery 4.1 on Redis with the results being stored in postgresql. Celery is basically used as a backend to launch fire and forget batches from the web front end. A batch runs with some parameters and updates a database, no data is really returned back to the launching page, except a 200 or 202 status stating the batch was launched successfully. On Celery 3.1, I would never see TaskState in admin, unless celerycam was running. As I am putting through the Celery 4 through its paces, I do see TaskResults appear under /admin/django_celery_results/taskresult/ despite only running celery -A websec worker -l info. So, should I still use celerycam for something? Is Flower needed to replace it? I am hesitant about adding more moving parts to this configuration without a clear rationale/need for doing so. Yes, I won't be getting Flower's nice little status web pages and the like, but honestly I've been OK just with 3.1s TaskStates so far. -
Django Rest Framework - Throttling not working in development environment
I was writing tests for throttling when I found out that throttling doesn't seem to be working properly in development env (It seems to be working in production). None of the requests is getting throttled (anon and user). This is the REST settings. REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': ( 'rest_framework.pagination.LimitOffsetPagination'), 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_expiring_authtoken.authentication.ExpiringTokenAuthentication', ], 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle', 'accounts.throttles.ResendEmailThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/minute', 'user': '100/minute', 'resend_email': '3/hour', }, 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } Weird thing I noticed was that when I kept the limit to 0/minute, it starts throttling the requests. This is the test code. class AccountThrottlesTestCase(BaseAPITestCase): def setUp(self): super(AccountThrottlesTestCase, self).setUp() def test_resend_email_throttles(self): url = reverse_lazy('accounts:resend_email') for i in range(0, 3): response = self.client.post(url) self.assertEqual(response.status_code, status.HTTP_200_OK) response = self.client.post(url) self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS) Throttles not working. FAIL: test_resend_email_throttles (tests.unit.accounts.test_throttles.AccountThrottlesTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/rustbucket/evalai/tests/unit/accounts/test_throttles.py", line 39, in test_resend_email_throttles self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS) AssertionError: 200 != 429 ---------------------------------------------------------------------- Ran 286 tests in 15.994s Why is the throttling behaving funny? -
Send request from chrome extension to django
I am developing a chrome extension having three links login,registration,Sign out. This is my html page in chrome extension <form name="form1" method="POST"> <p><a href="https://localhost:8000/login.html class="login" id="Login">Login!</a></p> <p><a href="#" class="text" id="Registration">Registration!</a></p> <p><a class="text" id="Signout">SignOut!</a></p> </form> Manifest file: "background": { "scripts": ["popup.js"], "persistent": false }, "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "externally_connectable": { "matches": ["*://localhost:*/"] }, "permissions": [ "http://localhost:8000/", "tabs", "contextMenus", "<all_urls>", "storage" ] Popup.js: function login() { chrome.tabs.executeScript({ file: 'contentscript.js' }); } document.getElementById('login').addEventListener('click', login); where i have developed login and registration pages in Django frame work and i have successfully registered and login in local host Django .But when I click a registration button in chrome extension i have to open Django registration page which is in local server. For this how to send request from chrome extension to Django and how to get request from chrome extension in Django. -
Django MsSQL FreeTDS - Nvarchar(max) Auto Truncates
I'm using Django that is connected to AWS' RDS MSSQL. So I'm to input very long texts, but they are generally longer than 4000 characters. In Django, this specific field is using TextField and the data type in MSSQL is nvarchar(max). So my question now is how can I configure and increase its max length. I've got the assumption that it's supposed to be infinite (of course it's not). Help is desperately needed. I've read about it briefly here: How to get entire VARCHAR(MAX) column with Python pypyodbc. However, I'm using RDS and I have no idea in doing this as at all. Thank you all in advanced! -
How I should set up my Django project tree in production
I've moved my Django repo from development onto my remote DigitalOcean server ready for production. My question is - where do I put my apps, manage.py etc? My current tree looks like this: path: /home/zorgan/project and the contents of the directory is: env manage.py static app So I imported app, which is my repo, from Bitbucket. This contains my code including manage.py etc. Do I use this manage.py or do I use the manage.py in the outer folder? Do I remove the app directory altogethor and simply put it's contents (all my apps) inside /home/zorgan/project next to env, static etc? Feedback appreciated. -
change value of selected RadioSelect field in django
How can i change the value of the selected choice rendered as RadioSelect field in django? ....... ---newbie Thanks... template <div class="row"><div class="boxed_content">Classification of Research<br> {% for rdo in form.classif_res %} <div class="form-check form-check-inline"> {{ rdo }} </div> {% endfor %} <input class="form-control" type="text" name="classif_other" id="res_classifcation" /> </div></div> the model field is a TextField with one of the choices named as "Others." what i want to do is whenever the user selects "Others" the data that will be saved is the value from the textbox in the template.... -
How to pass form value to view django 2
I need to pass form value to view to make fiter result by id. Here is my form <form class="form-horizontal rating-form" action="{% url 'stories:rating' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="hidden" name="rating_value" id="rating_value" /> <input type="hidden" name="story" id="story_id" value="{{ story.story_id}}" /> </div> </form> In my urls.py I have, path('ratings', views.RatingView.as_view(), name='rating'), And in my views.py file I have, class RatingView(generic.ListView): template_name = 'stories/rating.html' context_object_name = 'rating_count'; def get_queryset(self): return Rating.objects.get(story_id=id).values('rating_value').annotate(total=Count('rating_value')) fields = ['rating_value', 'story'] I need to perform where story_id = id ( {{story.story_id}}) in query. How to get the post value inside get_queryset function? -
datetime.datetime(2017, 4, 6, 1, 44, 44, tzinfo=<UTC>) django
When i create my Model serializer with django-rest-framework and try to get from URL i got the next error 'unicode' object has no attribute 'tzinfo' But when i execute the shell of django a = Model.objects.all()[0:1] a[0].upload_date This is printed in shell datetime.datetime(2017, 4, 6, 1, 44, 44, tzinfo=) The field in the model upload_date = models.DateTimeField(blank=True, null=True) The serializer class ReportSerializer(serializers.ModelSerializer): class Meta: model = Reports fields = '__all__' I don't know how serialize this field -
Is possible handle a fail queue with django-rq
Im working with google´s api , sometimes this fail and throw a 500 (backenderror), but in django settings , im calling RQ_EXCEPTION_HANDLERS = ['path.to.my.handler'] as say RQ documentation, but they dont talk about how to requeue , like a try_catch if worker or job return an error. -
How To validate Formsets in Django?
I am new to Django FormSet, let say I have the form like follow. class PillarForm(ModelForm): class Meta: model = Pillar exclude = ("created_at", "updated_at", "is_active", "owner") PillarFormSet = formset_factory(PillarForm, validate_min=True) and my pillar model looks like follow class Pillar(models.Model): name = models.CharField(max_length=255) description = models.TextField(null=True) order = models.IntegerField() #SYSTEM FIELDS created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) report = models.ForeignKey(Report, on_delete=models.CASCADE) when my views look like follow def pillars_create(request, report_id): context = {} report = Report.objects.get(pk=report_id, is_active=True) form = PillarFormSet() if request.POST: form = PillarFormSet(request.POST) print(form.errors) return render(request, os.path.join(TEMPLATE_FOLDER, "create/index.html"), { 'report' : report, 'formset' : form }) but form doesn't showing the error messages for example name, order are required fields but it doesn't shows the error messages and form.is_valid is True, what mistake i made here. but if I create formset with fields max_fields, min_fields, 'validate_max' like it shows the message. PillarFormSet = formset_factory(PillarForm, max_num=5, min_num=4, validate_max=True, validate_min=True) -
Django Apache django.wsgi adjusting system path
I am having trouble determining why my django project is throwing an error when launched through apache. Everything runs fine however I am getting an import error for a library I have created. within django.wsgi I attempt the following. import sys sys.path.append('path/to/some/directory') This is added because I am trying to use source code from a library on my system that is not directly located within my django project. In my code, I try to import the library I added to my system path within django.wsgi. However, within my apache error.log, I am getting an import error for this above added module. What am I doing wrong? -
How to do a Django subquery
I have two examples of code which accomplish the same thing. One is using python, the other is in SQL. Exhibit A (Python): surveys = Survey.objects.all() consumer = Consumer.objects.get(pk=24) for ballot in consumer.ballot_set.all() consumer_ballot_list.append(ballot.question_id) for survey in surveys: if survey.id not in consumer_ballot_list: consumer_survey_list.append(survey.id) Exhibit B (SQL): SELECT * FROM clients_survey WHERE id NOT IN (SELECT question_id FROM consumers_ballot WHERE consumer_id=24) ORDER BY id; I want to know how I can make exhibit A much cleaner and more efficient using Django's ORM and subqueries. In this example: I have ballots which contain a question_id that refers to the survey which a consumer has answered. I want to find all of the surveys that the consumer hasn't answered. So I need to check each question_id(survey.id) in the consumer's set of ballots against the survey model's id's and make sure that only the surveys that the consumer does NOT have a ballot of are returned. -
Django-Autocomplete-Light Admin InLine for Many to many fields
I'm trying to get Django Autocomplete Light to work of a specific project. I've been struggling with using it in the admin for InLine Many2Many relations. #models.py class Person(models.Model): name = models.CharField() class Country(models.Model): country_name = models.CharField() persons = models.ManyToManyField(Person) #forms.py class CountryInlineForm(forms.ModelForm): class Meta: model = Country fields = ('__all__') widgets = { 'country_person': autocomplete.ModelSelect2(url='countries-autocomplete') } #admin.py class CountryInLine(admin.TabularInline): model = Country form = CountryInlineForm extra = 2 class PersonAdmin(admin.ModelAdmin): inlines = CountryInline, admin.site.register(Person,PersonAdmin) There are a couple of questions dealing with Django-Autocomplete-Light and InLines that recommend to use ListSelect2 instead of ModelSelect2, but it's still not working. This is probably not the best example, since I should have the M2M at the Person Model, but in my project I need it to work as an InLine. Thanks! -
How To Display Multiple Progress Bars In Django Template Using JS?
Here is my code, which displays the bar based on votes for just first option. {% extends 'polls/base.html' %} {% block main_content %} <head> <style> ....//all css styling </style> </head> <div id="Results"> <h1>{{question.question_text}}</h1> {% for choice in question.choice_set.all %} <div id="votes"><img style="border-radius: 2px; border-width: 2px; border-style: none solid solid none; border-color: darkblue;" src='{{choice.image2.url}}'/> <div style=" float: right; width: 88%;"> <b>{{choice.choice_text}}</b> <div id="myProgress"> <div id="myBar">{{choice.votes}} vote{{choice.votes|pluralize}} <script> move() function move(){ var elem = document.getElementById("myBar"); var width = 1; var id = setInterval(frame, 10); function frame(){ if (width >= {{choice.votes}}){ clearInterval(id); } else { width++; elem.style.width = width + '%'; } } } </script></div> </div> </div> </div> {% endfor %} </ul> <p id="info">Your Vote Has Been Stored!!</p> <br> </div> {% endblock %} Following is what it displays. I need to modify a code so that i could display all bars based on votes. Question and choice are the models. Javascript modification is encouraged. Please help. results.html image -
Django Rest Framework for commercial use
The question is: can I use Django Rest Framework for commercial use? The reason why I'm asking this is because in their website, they talk about "signing up for a paid plan". -
404 on slug in django
I am following a tutorial where they do something like this: <a href="{ % url 'films:add_comment' slug=film.slug %}">Leave a comment</a> They use slug. I have not been doing that, but have been referencing an ID. The parts of my code which I think are important to this are: films/urls.py: app_name = 'films' urlpatterns = [ url(r'^films/<int:film_id>/comment/', views.add_comment, name='add_comment'), ] films/views.py def add_comment(request, film_id): film = get_object_or_404(Film, pk=film_id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit = False) comment.post = post comment.save() return redirect('film:detail',film) else: form = CommentForm() template = 'films/add_comment.html' context = {'form':form} return render (request,template,context) add_comment.html: {% extends 'base_layout.html' %} {% block content %} <div class="create-comment"> <h2>Add Comment</h2> </div> {% endblock %} If I click the link I made which is: <a href="{ % url 'films:add_comment' film.id %}">Leave a comment</a> I get this: And if I manually alter the url to http://127.0.0.1:8000/films/2/comment/ I get this: But it looks like url 3 in that list matches what I typed? -
can we split django server log?
I just got django server log setup and I found there's this problem, the file gets TOO big in just a day if there are lots of traffics. I am wondering if it is possible to split the files in a certain time or when the file reaches a size? Thanks in advance for any advices