Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Views Parameters
I have made a Django Model like this: Student Class, Subject Class - foreign key to Student Class Grade Class - foreign key to Subject Class In my understanding, I have set it up so that: Multiple Students can have multiple Subjects, and each Subject that students are in will have different Grades. I am trying to make a separate page for each student, so each page will display the Student name, Subjects the student is taking, and the Grade for each Subject. This is my views.py file for the page (I have set the url as /(student_pk)/ for each student's page) from django.shortcuts import render from .models import Student, Subject, Grade def detail(request, student_pk, subject_pk): stud = Student.objects.get(pk=student_pk) subject = stud.subject_set.all() sub = Subject.objects.get(pk=subject_pk) grade = subject.grade_set.all() context = { 'student_pk':student_pk, 'subject':subject, 'grade':grade, } return render(request, 'studentinfo/detail.html', context) The views parameter to my knowledge can only take 2. Is this the right way to do so? I have a feeling it is not and that my models itself is setup wrong for my purpose. Thank you. -
Receiving the error "Struct() argument 1 must be string, not unicode" when using Django
I am receiving the error "Struct() argument 1 must be string, not unicode" when running a script in Django but it runs OK in python. I'm trying to translate the hex version of a SID from Active Directory to the string version. The error says argument 1 is unicode but from what I can tell it's not. From what I can tell argument 1 is the sliced value of SID. Any help is appreciated. Here is the code: result = con.search_s(ldap_base, ldap.SCOPE_SUBTREE, criteria, attributes) sid = result[0][1]["objectSid"][0] if sys.version_info.major < 3: revision = ord(sid[0]) else: revision = sid[0] if sys.version_info.major < 3: number_of_sub_ids = ord(sid[1]) else: number_of_sub_ids = sid[1] iav = struct.unpack('>Q', b'\x00\x00' + sid[2:8])[0] sub_ids = [struct.unpack('<I', sid[8 + 4 * i:12 + 4 * i])[0] for i in range(number_of_sub_ids)] sid = 'S-{0}-{1}-{2}'.format(revision, iav, '-'.join([str(sub_id) for sub_id in sub_ids])) [Error part 1][1] [Error part 2][2] [sid value][3] [1]: https://i.stack.imgur.com/GV0yb.png [2]: https://i.stack.imgur.com/rxhW7.png [3]: https://i.stack.imgur.com/4lzed.png -
django rest api with jwt authentication is asking for csrf token
I am new to django rest api framework. I am using JWT token based authentication for the rest api with the following setting - REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } AND JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler', 'JWT_SECRET_KEY': SECRET_KEY, 'JWT_GET_USER_SECRET_KEY': None, 'JWT_PUBLIC_KEY': None, 'JWT_PRIVATE_KEY': None, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 0, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300), 'JWT_AUDIENCE': None, 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': ('JWT','Bearer'), 'JWT_AUTH_COOKIE': None, } Now based on this, I have used postman plugin inside chrome and tried to test my web api for authentication using the steps below - I used the url http://127.0.0.1:8000/webs/auth-jwt/ with the credentials to obtain the token. I used the url http://127.0.0.1:8000/webs/testspsearch/ and passed the token generated in step 1 as Authorization Bearer . This is defined as POST method but when I do this, I get the error -> CSRF verification failed. Request aborted. HTTP 403 error. Can you please let me know what am I doing wrong in this? -
Django exact match of ForeignKey Values
class Sentence(Model): name = CharField() class Tokens(Model): token = CharField() sentence = ForeignKey(Sentence, related_name='tokens') I want to implement two cases: Sentence consists exactly of three tokens ['I', 'like', 'apples']. So list of sentence.tokens.all() is exactly ['I', 'like', 'apples']. Same as above, but contains tokens (part of sentence). Sentence.objects.annotate(n=Count('tokens',distinct=True)).filter(n=3).filter(tokens__name='I').filter(tokens__name='like').filter(tokens__name='apples') doesn't work, since it matches I I I as well. Is there any way to filter on exact set of values in ForeignKey? -
Django Admin "Inline and Parent's Inline" Custom Validations
I'm trying to create two validations in one Django Admin page; an Inline's validation and the Inline's Parent Validation. Let me show you my code first: models.py class Rule(models.Model): disease = models.ForeignKey(Disease,related_name="diseases") measure_of_belief = models.PositiveIntegerField( \ help_text="The measure of belief (percentage) that a disease is present given this evidence exists", \ default=0,validators=[MinValueValidator(0), MaxValueValidator(100)]) measure_of_disbelief = models.PositiveIntegerField( \ help_text="The measure of disbelief (percentage) that a disease is present given an evidence does not exists", \ default=0,validators=[MinValueValidator(0), MaxValueValidator(100)]) Condition_Order = models.CharField(\ help_text="This field will be the basis of the condition's hierarchy/order, If two or more evidence exists in a rule." + \ "<br/> This statement only accepts the corresponding 'evidence number', an 'or' (disjunction), and an 'and' (conjuction)." + "<br/> e.g. 24 and 34" \ ,max_length=500,default=None,blank=True, null=True) archived = models.BooleanField(default=False) def __str__(self): return "{}-{}".format(self.id,self.disease) class Meta: verbose_name = "Rule" verbose_name_plural = "Rules" class Rules_Evidence(models.Model): rule = models.ForeignKey(Rule,related_name="rules") evidence = models.ForeignKey(Evidence,related_name="evidences") class Meta: verbose_name = "Rules Evidence" verbose_name_plural = "Rules Evidences" def __str__(self): return "{}".format(self.id) Here's my models. What I'm trying to achieve is to create a validation for the "condition order" field. admin.py class BaseEvidenceAdminInlineSet(BaseInlineFormSet): # 'Rules_Evidence' Validation def clean(self): super(BaseEvidenceAdminInlineSet, self).clean() repetition = [] for form in self.forms: string_error = "Please … -
Django insert permission in migration
I need to populate auth_group_permission table in a migration. I've created a migration with this code: # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-12-05 10:07 from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group, Permission from django.contrib.auth.management import create_permissions def add_group_permissions(apps, schema_editor): for app_config in apps.get_app_configs(): create_permissions(app_config, apps=apps, verbosity=0) #Workers group, created = Group.objects.get_or_create(name='Workers') can_add_worker_task = Permission.objects.get(codename='add_worker_task') group.permissions.add(can_add_worker_task) group.save() class Migration(migrations.Migration): dependencies = [ ('crowdsourcing', '0005_add_view_permission'), ('auth', '0001_initial'), ] operations = [ migrations.RunPython(add_group_permissions), ] But when I execute "python manage.py migrate" commando I received this error: "django.contrib.auth.models.DoesNotExist: Permission matching query does not exist". I think the problem is that the "auth_permission" table is still empty. Can i solve? -
Django test doesnt update model
Probably something simple but its bugging me that one of my tests is failing. I have a view that handles a POST request from a form to edit a model. I cant see why this test is failing (name does not change): def test_edit_club_view(self): """ Test changes can be made to an existing club through a post request to the edit_club view. """ new_club = Club.objects.create( name = "new club name unique" ) self.client.post("/clubs/edit/{}/".format(new_club.pk), data = {"name": "edited_club_name"}) self.assertEqual(new_club.name, "edited_club_name") The test for the form passes: def test_club_can_be_changed_through_form(self): """ Test the ClubForm can make changes to an existing club in the database. """ form_data = { "name": "new club name" } add_club_form = ClubForm(data = form_data, instance = self.existing_club) add_club_form.save() self.assertEqual(self.existing_club.name, "new club name") Also, if I print the values for the name field in the view, it appears to be changed there, but not reflected in the test case. AssertionError: 'new club name unique' != 'edited_club_name' -
Patch Method with Extend User Model in Django Rest Framework
I'm confusing to create a Patch method with Extend User Model in Django Rest Framework. Hope your guys helps. My Extend User Model: class Profile(models.Model): user = models.OneToOneField(User, unique=True) bio = models.CharField My serializers: class UserEditSerializer(ModelSerializer): username = serializers.CharField(source='user.username') first_name = serializers.CharField(source='user.first_name') last_name = serializers.CharField(source='user.last_name') email = serializers.CharField(source='user.email') class Meta: model = Profile fields = [ 'username', 'email', 'first_name', 'last_name', 'bio', ] My Viewsets: class UserUpdateAPIView(ReadOnlyModelViewSet): queryset = Profile.objects.all() serializer_class = UserEditSerializer @detail_route(methods=['PATCH']) def edit(self, request): user_obj = User.objects.get(id=request.user.id) serializer = UserEditSerializer(user_obj, data=request.data, partial=True) print(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(status=status.HTTP_400_BAD_REQUEST) Error: AttributeError at /api/v1/users/account/edit/ Got AttributeError when attempting to get a value for field `username` on serializer `UserEditSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'RelatedManager' object has no attribute 'username'. -
Hostname showing different page to IP Address
I'm creating my Django website via Digital Ocean using Nginx/Gunicorn via this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 In my Django settings I have: ALLOWED_HOSTS = ['venvor.com', '174.138.62.249'] The first is my hostname, and second is the corresponding IP Address. Here's the networking tab in my Digital Ocean showing that: https://i.imgur.com/YTu6wIW.png However these 2 pages show 2 different things. If you click here my hostname shows this Nginx page : http://venvor.com/ but the IP Address shows the initial Django page: http://174.138.62.249/ Any idea why they are different? -
Basic: How to use PATCH Method User Model in Django Rest Framework
I have problem with using PATCH Method User Model in Django Rest Framework. Hope your guy helps and save my time. Urls.py urlpatterns = [ url(r'^account/edit/$', UserDetailAPIView.as_view({'patch': 'edit'})) ] Views.py: class UserDetailAPIView(ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @detail_route(methods=['PATCH']) def edit(self, request): user_obj = User.objects.get(id=request.user.id) serializer = UserRegisterSerializer(user_obj, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(status=status.HTTP_400_BAD_REQUEST) Serializer: class UserRegisterSerializer(ModelSerializer): class Meta: model = User fields = [ 'email', 'first_name', 'last_name' ] Error: It's not partial update. It update all fields with let it blank. -
In what cases should I use UUID as primary key in Django models
What are advantages and disadvantages of UUID field? When should I use it as a primary key? When should I use default primary key? My table has many rows. Is it possible that max value of default primary key will be exceeded? I use PostgreSQL. -
Django app: on modelse.py any kind of def is not working
here my code, last two function is not working i am also trying more function but still they are not working. from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) # nothing to show def __str__(self): return self.title def snippet(self): return self.body[0:50] -
How do I retrieve informations from my facebook user token using python in a django web app?
I just created a web application using django. It has a login page where a user can login using facebook or twitter or github and I did that using django_social_auth2. In my settings.py, I added the required authentication backends: AUTHENTICATION_BACKENDS = ( 'social_core.backends.github.GithubOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend',) added social_django in my installed apps and ask for the following informations: SOCIAL_AUTH_FACEBOOK_SCOPE = [ 'email', 'user_posts', 'user_location',] A user who wants to login, gets the following message: And in the admin page, I get a token with the granted informations. Now, what I want to do is extract the user's informations without having to paste the token in the facebook graph API explorer. How can I do this in python and integrate it in my Django app ? I have read the documentation regarding the granted informations and the users will only be me and my teaching assistant. Thanks -
Using mysql and mongodb together for Django
Can I use both relational-database(eg : mysql) and non-relational database(eg : mongodb) together as bacekend dbs for a Django project? If possible then how? I use Django version 1.11 -
object is not shown in CategoryView
I wrote in top.html <div> <a href="#"> Category </a> <div> {% for category in category_content %} <a href="{% url 'category' category.name %}"> {{ category.name }} </a> {% endfor %} </div> </div> in category.html like <div> {% for content in queryset %} <h2>{{ content.title }}</h2> <a href="{% url 'detail' content.pk %}">SHOW DETAIL</a> {% endfor %} </div> When I put in top.html,no error happens and page is shown but no <h2>{{ content.title }}</h2> is shown here. I wrote in views.py class CategoryView(ListView): model = Category template_name = 'category.html' def get_queryset(self): category_name = self.kwargs['category'] self.category = Category.objects.get(name=category_name) queryset = super().get_queryset().filter(name=self.category) return queryset def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['categories'] = Category.objects.all() return context def category(self,pk): queryset = self.base_queryset() category = self.kwargs.get("category") queryset = queryset.filter(category__name=category) return queryset in urls.py urlpatterns = [ path('top/', views.top, name='top'), path('category/<str:category>/',views.CategoryView.as_view(), name='category'), ] in models.py class Category(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) class Index(models.Model): title = models.CharField(max_length=100) text = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) I want to show list of Index data that are by filtered Category in my db in category.html .For example, it is my ideal system ,when I put Python link in top.html,content.title which is related with Python is shown in category.html .But … -
What is JsonResponseMixin? How they work with the class based views
I have read about mixins and understood that A mixin is a special kind of multiple inheritance and provide a lot of optional features for a class. Now i want to know what are JsonResponseMixin and why they are used. class JsonResponseMixin(object): def render_to_json_response(self,context,**response_kwargs): return JsonResponse(context,**response_kwargs) def get_data(self,context): return context This is the code i found in mixin.py .Can someone please expain why this is used .Are they used in serializing data?Please elaborate -
Django: Use admin styles (css files and widgets) in my own app
Is there a simple way to use the admin-style css and widgets in your own app? -
How to get objects based on existence of object of another model?
In my Django app I have the following models: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET('deleted_user')) post_id = models.BigAutoField(primary_key = True) content = models.CharField(max_length = 2000) timestamp = models.DateTimeField(auto_now_add=True) original_poster = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET('deleted_user'), related_name='author') class Following(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='follows') followed_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='followed') I am using standard User model included in Django. Now I would like to retrieve posts of all users that are followed by a given user. What is the simplest way to achieve that? -
Django URLs randomly shows ImproperlyConfigured
I sometimes receive an ImproperlyConfigured "The included URLconf 'app_name.urls' does not appear to have any patterns in it." on my website. When I revisit the URL that caused the error, it works fine. The error shows that "patterns" is a module in these cases. Most of the time it properly loads my URLs. Does anyone spot a problem with my URLs? This is a strange issue that occurs on both the root URL (/) and the details page (####/details). I've never seen an error for my other URLs, but they don't receive much traffic. I haven't been able to reproduce the error, but I receive it several times a day. I'm using Python 3.5.2 with Django 2.0. The codebase was original written with Django 1.6 I believe. I recently migrated to 2.0 and that is when I noticed the issue. I modified django/urls/resolvers.py to log the 'patterns' variable and most of the time I receive this list: [<URLResolver <URLPattern list> (admin:admin) 'admin/'>, <URLPattern '<int:pk>/details' [name='details']>, <URLPattern 'check/' [name='check']>, <URLPattern 'logout/' [name='logout']>, <URLPattern 'search/' [name='search']>, <URLPattern 'features/' [name='features']>, <URLPattern 'terms-of-service/' [name='terms']>, <URLPattern 'privacy-policy/' [name='privacy']>, <URLPattern '' [name='index']>] urls.py from django.urls import path, re_path from django.contrib import admin from app_name import views … -
Jinja2 and Django Set up
Having trouble setting up Jinja2 on Django, attempting to set up on the latest iterations of the software using the how to below. Just wondering weather this setup is still relevant it's been a long time since this post. How to use jinja2 as a templating engine in Django 1.8 -
How do I upload and manipulate excel file with Django?
Ok, I had a look at the UploadFile Class documentation of the Django framework. Didn't find exactly what I am looking for? I am creating a membership management system with Django. I need the staff to have the ability to upload excel files containing list of members (and their details) which I will then manipulate to map to the Model fields. It's easy to do this with pandas framework for example, but I want to do it with Django if I can. Any suggestions. Thanks in advance -
How to use selenium grid with random clients(means no registration of IP)
Is it possible to use selenium server on a website where any user having the servers IP address can join-in? Without going to the server and personally registering the user as mentioned here. I work in an institution where proxy-IP addresses are cycled for security purposes. But I need no run a website on my server which allows clients to go to my website and perform minor automatic browsing and data scraping from a different website. To ensure correct data entry. -
VueJS Authentication with Django REST Key
I can retrieve a key after logging in through my Django REST API, but then I am wondering how I should store that key. I'm not really using Django, but I imagine I have to store the cookie myself then or something. I'm using Axios for VueJS to interact with the API. I am using django rest auth to get the token. -
How to manually make queries into the DB using Django?
Sometimes, I have to make migrations that implie in loss of the db. Then I have to manually go to the /admin page and re-insert every piece of data to start exploring my methods. So, is there any way to manually insert data into the db when I create the models.Model classes? (I'm using the default Django's db: sqlite) -
Categories' list is not shown
Categories' list is not shown.I wrote in views.py class CategoryView(ListView): model = Category template_name = 'category.html' def get_queryset(self): category_name = self.kwargs['category'] self.category = Category.objects.get(name=category_name) queryset = super().get_queryset().filter(category=self.category) return queryset def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['categories'] = Category.objects.all() return context in category.html <div> {% for content in queryset %} <h2>{{ content.title }}</h2> <a href="{% url 'detail' content.pk %}">SHOW DETAIL</a> {% endfor %} </div> <div> <a href="#"> Category </a> <div> {% for category in categories %} <a href="{% url 'category' category.name %}"> {{ category.name }} </a> {% endfor %} </div> </div> in models.py class Category(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) Now FieldError at /app/category/Python/ Cannot resolve keyword 'category' into field. Choices are: created_at, id, name, post happens.I wrote context['categories'],so I really cannot understand why this error happens.What is wrong in my codes?How should I fix this?