Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. Show error message on current page
Help me please! I'm trying to show error message: In forms: def clean_form(self): url = self.cleaned_data['text'] if url == 'qwe': raise ValidationError("Error") return self.cleaned_data In view: def main_site(request): if request.method == 'POST': form = Form(request.POST or None) if form.is_valid(): form.clean_form() link = form.cleaned_data['text'] ... But when I send 'qwe' in form: And press 'send'. Take: But I want to see Error on same page. What's I should be do? Thank you! -
Fields with NULL and blank values
I'm writing my first Python web application. My code is difficult because it often needs to treat fields separately if they contain a blank value (object.propery = '') and a Null value (object.property = None). Is there a simple way of dealing with these two values as one? I've noticed some languages have a isNullorEmpty() function. I've also noticed that if a DB field is set to contain numbers then assigning a blank value to the field just makes it Null (convinient :-) -
Subdomain www.example.com and root doman example.com with django-allauth with a single SITE_ID
We are using django-allauth to enable login with Twitter. As far I as am aware the following must match: SITE_ID = 1 so the site used in the social login must have id = 1 Twitter login callback must of the form http://www.example.com/accounts/twitter/login/callback/ The user must be visiting the application via example.com not example.herokuapp.com I am wondering how to handle root domain example.com and www.example.com, what should the domain of the site be? Links SITE_ID (https://docs.djangoproject.com/en/3.0/ref/settings/#site-id) -
Django api filter search on other models without a direct foreign field
I have two models named user, skill, and profile. I am trying to implement a search filter on the user's skills. which means when someone searches for something that is contained in the skills of a user, that user would appear in the search result. Note: when the user signs up, a signal is used to auto-create a profile for that user. The user simply updates their profile to add skills and other things. user model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=250) picture = models.TextField(null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True, blank=True) profile model class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profiles') date_of_birth = models.DateField(blank=True, verbose_name="DOB", null=True) bio = models.TextField(max_length=500, blank=True, null=True) skills = models.ManyToManyField(Skill, related_name='skills') sex = models.CharField(max_length=6, choices=SEX, blank=True, null=True) type_of_body = models.CharField(max_length=8, choices=BODYTYPE, blank=True, null=True) feet = models.PositiveIntegerField(blank=True, null=True) inches = models.PositiveIntegerField(blank=True, null=True) lives_in = models.CharField(max_length=50, blank=True, null=True) updated_on = models.DateTimeField(auto_now=True) skill model class Skill(models.Model): name = models.CharField(max_length=60) subcategory = models.CharField(max_length=60, blank=True, null=True) description = models.TextField(null=True, blank=True) created_on = models.DateTimeField(auto_now=True) updated_on = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.DO_NOTHING) the user view, where the search is done from class ListUsersView(generics.ListAPIView): … -
Updating Notification model in django using signals
I'm working on a books inventory project. I'm trying to send notification to user as soon as a new book is added. I've built this notification model: ... class Notification(models.Model): title =models.CharField(max_length =255) message =models.TextField() viewed =models.BooleanField(default =False) user =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete =models.CASCADE,) def __str__(self): return self.title I'm able to build post_save signal that prints the 'Book is added' in the console. Though I'm facing challenge in saving the value in the notifications table This is the signals.py file: from django.db.models.signals import post_save # from django.dispatch import receiver from books.models import Book from .models import Notification # @receiver(post_save,sender =Book) def book_add_notify(sender,**kwargs): print('Book is added') Notification.objects.create(user =kwargs.get('instance'), title ='Thanks for adding your book!', message='Your book has been successfully Added') post_save.connect(book_add_notify,sender =Book) This is the error message I'm getting: ValueError at /books/new/ Cannot assign "": "Notification.user" must be a "CustomUser" instance. I'm not sure how to handle this CustomUser error. Let me know if any more info is required. -
failed to open python file mysite.wsgi unable to load app 0 (mountpoint='') (callable not found or import error)
I am trying to deploy my django app using nginx and uWSGI. The problem that I am facing is that I cannot run the Django application with uwsgi. The command that I am using is uwsgi --socket //tmp/mysite.sock --module mysite.wsgi --chmod-socket=664 However I get an error saying Python version: 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0x564b119cc430 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 72904 bytes (71 KB) for 1 cores *** Operational MODE: single process *** failed to open python file mysite.wsgi unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 30670, cores: 1) My project structure is below /mysiteAPI /mysite __init.py settings.py urls.py wsgi.py /app1 ... /app2 ... manage.py Any help is appreciated! I have been stuck for hours.. -
DRF serializer: method update_or_create is not working as expected
There is a model in which the parameter unique_together class RfiParticipation(models.Model): vendor = models.ForeignKey('Vendors', models.DO_NOTHING, related_name='to_vendor') m = models.ForeignKey('Modules', models.DO_NOTHING, related_name='to_modules') active = models.BooleanField(default=False) user_id = models.IntegerField(null=True, blank=True) rfi = models.ForeignKey('Rfis', related_name='to_rfi', on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) class Meta: db_table = 'rfi_participation' unique_together = (('vendor', 'm', 'rfi',),) And there is a serializer in which the preservation of an instance in a database is performed by the method update_or_create. class RfiParticipationSerializer(serializers.ModelSerializer): rfi = serializers.PrimaryKeyRelatedField(queryset=Rfis.objects.all(), required=False, allow_null=True) class Meta: model = RfiParticipation fields = ('pk', 'active', 'm', 'rfi', 'vendor', 'timestamp') read_only_fields = ('timestamp', ) def create(self, validated_data): .... .... module, created = RfiParticipation.objects.update_or_create( rfi=validated_data.get('rfi', None), vendor=validated_data.get('vendor', None), m=validated_data.get('m', None), defaults={'active': validated_data.get('active', False)}) return module The problem is that when I try to update an instance, I get an error { "non_field_errors": [ "The fields vendor, m, rfi must make a unique set." ] } But I'm not trying to create a new object with already existing values, but to update it. As I understand it, this error must occur when creating a duplicate and not when updating it. -
Django doesn't reflect changes made through dbshell in admin panel
I have a table with some entries and it is being shown perfectly in the admin panel too. Now, I entered into dbshell (sqlite3) and altered the table to add a column named tempColumn. When I viewed the db.sqlite3 file in online sqlite3 viewer, it showed the updated table with the new column ie. tempColumn. But when I go to admin panel to view the table there, it doesn't show the updated table... I even tried running makemigrations and migrate commands, but it shows no migrations to apply. This might be because, when i run makemigrations cmd, it must be checking if my table in models.py has been changed or not, which would remain unchanged as i altered the table through dbshell terminal. So is there a way to reflect the changes made through dbshell to be visible in admin panel without actually adding the field in table in models.py ? -
Error in posting data through Axios to Django Rest Framework server,Error code 500
I use token authentication to communicate between React and DRF. I can make GET request using below token but can not POST data to server with payload. axios.post('URL', { headers: {'Authorization': 'Token 83d1892877db7950c1c5a818cbb6ca738e53f90b'} }) .then(function (response) { console.log(response) }) .catch(function (error) { console.log(error); }) I get error 500 from Django server when posting above.But with same URL and Token I could successfully execute POST request in Postman. I want to add a data with the axios POST request, the data is {name:'myname'}. Thanks in advance -
how to make translatable relationship in django admin with django parler
I use django-parler to make my django app translatable, and everything works fine but I have a model for my products with relationship one to many: class Product(TranslatableModel): title = models.CharField(max_length=191) price = models.FloatField() translations = TranslatedFields( description=models.TextField(_('description')), any_language=True ) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products',) image = models.ImageField( upload_to=image_files, max_length=254, null=False ) def __unicode__(self): return self.description class Meta: ordering = ['id'] verbose_name = _('product') verbose_name_plural = _('products') where category is also translatable model. In my admin when I want to create a product I get this form: how can I change in that select object to translatable title? here is my admin.py: class ProductAdminForm(TranslatableModelForm): class Meta: model = Product exclude = () def __init__(self, *args, **kwargs): super(ProductAdminForm, self).__init__(*args, **kwargs) print(Category.objects.prefetch_related('translations').all()) self.fields['category'].queryset = Category.objects.prefetch_related('translations').all() class ProductAdmin(TranslatableAdmin): prefetch_language_column = True form = ProductAdminForm list_display = ('title', 'description', 'category', 'price', 'image') fieldsets = ( (None, { 'fields': ('title', 'description', 'price', 'category', 'image'), }), ) -
Django ordering by two fields not working as expected
i am working on a shop for clothes, shoes etc. And i am trying to sort the products by price. The problems comes when the product's discount_price field is populated which means that this product is discounted. So when i want to order the products in my view i am expecting to see products with lower discount_price before products with higher price, but it is not working like this. models.py class Item(models.Model): price = models.IntegerField(null=True, blank=True) discount_price = models.IntegerField(null=True, blank=True) The query i am performing items = Item.objects.all().order_by('price', 'discount_price') -
Several urls of website visible in Google
I build website in Django framework. I don't way why in Google serach, when I type name of the website domain, are visible several urls (like several webpages) which I created, not only main page? Is it any error in creating urls or any other error? -
FroalaField is not supported by modeltranslation
I am using frola editor on my django project. Today I tried to write modeltranslations for my website. it throws error : django.core.exceptions.ImproperlyConfigured: FroalaField is not supported by modeltranslation. on command python manage.py makemigrations Is there solution for this problem? -
How much data can a websocket consumer handle?
I've built a simple application using Django Channels where a Consumer receives data from an external service, the consumer than sends this data to some subscribers on another consumer. I'm new to websockets and i had a little concern: the consumer is receiving a lot of data, in the order of 100 (or more) JSON records per second. At what point should i be worried about this service crashing or running into performance issues? Is there some sort of limit for what i'm doing? -
Django rest framework, access the requested object in an extra action
I have a custom extra action that relies on the object requested by the user. Meaning that, if this the view's URL: 127.0.0.1:8000/myapp/ I want in my extra action to get the object in the get request. meaning, if this is the request: 127.0.0.1:8000/myapp/myobj then, the queryset in my extra action would be something like this: @action(detail=True) def get_location_details(): name = self.request.GET.get("name") data = Mission.objects.get(MissionName=f'{name}') But a code like this raises: object matching query does not exist. and if I print the name variable it's None -
Inherent and filter data from Django model
How to inherent and filter data from the base model in Django for example: my base model goes like this: class Customers(models.Model): Time_Registered = models.DateField(blank=False) Number = models.CharField(max_length=500) Name = models.CharField(max_length=250) Locations = models.ForeignKey(Locations, on_delete=models.CASCADE) what I want to do is create another models contains customer information related to one location such as : Class Canada(Customers): class Meta: proxy = True # filter by Canada' -
Failing to send variable with pure javascript to POST request
I am trying to pass two variable (dragged_id and replaced_id) in POST request via javascript to a view but when I print the request from the view (in django), I get an empty dictionary. What am I doing wrong? the JS: function swapHabits(dragged_id, replaced_id) { var request = new XMLHttpRequest(); var url = "/swap/" request.open("POST", url, true); var cookies = parse_cookies(); request.setRequestHeader('X-CSRFToken', cookies['csrftoken']); request.send(JSON.stringify({'dragged_id': dragged_id, 'replaced_id': replaced_id})); } I am using the library SortableJS to drag and drop rows of a table. The function swapHabits is triggered on drop of the row (onEnd): var originalList; var sortable = Sortable.create(selection, { handle: '.bars-move', animation: 150, onStart: function (evt) { originalList = [...document.querySelectorAll("#selection > tr")].map(el => el.id); }, onEnd: function(evt) { var dragged_id = evt.item.id; var replaced_id = originalList[evt.newIndex]; swapHabits(dragged_id, replaced_id); }, }); -
Django never closes connection to Aurora Serverless
Django never closes connections to Aurora Serverless database, it always shows 4 connections (4 asgi workers) Even if docs say Persistent connections avoid the overhead of re-establishing a connection to the database in each request. They’re controlled by the CONN_MAX_AGE parameter which defines the maximum lifetime of a connection. It can be set independently for each database. The default value is 0, preserving the historical behavior of closing the database connection at the end of each request Any ideas what could be the case there? -
Django ForeignKey value does not have corresponding value
I'm working on the Django section of CS50 around the 30min mark on the video with the modes 'ForeignKey' section. When i run the make migration i get the error. You are trying to add a non-nullable field 'agent' to product without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: 2 if I set the default as a string value i get the error saying it was expecting an id. If i set it as 1 then i get the following. The row in table 'clutter_product' with primary key '1' has an invalid foreign key: clutter_product.agent_id contains a value '1' that does not have a corresponding value in clutter_supplier.id. class Supplier(models.Model): company = models.CharField(max_length=64) contact = models.CharField(max_length=64) email = models.CharField(max_length=128, blank = True) def __str__(self): return f"{self.id} {self.company} {self.contact} {self.email}" class Product(models.Model): name = models.CharField(max_length=64) sku = models.CharField(max_length=64, blank = True) unit_cost = models.IntegerField() rrp = models.IntegerField() average_fee = models.IntegerField() shipping_fee = models.IntegerField() agent = models.ForeignKey(Supplier, default=1, … -
Pythonanywhere - Django - No module named 'api.urls'
I uploaded my django project to pythonanywhere. But, I got some errors. No module named 'api.urls' in project/urls.py project/urls.py from django.contrib import admin from django.conf.urls import include, url from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('user.urls')), url(r'^api/', include('api.urls')), ] urlpatterns = format_suffix_patterns(urlpatterns) Only error at api.urls. But user.urls not. I can not understand why? My project structure: . |---project |---api |----urls.py |---user |----urls.py |---project |----settings.py |----urls.py pythonanywhere_com_wsgi.py # +++++++++++ DJANGO +++++++++++ # To use your own django app use code like this: import os import sys path = '/home/setname/example/project' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' # then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Thanks. -
I want to navigate to the details of a product but it displays <QuerySet [<Product: Tshirt>]> and does not show any information Django ORM Python
When i click on the provided link it must show the products related to the particular shop but i get an error Unsupported lookup 'product_name' for CharField or join on the field not permitted. Please suggest on this product_name is the foreign key for ProductDetails and shop is the foreign key for Products this is the template <strong><a href="{{partone}}">{{tut.product_description}}</a></strong> Views.py # first check to see if the url is in categories. categories = [c.shop_slug for c in Shop.objects.all()] if single_slug in categories: matching_series = Product.objects.filter(shop_name__shop_slug=single_slug) series_urls = {} for m in matching_series.all(): part_one = Product.objects.filter(product_name=m.product_name) series_urls[m] = part_one return render(request=request, template_name='products/shop_products.html', context={"product_name": matching_series, "part_ones": series_urls}) product_details = [t.test_something for t in ProductDetails.objects.all()] if single_slug in product_details: this_product = ProductDetails.objects.get(test_something = single_slug) return render(request, 'products/product_details.html',{"product":this_product}) return HttpResponse(f"{single_slug} does not correspond") from django.db import models # Create your models here. # For shop in the beginning # class ShopType(models.Model): # shop_type = models.CharField(max_length=50) # shop_type_description = models.TextField() # def __str__(self): # return self.shop_type class Shop(models.Model): shop_name = models.CharField(max_length=50) shop_location = models.CharField(max_length=100) shop_opening_time = models.CharField(max_length=10) shop_slug = models.CharField(max_length = 20) # shop_type = models.ForeignKey( # ShopType, default=1, on_delete=models.SET_DEFAULT) shop_image = models.ImageField(upload_to='products', null=True, blank=True) shop_owner = models.CharField(max_length=100) shop_description = models.TextField() shop_added_date = models.DateTimeField(auto_now=True) def … -
Django: Get a confirmation when a model is saved to db
I have a model called Project. On updating this model object, I want to show the corresponding "success" or "failed" message. Somthing like the following: (this doesnt work since save returns an object not boolen). Do you know how to know if an object is actually saved ? views.py if (project.save()): messages.success(request, 'Project was deleted') else: messages.warning(request, 'Your request could not be processed. Please try again.') -
OpenEdx - AuthMissingParameter at /complete/edx-oidc/
I have installed docker devstack version of openedx ironwood.master release. When I click 'View My Records' button in profile page I got an error: AuthMissingParameter at /complete/edx-oidc/ Missing needed parameter state Request Method: GET Request URL: http://localhost:18150/complete/edx-oidc/ Django Version: 1.11.29 Exception Type: AuthMissingParameter Exception Value: Missing needed parameter state Exception Location: /edx/app/credentials/venvs/credentials/lib/python3.5/site-packages/social_core/backends/oauth.py in validate_state, line 88 Python Executable: /edx/app/credentials/venvs/credentials/bin/python Python Version: 3.5.2 Python Path: ['/edx/app/credentials/credentials', '/edx/app/credentials/venvs/credentials/lib/python35.zip', '/edx/app/credentials/venvs/credentials/lib/python3.5', '/edx/app/credentials/venvs/credentials/lib/python3.5/plat-x86_64-linux-gnu', '/edx/app/credentials/venvs/credentials/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/edx/app/credentials/venvs/credentials/lib/python3.5/site-packages', '/edx/app/credentials/credentials'] Server time: Sun, 12 Apr 2020 06:44:47 +0000 Please help me. Thanks. -
Why are class variables used in model classes?
I am learning django and reading other's code, as below: class Review(models.Model): RATING_CHOICES = ((1, '1'),(2, '2'),(3, '3'),(4, '4'), (5, '5'),) wine = models.ForeignKey(Wine, on_delete=models.CASCADE) pub_date = models.DateTimeField('date published') user_name = models.CharField(max_length=100) comment = models.CharField(default="no comment", max_length=200) rating = models.IntegerField(choices=RATING_CHOICES) Why are all these variables not defined in init as instance variables? They don't make sense as class variables. Right? -
Load Three JS model with gltf loader in Django
I am trying to load a Three JS model in a Django(3.0.3) app on a local environment. Template: <script> var address_to_model ="{% static 'models/matilda/scene.gltf' %}"; // Pass this variable to .js file </script> <script src="{% static 'js/matilda.js' %}"></script> matilda.js: var loader = new THREE.GLTFLoader( ); loader.load( address_to_model, function ( gltf ) { scene.add( gltf.scene ); }, undefined, function ( error ) { console.error( error ); } ); renderer.outputEncoding = THREE.sRGBEncoding; The page loads without any Django error and it shows the ThreeJS window which is working but the model is not loaded and in the Chrome error console, I get this error: GET http://127.0.0.1:8000/matilda/models/matilda/scene.gltf 404 (Not Found) I think it should not check this URL because I do not resolve it in urls.py and there is nothing in this address. It should load the model which is collected in the 'static/models/matilada' with collectstatic command. I check these links but they do not help: * Django {% static 'path' %} in javascript file * Correctly accessing django static files from external javascript * Django: External JS using framework doesn't load * https://pypi.org/project/django-js-urls/