Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Implementing themes in Django (Custom templates by users)
I want to implement the feature for users to have custom templates. Like they can place themes or templates in a particular folder relative to the home folder. Each theme may have a folder and some config or preview for example(optional). 1) First I need to figure out how to set custom templates dir for an app. 2) Then I can probably do listdir and get all the folders and then give the admin an option to select the dir. 3) A setting list to specify additonal template folders by users. 1 is the problem. The main question I want answer for is how to set custom template dir which can be modified anytime. -
how to save one column value based on id column in django
I would like to save model id along with other format characters into another column, based on the model id being automatically created. For example, For example, I have column name formated_id in shipment model, and want set its value to "easter" + ID which is automatically generated. How could I achieve that? Thanks. class Shipment(models.Model): formated_id = models.CharField("formatedid",max_length= 50) class Meta: ordering = ['-id'] def save(self, *args, **kwargs): super().save(*args, **kwargs) -
Django force only one filefield use TemporaryFileUploadHandler
I have a filefield and in this filefield I want to upload a zip file and work with it from the view, but without saving it in MEDIA_ROOT, I just want to upload it and extract the xml extract info from the xml to send my model and db, the ones from the xml I have solved it, but my question is how can I use only TemporaryFileUploadHandler in this field, from the views and do all the work, the problem is that when it weighs less than 2.5mb it goes up to memory nothing more and the zipfile asks me for a path that's why I want to use the TemporaryFileUploadHandler, how can I do it? small abstract of my view: @login_required def crear_reporte(request): if request.method == 'POST': form = CreateReportForm(request.POST, request.FILES) if form.is_valid(): report = form.save(commit=False) user = request.user report.owner = UserProfile.objects.get(user_id=user.id) current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M") report.title = 'Reporte de ' + current_time + '.' report.save() filez = request.FILES['upload'] filereport = filez.name path = filez.temporary_file_path filereportcom = path + filereport with zipfile.ZipFile(filereportcom, 'r') as z: for f in z.namelist(): xmlss = len(z.namelist()) print (xmlss) print (filez.content_type) print (filez.size) return HttpResponseRedirect('/escritorio')