Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Basic Entity Management System
How can I design an Entity Management system in Django which can be able to adapt to any kind of entity with minimal code changes (e.g. a product in a catalog, patient information in healthcare etc.). Adding, removing, modifying the attributes of an entity should be simple It should allow for nested attributes (sub-entities) e.g Patient -> Consulting doctor Each attribute or sub-entity in the entity can have a set of business rules -
Django rest framework - DefaultRouter - One-to-One Nested Relationship
I need to represent a nested RESTful resource via Django Rest Framework. I have a two Django models: User and Profile, with a 1 to 1 relationship between them. I want to expose the following API structure: GET /api/users/<user_pk>/ PATCH /api/users/<user_pk>/ And also endpoints that deal with the user's profile, such as: GET /api/users/<user_pk>/profile/ PATCH /api/users/<user_pk>/profile/ Another constraint, is that I would like to use drf DefaultRouters, in order to keep the overall project implementation homogeneous, but I got aware that DefaultRouters only provides not satisfactory approaches, for instance: GET profile-list not needed, since I need only one object, not a list; GET profile-detail /api/users/<user_pk>/profile/<profile_id>/ is non-sense to introduce the profile_id. So, what's the drf's DefaultRouter Best Practice, or better approach, for this 1to1 nested relationship? -
django(v2.0.1) -- _str_() method shows Object but not notes in self.text(python3.5)
My models.py is like this: enter image description here My python's version is 3.5.x and django's version is 2.0.1, and when I went to admin's page, I got this page: enter image description here -
How to update user profile in Django
I want to let my student to update his profile after he logged in, but I don't seem to be able to code the profile update properly. This is my code: class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) <form method="POST" action="{% url 'profile_edit' %}" class="" > {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button>q </form> def profile_edit(request): user = request.student form = StudentForm(request.POST or None, initial={'name': user.name, 'surname': user.surname}) if request.method == 'POST': if form.is_valid(): user.student.name = request.POST['name'] user.student.surname = request.POST['surname'] user.save() return HttpResponseRedirect('index') context = { "form": form } return render(request, "registration/profile_edit.html", context) -
Iterate over all Django App models if Meta.managed = True
I want a script that iterates over all models for a given app that are managed=True and deletes the data. My non-managed models are views, etc that I don't want to touch. I am doing the following. It works. I want to know if there is a better or more pythonic way to do the same thing. Would it be sensible to define other Meta options in each model if I want to include or exclude them in such a method? from django.apps import apps def deletedata(): if app.upper() in [x.verbose_name.upper() for x in apps.get_app_configs()]: appmodels = apps.get_app_config(app).get_models() for appmodel in appmodels: if appmodel._meta.managed: appmodel.objects.all().delete() def main(): deletedata("foo") if __name__ == "__main__": main() -
Cannot find which model is getting error in Django
I have following model and after Migrate, I tried to add data through Admin page. However, I got the error NOT NULL constraint failed: HVAC_chiller.basicinfo_ptr_id. Referring to other stackoverflow, I understood problem. However, I cannot find any model which has attribute ptr. Does anyone know which attribute I should revise? models.py class BasicInfo(models.Model): title = models.CharField(max_length=100) manufacturer = models.CharField(max_length=50, blank = True) used_project = models.CharField(max_length=50, null=True,blank=True) cost=models.IntegerField(null = True, blank = True) url=models.URLField(null=True,blank=True) comment=models.TextField(null=True,blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class VRV(BasicInfo): InletT = models.FloatField(blank=True) OutletT = models.FloatField(blank=True) Capacity = models.IntegerField(blank=True) # Reference capacity COP = models.FloatField(blank=True) # Reference COP class CapacityFunction(models.Model): name=models.CharField(max_length=100, blank = True) c1=models.FloatField() c2=models.FloatField() c3 = models.FloatField() c4 = models.FloatField() c5 = models.FloatField() c6 = models.FloatField() minX= models.FloatField(blank=True) maxX = models.FloatField(blank=True) minY = models.FloatField(blank=True) maxY = models.FloatField(blank=True) def __str__(self): return self.name class EIRofTemp(CapacityFunction): pass class EIRofPLR(models.Model): name = models.CharField(max_length=100, blank=True) c1=models.FloatField() c2= models.FloatField() c3 = models.FloatField() c4 = models.FloatField(blank=True,null=True) minX = models.FloatField(blank=True) maxX = models.FloatField(blank=True) def __str__(self): return self.name class Chiller(VRV): CONDENSER_CHOICES = ( ('WaterCooled','WaterCooled'), ('AirCooled', 'AirCooled'), ('EvaporativelyCooled','EvaporativelyCooled') ) Condenser=models.CharField(max_length=15,choices=CONDENSER_CHOICES,default='Water') CHWFlowRate=models.FloatField(blank=True,null=True) CWFlowRate=models.FloatField(blank=True,null=True) minPLR=models.FloatField(blank=True,null=True) maxPLR=models.FloatField(blank=True,null=True) optimumPLR=models.FloatField(blank=True,null=True) minUnloadRatio=models.FloatField(blank=True,null=True) CapacityFunction=models.OneToOneField(CapacityFunction,blank=True,null=True,on_delete=models.CASCADE,related_name='cap') EIRofTemp=models.OneToOneField(EIRofTemp,blank=True,null=True,on_delete=models.CASCADE,related_name='eirtemp') EIRofPLR = models.OneToOneField(EIRofPLR, blank=True,null=True, on_delete=models.CASCADE,related_name='eirplr') -
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?