Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use variables from backend in .scss files
I have a site built with Django, Python and Wagtail. What I want is that I'm able to add some styles in the backend and then use it in my frontent's .scss files. For example I want to be able to set a primary color to #fff via backend and then use it in my .scss file as: $g-color-primary: primary_color_from_backend; $g-font-size-default: primary_font_size_from_backend; I do not have any idea how I can do that and if it's possible at all? Thanks for the help. -
Object has no attribute 'items` while writing api test case?
Here I am trying to write TestCase for my PackageCreateView and I did the following.But it is not working. File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\test\client.py", line 535, in post response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\test\client.py", line 346, in post post_data = self._encode_data(data, content_type) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\test\client.py", line 305, in _encode_data return encode_multipart(BOUNDARY, data) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\test\client.py", line 194, in encode_multipart for (key, value) in data.items(): AttributeError: 'Package' object has no attribute 'items' models class Country(models.Model): name = models.CharField(max_length=255, unique=True) class Package(models.Model): name = models.CharField(max_length=255) package_description = models.TextField() package_start_date = models.DateTimeField() country = models.ManyToManyField(Country) tests.py from rest_framework.test import APITestCase class CreateProductTest(APITestCase): def setUp(self): self.country = Country.objects.create(name='name') self.package = Package.objects.create(name='package',package_description='description',package_start_date='2019-11-12 11:11') self.package.country.add(1) self.package.save() self.client = Client() def test_create(self): url = reverse('package:create_package') response = self.client.post(url, data=self.package,format='json') print(response.status_code) self.assertEqual(response.status_code, status.HTTP_201_CREATED) views.py class CreatePackage(generics.CreateAPIView): serializer_class = PackageSerializer queryset = Package.objects.all() -
Django Aggregation Get Count of Users per Project View
I have a model for tracking users viewing a project, it has foreign key references to user and project. An example looks like project user 1 1 1 2 1 3 2 1 2 2 What I want to achieve is a view count per projects so project 1 will be 3 and project 2 will be 2 in the example above. I am trying below, but it counts every user instance, how do I get every user instance per project? projects = ProjectViews.objects.all().annotate(view_count=Count('user')) -
How to show different entries from data tables on as a dropdown box option?
Hi this is my DB table for job title https://www.screencast.com/t/tse1qsnJI And this from employee table https://www.screencast.com/t/uMtmowCg How could I show the job titles on the drop down box and not the job_title_id as options? https://dpaste.de/SpAe -
Get permission to access google sheet on backend server Django from frontend
I want to read the data of google sheet in django server, which may not be shared with me. In front-end (angular 7) I want to give user an option, when he selects the google sheet, from where he can directly approve the permission to allow server to read the sheet data. Is there any possible way to do this? -
how can I write a custom link for activation?
I am trying to make my activation url like activate/096715d5a428c3d84dd142711f025d68963cc45ec29d4ddd8007506e00af13a3/ . my origial url looks like path('activate/<slug:uidb64>/<slug:token>/', views.activate, name='activate') , and I tried to remove <slug:uidb64> it doesnt work any tips to achieve this? -
How t properly use default django password validators in DRF
This is the serializer for registering users.I have two password fields here password1 and password2.For the password validation I would like to use django default AUTH_PASSWORD_VALIDATORS and for this I have tried like this.But the problem here is when I used only def validate_password1 then the def validate() function always returns ValidationError so I write another function for password2 also.Now if the password matches and it is valid, it register the user but when the password is not valid it displays validation errors on both password1 and password2 field and which I doesn't want.How can I solve it ? And also another problem here is with function def validate_username() which is not implementing while registering the user. serializers.py import django.contrib.auth.password_validation as validators class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())]) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) class Meta: model = get_user_model() fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'profile'] def validate_password1(self, password): validators.validate_password(password=password) def validate_password2(self, password): validators.validate_password(password=password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def validate_username(self, value): data = self.get_initial() username = data.get("username") if len(username) < 6 and len(username) > 15: raise ValidationError('Username must be between 6 and … -
How to populate Django form dynamically with a dictionary of lists and dictionaries?
I've been stuck on this for over a day now and was hoping I could get some help. I've read a bunch of different SO posts and Django docs on forms, formsets, bound and unbound forms, but still cant figure this out. I'm pulling in some data from a model which is a JSONField. It's a nested mess of dictionary (dict) like so: dict= { <br> &nbsp;'A' : 'data1', <br> &nbsp;'B' : [ { <br> &nbsp;&nbsp;&nbsp; 'one': [ <br> &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;{'x': 'data2', 'y': 'data3', 'z': 'data4'},<br> &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;{'x': 'data5', 'y': 'data6', 'z': 'data7'},<br> &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;{'x': 'data8', 'y': 'data9', 'z': 'data10'} <br> &nbsp;&nbsp; &nbsp;], <br> &nbsp;&nbsp;&nbsp;'two': 'val',<br> &nbsp;&nbsp;&nbsp;'three': { <br> &nbsp;&nbsp;&nbsp; &nbsp; 'color':'red',<br> &nbsp;&nbsp; &nbsp; &nbsp;'size':'big',<br> &nbsp;&nbsp; &nbsp; &nbsp;'order':'new'<br> &nbsp;&nbsp; &nbsp;}<br> &nbsp;&nbsp; &nbsp;'four':'someVal',<br> &nbsp;&nbsp;}]<br> &nbsp;'C' : 'moreData'<br> } The inner list, one, will have a dynamic amount of dictionaries in it, in this example there are just 3. The key's for one will always be the same (x, y, and z), but the values will change. I need to create an editable form, that has each key in it's own charfield with the initial data set as the value. I've looked into and tried some packages (django-entangled, django-json-widget, … -
Django model field dynamic in column
I am working on a Django model which could load an excel file as all the fields in that model, but the number of columns is dynamical(such as Years), which means I can not define each field by myself. Is there any library that could build the fields by providing the information inside the excel file, such as the name and length of the file? -
Failed to load resource: the server responded with a status of 403 (Forbidden) when i set DEBUG=FALSE and use nginx
I am new on develop django. I have to deploy it to manual server and my website cant load img in summernote django editor and img in ImageField(). I check on my server, it's uploaded. But it's not displayed. I tried set up my nginx.conf like location /media/{ alias /root/website-django/mysite/mysite/media/;} and try chmod for media/ folder in my django folder. on my console tab in url like www.example.com/media/my-img-1.png: It's notice me: "Failed to load resource: the server responded with a status of 403 (Forbidden)" when i turn DEBUG=TRUE -> All img will display. But i dont want to set DEBUG=TRUE because it's very risk. Please anyone help me. Thank you so much -
Django Queryset filter by relevance
So I'm looking to extract entries from a Queryset that contain a set of search words in a list. I need to then append the extracted entries to another list and sort them by word relevance, that is, the extracted entries that contain more of the search words are found earlier in the list. For example, something along the lines of: search_words=['this', 'is', 'a', 'test'] filtered_results=Test.objects.filter(content__names__icontains=search_words) where filtered_results would contain results starting with all four words, then a combination of 3/4 words, then a combination of 2/4 words, and so on. Is there a way to do this? -
Django Displays Password Field in User Edit Form
I am currently constructing a basic login functionality. While doing so, I encountered a hiccup. The method I am using displays the password field in the template. I believe I understand why it does that, but am unsure how to prevent it from appearing. I have the following view @method_decorator(login_required, name='dispatch') class UserUpdateView(UpdateView): form_class = CustomUserChangeForm #model = User #fields = ('first_name', 'last_name', 'email', 'profile_picture') template_name = 'user_accounts/profile.html' success_url = reverse_lazy('user_accounts:user_profile') def get_object(self): return self.request.user The pertinent Django form is class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('first_name', 'last_name', 'email', 'profile_picture') The profile.html is {% extends 'base.html' %} {% block title %}My account{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item active">My account</li> {% endblock %} {% block content %} <div class="row"> <div class="col-lg-7 col-md-8 col-sm-10"> <form method="post" novalidate> {% csrf_token %} {% include 'includes/form.html' %} <button type="submit" class="btn btn-success">Save changes</button> </form> </div> </div> {% endblock %} Lastly, the form.html is {% load widget_tweaks form_tags %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} <p{% if forloop.last %} class="mb-0"{% endif %}>{{ error }}</p> {% endfor %} </div> {% endif %} … -
Cannot route traffic with Minikube + ingress + Django
In my local development setup, I'm using Django as the webserver (a-la python manage.py runserver 8000) and I'm able to kubectl port-forward <django_pod> 8000 my traffic to my local dev machine so I can interact with my site by browsing to http://localhost:8000/whatever. I've configured my ALLOWED_HOSTS to include localhost to enable this. However, I'd like to avoid using port-forward and go the more proper route of running my traffic through the Kubernetes ingress controller and service. On the same Minikube cluster, I have ingress configured to point certain traffic urls to a very rudimentary nginx pod to confirm that my ingress+service+pod networking is working properly. All other urls should route to my Django app. In my ingress controller logs, I can see the traffic being sent to the service: 192.168.64.1 - [192.168.64.1] - - [22/Nov/2019:03:50:52 +0000] "GET /test HTTP/2.0" 502 565 "-" "browser" 24 0.002 [default-django-service-8000] [] 172.17.0.5:8000, 172.17.0.5:8000, 172.17.0.5:8000 0, 0, 0 0.000, 0.000, 0.000 502, 502, 502 aa2682896e4d7a2052617f7d12b1a02b When I look at the Django logs, I don't see any traffic hitting it. My ingress servicePort is 8000, the django-service port is 8000 (I've just let it default to ClusterIP), the pod's spec.containers.ports.containerPort is 8000, and the process has … -
upstream timed out (110: Connection timed out) while reading response header from upstream while running django application
I'm running django application using uwsgi and nginx using cronjob with command* * * * * /usr/local/bin/lockrun --lockfile /path/to/lock_file -- uwsgi --close-on-exec -s /path/to/socket_file --chdir /path/to/project/folder/ --pp .. -w project_name.wsgi -C666 -p 32 -H /path/to/virtualenv/ 1>> /path/to/success_log 2>> /path/to/error_logBut in nginx error log the above error is showing,how to fix this error can anybody help, due to this error the server is too slow and unable to work in screen??? -
Django auto-populating form field from API call
I am trying to auto-populate one field of a Django form based on the query response of an entry into another field. I would like to do so before the form is submitted, displaying the autopopulated value in the field and maintain the user's ability to edit. (Example, I type 'a handful of bananas' into the name field, when that field blurs it queries the api and fills the carbs field with the # of carbs a handful of bananas has) Right now I have the ajax function to query: $('#recipe-query').on('blur', function(event){ event.preventDefault(); console.log("blur") query_macros(); }); function query_macros(){ var dataStr = "APIKEYREDACTED" var ingredParam = encodeURI($('#recipe-query').val()) dataStr = dataStr + ingredParam if($('#recipe-query').val() && $('#should-query').val()){ $.ajax({ url: "https://api.edamam.com/api/nutrition-data", data: dataStr, type: "GET", dataType: "json", success : function(json){ console.log(json); console.log(json.totalNutrients.CHOCDF.quantity) $('#carbs-query').value = json.totalNutrients.CHOCDF.quantity; }, error : function(xhr, errmsg, err){ console.log(xhr.status + ": " + xhr.responseText); } }); } } this is the form class NutritionForm(forms.ModelForm): class Meta: model = Nutrition fields = ('food_name', 'autofill_macros', 'grams_of_fat', 'grams_of_protein', 'grams_of_carbs', 'date') widgets = { 'food_name': forms.TextInput(attrs={ 'id': 'recipe-query' }), 'autofill_macros': forms.CheckboxInput(attrs={ 'id': 'should-query' }), 'grams_of_fat': forms.TextInput(attrs={ 'id': 'fat-query' }), 'grams_of_protein': forms.TextInput(attrs={ 'id': 'protein-query' }), 'grams_of_carbs': forms.TextInput(attrs={ 'id': 'carbs-query' }) } and model class Nutrition(models.Model): food_name … -
Passenger Python web application could not be started ImportError
Running a python application on a shared server encountering the following error: Web application could not be started An error occurred while starting the web application. It exited before signalling successful startup back to Phusion Passenger. Please read this article for more information about this problem. Raw process output: Traceback (most recent call last): File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 26, in import sys, os, re, imp, threading, signal, traceback, socket, select, struct, logging, errno File "/usr/lib/python2.7/logging/init.py", line 26, in import sys, os, time, cStringIO, traceback, warnings, weakref, collections File "/usr/lib/python2.7/weakref.py", line 14, in from _weakref import ( ImportError: cannot import name _remove_dead_weakref Error ID 04438b96 Application root /home/groups/group1/2018/production Environment (value of RAILS_ENV, RACK_ENV, WSGI_ENV, NODE_ENV and PASSENGER_APP_ENV) development Server runs perfectly using runserver (python manage.py runserver) but seems to break when attempting to start with Passenger. Any help or pointers in the right direction would be extremely appreciated. -
Extend a model using OneToOneField
I'm trying to extend django-taggit Tag model to have an added_by (ForeignKey to User) field on it, so I can query all tags added by a particular user. So, I have created an app and in models.py there I have created another model, called MyTag and I have a OneToOneField to Tag on it: from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from taggit.models import Tag class MyTag(models.Model): tag = models.OneToOneField(Tag, on_delete=models.CASCADE) added_by = models.ForeignKey(User, on_delete=models.CASCADE) @receiver(post_save, sender=Tag) def create_tag(sender, instance, created, **kwargs): if created: MyTag.objects.create(tag=instance, added_by=???) @receiver(post_save, sender=Tag) def save_tag(sender, instance, **kwargs): instance.mytag.save() The issue is, I can't access request.user from inside models.py. How do I overcome the issue, i.e. how do I properly extend django-taggit's Tag model to have added_by field on it? -
Hosting Django Rest framework on its own server
So I have an angular front end with an Django rest framework backend that's hosted on a single ubuntu 18.04 VPS box running apache. The front end is hosted on port 80 and the backend is at port 8000 and we noticed it seems like a lot of networks block port 8000. So what happens is if I logon on a public wifi you can see the front end but you can't access the backend. I need some guidance on how to make this work. Right now it's setup like so Api requests are: http://myapp.com:8000 In the future all API quests should be: http://myapp.com/api or maybe even a separate server that's http://api.myapp.com I'm asking for some guidance on this issue. Is there anyway to just make apache think that all requests are on port 80/443 and i don't need the 8000 anymore? and for a small app is that an okay practice? OR should I just run the backend on a separate server and if so how do I set that up? all guides seem to point to putting that on 8000. Any links and guidance on this issue would be appreciated. -
Django Categories and Breadcrumbs Issues
I am working on the categorization application in this link. Everything works normally on the admin side. However, I could not show the categories and breadcrumbs on front site. I'd appreciate it if you could help me. https://djangopy.org/package-of-week/categories-with-django-mptt/ -
How to do backward relationships lookup for all model objects in Django?
I want to have a list view of all products from Product model with their own image URLs from ProductImage model. Each product may have multiple images. models.py: class Product(models.Model): product_id = models.CharField(max_length=6) material = models.ForeignKey(Material, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(verbose_name='Active') def __str__(self): return self.name clsas ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) url = models.URLField(max_length=250) created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(verbose_name='Active') def __str__(self): return self.url I've been trying to implement the queries from this Django documentation. But the example specifically target an object by its id. How to do the same thing with all objects? b = Blog.objects.get(id=1) b.entry_set.all() # Returns all Entry objects related to Blog. Is it possible to do it without changing the Foreign Key relation into productimage = models.ManyToManyField(ProductImage) in Product model ? My current attempt on views.py: def product_list_view(request): products = Product.objects.all() images = products.productimage_set.all() context = { 'product_list': products, 'product_image_list': images } return render(request, 'product_visualizers/product_list.html', context) product_list.html template: {% for product in product_list %} <li> <p> {{ product.product_id }}: </p> {{ product.name }} - {{ product.material }} - {{ product.created_at }} - {{ product.enabled }} <p> {{ product_image_list.url }} </p> </li> {% endfor %} The error I got: AttributeError … -
Multi-tenant redirect to sub-domain based on User Id
I am implementing Django-tenant-schemas on a SaaS website I am building and am wondering how to allow users to login at the main site and be redirected to the tenant specific subdomain their user account exists at. e.g. User goes to www.mysite.com and tries to log in - because, after all, this is the site they expect to log in at - but their user account is actually associated with www.tenant1.mysite.com. How do I go about redirecting the user automatically when they attempt to log in at the main domain? I assume there is something very simple that I am not seeing. Thanks in advance! Note: I want the user to log in to their sub-domain and only their sub-domain, not as a user across all domains (which is what SESSION_COOKIE_DOMAIN does I believe). -
Why does Django tell me that a field clashes with a field in the base class when that field only exists in the subclass?
I am attempting to define some models that inherit from a base class with timestamps, but I'm getting the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/matt/Repositories/mtm/env/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/matt/Repositories/mtm/env/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/matt/Repositories/mtm/env/lib/python3.5/site-packages/django/core/management/base.py", line 436, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: events.Event.location: (models.E006) The field 'location' clashes with the field 'location' from model 'home.timestampedmodel'. System check identified 1 issue (0 silenced). Here are my models: home/models.py from django.db import models class TimestampedModel(models.Model): date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) events/models.py from django.db import models from home.models import TimestampedModel class Location(TimestampedModel): name = models.CharField(max_length=200) address1 = models.CharField(max_length=200) address2 = models.CharField(max_length=200) city = models.CharField(max_length=80, default='Chicago') state = models.CharField(max_length=2, default='IL') class Event(TimestampedModel): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) date_start = models.DateTimeField() date_end = models.DateTimeField(null=True, blank=True) location = models.ForeignKey(Location, on_delete=models.CASCADE) The code runs successfully when I have Location and Event inherit from models.Model, but this isn't how I want my code to be structured. events/models.py (works, but not desirable) from django.db import models class Location(models.Model): name = models.CharField(max_length=200) address1 … -
How to use MySQL JSON type model in Django pymysql?
We are doing web development for simple internal use. (I'm a beginner developer.) I am utilizing Django 2.1, mysql 8.0, python 3.7, pymysql. I want to make a model using JSON type in MySQL. Is there a way? -
Django Users, groups and organizations for multi vendor app, how to?
I'm building a marketplace that allows users to sign up with a company or organization, add or invite other users to that company and manage those users. All users can create listings (products or service). Currently I have an abstract user model and a company model with a foreign key to the user, which works well if a company only has one user, it looks like this: class User(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_number = models.CharField(max_length=15) email = models.EmailField(unique=True) objects = UserManager() def __str__(self): return self.first_name class Company(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=100, unique=True) company_address = models.CharField(max_length=100, unique=True) company_website = models.URLField() company_verified = models.BooleanField(default=False) def __str__(self): return self.company_name What would be the best way to accomplish this, without giving the users permissions to the admin site? I've looked at using django-organizations, but the documentation seems poor and they don't support postgresql. -
Populate added_by field from CreateView
I have extended django-taggit TagBase model to include an added_by field as a ForeignKey to User: class TagBase(models.Model): name = models.CharField(verbose_name=_("Name"), unique=True, max_length=100) slug = models.SlugField(verbose_name=_("Slug"), unique=True, max_length=100) added_by = models.ForeignKey(User, on_delete=models.CASCADE) Everything works great, however I'm having an issue with populating that field from my CreateView. This is what I have tried: class NoteCreateView(LoginRequiredMixin, CreateView): model = Note fields = [ 'title', 'description', 'notebook', 'tags' ] def form_valid(self, form): form.instance.added_by = self.request.user form.instance.save() for tag in form.instance.tags.all(): tag.added_by = self.request.user return super().form_valid(form) but I'm getting an error: IntegrityError at /notes/1/create/ NOT NULL constraint failed: taggit_tag.added_by_id How do I properly autopopulate added_by field on my tag instances?