Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Javascript ReferenceError: function is not defined at HTMLButtonElement.onclick
So I have index.js in static/network/index.js and I would like the functions I define there to run in Django templates. The file is linked by and {% load static%} but unfortunately after adding a button with the onliclick parameter in the console to any place in the template, it appears error "ReferenceError: function is not defined at HTMLButtonElement.onclick" layout.html {% load static %} // This is where static files should be loaded. <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'network/styles.css' %}" rel="stylesheet"> <script src="{% static 'network/index.js' %}"></script> // And this is where the static files should also be loaded. </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Network</a> <div> <ul class="navbar-nav mr-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'profile' user.username %}"><strong>{{ user.username }}</strong></a> </li> {% endif %} <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}" >All Posts</a> </li> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'followers_view' %}">Following</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}">Log Out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Register</a> … -
How do I change FilePathField to FileField in a Django Model dependant on the instance of a related Model?
I am trying to create a directory based on the instance of a created participant. This directory will be used to upload files for that participant. I'm trying to convert a desktop app into a Django web app and I'm new to Django. Any help will be greatly appreciated. Thanks in advance. My code: def processed_path(report_folder_name): s_id = report_folder_name processed_file_path = os.path.join(settings.MEDIAFILES_DIR, 'processed', s_id) processed_file_path = str(processed_file_path) if not os.path.exists(processed_file_path): os.mkdir(processed_file_path) return processed_file_path class Participant(models.Model): id = models.BigAutoField(primary_key=True, unique=True, editable=False) participant_id = models.CharField(default="Participant", max_length=100) location = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True, null=True) # isansys_file_upload = models.FileField(null=True, blank=True, upload=isansysFilePath) def __str__(self): return str(self.participant_id) class ProcessedDataFile(models.Model): participant = models.ForeignKey(Participant, on_delete=models.CASCADE) processed_folder_name = Participant.participant_id processed_file_upload = models.FileField(null=True, blank=True, upload_to='processed/') processed_file_path = models.FilePathField(null=True, blank=True, path=processed_path) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.processed_file_path) -
Can Django see in inner directories 'management/commands' a commands
Whether can Django see a command which is situated like management/commands/other_directory/my_command.py? I just wanna sort them by their actions. -
Django request.body format
When I try to print request.body, the below is printed b'----------------------------914826831994362856243559\r\nContent-Disposition: form-data; name="release_date"\r\n\r\n2003-06-01\r\n----------------------------914826831994362856243559\r\nContent-Disposition: form-data; name="fanmodel"\r\n\r\nfan234code\r\n----------------------------914826831994362856243559\r\nContent-Disposition: form-data; name="country_code"\r\n\r\nAO\r\n----------------------------914826831994362856243559--\r\n' My post request data is available here but along with a lot other data. I want to understand what is that other data and how can I format it ? -
how can I create a category for ungrouped data?
I'm trying to create a category for scraped data that isn't grouped but I get this error. I'm wondering if there is a way I can get around it. Traceback (most recent call last): File "C:\Users\MUHUMUZA IVAN\Desktop\JobPortal\test.py", line 128, in <module> the_category = Category.objects.get(title="Others") File "C:\Users\MUHUMUZA IVAN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\MUHUMUZA IVAN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 397, in get raise self.model.DoesNotExist( jobapp.models.Category.DoesNotExist: Category matching query does not exist. for test_job in final_jobs: if 'Manager' in test_job['title']: the_category = Category.objects.get(title='Manager') elif 'Engineer' in test_job['title']: the_category = Category.objects.get(title= 'Engineer') elif 'Architect' in test_job['title']: the_category = Category.objects.get(title='Architect') else: the_category = Category.objects.get(title="Others") I know it says there is no query matching Others, how can I correct this. -
Django - separated settings by environment. Not finding variable from base settings
I've split my django environment as per this post. In settings/base.py I have BASE_DIR specified: BASE_DIR = Path(__file__).resolve().parent.parent.parent In settings/__init__.py I have: from .base import * env = os.environ['ENV'] ... if env == 'test': from .test import * ... In settings/test.py I have DATA_VOLUME_BASE_DIR = BASE_DIR / 'scanned_images'. I expect that Django loads the settings module, imports settings/base.py, checks the environment ('test'), imports settings/test.py (which works) and the variable is available (which isn't). My stacktrace: sid_test_web | Traceback (most recent call last): sid_test_web | File "/code/manage.py", line 22, in <module> sid_test_web | main() sid_test_web | File "/code/manage.py", line 18, in main sid_test_web | execute_from_command_line(sys.argv) sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_ sid_test_web | utility.execute() sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 363, in execute sid_test_web | settings.INSTALLED_APPS sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__ sid_test_web | self._setup(name) sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 69, in _setup sid_test_web | self._wrapped = Settings(settings_module) sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 170, in __init__ sid_test_web | mod = importlib.import_module(self.SETTINGS_MODULE) sid_test_web | File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module sid_test_web | return _bootstrap._gcd_import(name[level:], package, level) sid_test_web | File "<frozen importlib._bootstrap>", line 1050, in _gcd_import sid_test_web | File "<frozen importlib._bootstrap>", line 1027, in _find_and_load sid_test_web | File "<frozen importlib._bootstrap>", … -
add to cart button is not responding
my add to cart button is not responding. I have applied javascript on my add to cart button, In cart button I have assigned attribute i.e data-product the value that is {{product.id}}. <div class="card-body"> <h5 class="card-title fw-bold text-uppercase">{{product.name}}</h5> <p class="card-text"><h4 style="font-size: 1rem; padding: 0.3rem; opacity: 0.8;">$ {{product.price}} </h4></p> <button data-product={{product.id}} data-action="add" class = "btn btn-outline-secondary add-btn update-cart">ADD TO CART</button> </div> </div> above is my code for products.html and this my code for javascript. var updateBtns = document.getElementsByClassName('update-cart') for(var i = 0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) }) } The console is not showing any thing even though I click on Add to Cart button several times -
When will the "raise_exception=True" pass through the is_valid() function?
My Serializer.py in this MovieSerializer I will check if "name" and "description" is same or not, if same then raise an error. class MovieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=80) description = serializers.CharField(max_length=300) def create(self, validated_data): return Movie.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.save() return instance # object level validation def validate(self, data): if data['name'] == data['description']: raise serializers.ValidationError("Name and Description can not be Same.") else: return data My views.py in serializer.is_valid() not pass raise_exception=True, when 'name' and 'description' is same it return a formated error message. output : class MovieListAV(APIView): def post(self, request): serializer = MovieSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My another serializer validate "password" and "confirm_password" same or not, if different then raise an error. class UserPasswordChangeSerializer(serializers.Serializer): password = serializers.CharField(write_only=True, style={'input_type':'password'}) confirm_password = serializers.CharField(write_only=True, style={'input_type':'password'}) class Meta: fields = ['password', 'confirm_password'] def validate(self, attrs): password = attrs.get('password') password2 = attrs.get('confirm_password') if password != password2: raise serializers.ValidationError({'password':'Password and Confirm Password Should be Same!'}) user = self.context.get('user') user.set_password(password) user.save() return attrs My other view serializer.is_valid() not pass raise_exception=True, when "password" and "confirm_password" is dirrerent it can't return any formated error message. but when I use "raise_exception=True" as a … -
How to add data dynamically to specific column in jQuery DataTable which is already initialised?
In jQuery DataTable, i want to add data to specific columns dynamically after table is initialised, I don't want to reinitialise table again, just want to add row data to specific columns dynamically. -
SuspiciousFileOperation at /file/upload/ Detected path traversal attempt in '/app/media/Resume/Lal.pdf'
I am trying to upload a file to dropbox using django restframework. I am getting the following error : SuspiciousFileOperation at /file/upload/ Detected path traversal attempt in '/app/media/Resume/Lal.pdf' This is first time I am using dropbox with django and I have tried my best to find the issue but I couldn't. TIA. Traceback: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/app/file_app/views.py", line 14, in post file_serializer.save() File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/serializers.py", line 212, in save self.instance = self.create(validated_data) File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/serializers.py", line 962, in create instance = ModelClass._default_manager.create(**validated_data) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 453, in create obj.save(force_insert=True, using=self.db) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 739, in save self.save_base(using=using, force_insert=force_insert, File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 776, in save_base updated = self._save_table( File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 881, in _save_table results = … -
Is VAPID keys are unique to each server for web push notifications?
While implementing push notification (in Django framework), I have used VAPID keys which generated by a website (https://vapidkeys.com/). Can I use any random dummy text for these keys instead of generating using any other platforms ? Or does these VAPID keys being checked with any server during push notification process ? -
Migrations conflicts in Django, CircularDependencyError
I have a fresh new Postgres DB for my Django app. After applying the initial migrations with python3 manage.py migrate I run python3 manage.py makemigrations to create the tables for my models but no change is detected and no migrations created. This is weird but running python3 manage.py makemigrations app_name for each individual app in my project seems to work. When I try to python3 manage.py migrate I got an error: django.db.migrations.exceptions.CircularDependencyError: hub.0001_initial, crm.0001_initial where hub and crm are the names of 2 of the apps in the projects. This happens because some models in my hub app have relationships with some models in the crm app and viceversa. An effective solution would be to comment out all the relationship fields in my models, migrate, un-comment and makemigrations and migrate again to create the relationships tables. I don't want to go through all my models commenting out fields, is anyone aware of a more elegant solution? Thanks in advance. -
Django get_form results in unbound form (or what is the best way to get url parameters into a model form using CBV createview?)
I'm using a model form and a CBV (createview) to build a form. I needed to get url parameters into the form so I could access details from the previous view that sent the user to the form. To achieve this I initially tried overriding get_form as follows: def get_form(self): form = AddDataForm(key_a=self.request.GET['a'], key_b=self.request.GET['b']) return form This didn't work. The form wouldn't save (even when all fields were correctly completed). It would result in an unbound form. I eventually got a positive result by using get_form_kwargs as follows: def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update({'key_a': self.request.GET['a'], 'key_b':self.request.GET['b']}) return kwargs My question is, what about get_form (or my lack of understanding of it) results in this behaviour? My forms.py is below too. class AddDataForm(forms.ModelForm): class Meta: model = MiningTech fields = '__all__' exclude = ('user',) def __init__(self, key_a, key_b, *args, **kwargs): # key_a comes from the view's get_form. super(AddDataForm, self).__init__(*args, **kwargs) if len(key_a) > 3: for field_name in self.fields: if not field_name.startswith(key_a[0:3]): # If field_name doesn't start with first 3 characters of key_a, hide it. self.fields[field_name].widget = forms.HiddenInput() print("__init__ args", kwargs) else: self.fields[field_name].required = True self.fields['slug'].initial = key_b else: print("All fields Hidden") -
How to show/hide field in django admin with js?
I want to hide/show the field depending on the selection, but it doesn't work for me I have models: STATUS_CHOICES = ((1, 'Accepted'),(0, 'Rejected'),) class City(models.Model): id = models.BigAutoField(primary_key=True) status = models.IntegerField(choices=STATUS_CHOICES, default = 0) name = models.CharField(max_length=200) In my admin, i have: @admin.register(City) class CityAdmin(admin.ModelAdmin): list_display = ( 'pk', 'name', 'status', ) form = CityForm class CityForm(forms.ModelForm): class Media: js = ('targets-show.js',) In targets-show.js $(function() { $('input[name="status"]').on('click', function() { if ($(this).val() == '0') { $('#id_name').show(); } else { $('#id_name').hide(); } }); }) -
How to fix "self.model.DoesNotExist"?
I'm trying to filter through some data I've scraped for my project. And I would like to create a "categories" section. I get this error Traceback (most recent call last): File "C:\Users\MUHUMUZA IVAN\Desktop\JobPortal\test.py", line 127, in <module> the_category = Category.objects.get(title='Project') File "C:\Users\MUHUMUZA IVAN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\MUHUMUZA IVAN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 397, in get raise self.model.DoesNotExist( jobapp.models.Category.DoesNotExist: Category matching query does not exist. However, I do have an existing model for Category. class Category(models.Model): title = models.CharField(max_length= 200, null = True, blank = True) description = models.TextField(null = True, blank = True) uniqueId = models.CharField(null = True, blank = True, max_length = 100) categoryImage = models.ImageField(default = 'category.png', upload_to = 'upload_images') slug = models.SlugField(max_length = 500, unique=True, blank = True, null = True) seoDescription = models.CharField(max_length = 500, null = True, blank = True) seoKeywords = models.CharField(max_length = 500, null = True, blank = True) def __str__(self): return '{} - {}'.format(self.title, self.uniqueId) def get_absolute_url(self): return reverse('category-detail', kwargs = {'slug': self.slug}) def save(self, *args, **kwargs): if self.uniqueId is None: self.uniqueId = str(uuid4()).split('-')[0] self.slug = slugify('Category {} {}'.format(self.title, self.uniqueId)) self.slug = slugify('Category {} {}'.format(self.title, self.uniqueId)) self.seoDescription = 'Apply for {} Jobs online, start your career journey today'.format(self.title) self.seoKeywords … -
If category == x select the option in Django Template
In my Django Template I have to template tag. {{categories}} and {{category}}. If category equals one of the items in categories ı want that option select. But my code isn't working. I'm pretty sure category equals one item in categories. Here is my code: <select id="category" name="category"> {% for x in categories %} <option value="{{x}}" {% if category == x %}selected{% endif %}>{{x}}</option> {% endfor %} </select> -
IntegrityError: null value in column "categories_id" of relation "polls_products" violates not-null constraint
I am trying to do CRUD with foreign keys using serializers,the issue is that I am unable to insert the data that I want to display with the below error coming : "django.db.utils.IntegrityError: null value in column "categories_id" of relation "polls_products" violates not-null constraint DETAIL: Failing row contains (42, aw, 12, 4, good, 9, null, 3, 3, 1, t)." I in fact made sure to add every data as shown in the images below despite having insert every data the error is coming below is the models and serializer class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class POLLSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" class pollSerializer(serializers.ModelSerializer): categories = serializers.StringRelatedField() class Meta: model = Products fields = "__all__" def insert(request): data = {} if request.method == "POST": print('POST',id) data['categories'] = request.POST.get('categories') data['sub_categories'] = request.POST.get('sub_categories') data['color'] = request.POST.get('color') data['size'] = request.POST.get('size') data['title'] = request.POST.get('title') data['price'] = request.POST.get('price') data['sku_number'] = request.POST.get('sku_number') data['product_details'] = request.POST.get('product_details') data['quantity'] = request.POST.get('quantity') form = pollSerializer(data=data) print(form) if form.is_valid(): print('form after valid:',form) print("error of form:",form.errors) form.save() … -
DRF Image serializer with nested thumnails
I'm writing django project, in which I have the following models in my media_app application: class Image(File): """ Image model class, through which client will get images stored on AWS S3. """ # ... (not needed in serializer fields) class Thumbnail(File): """ Related model for Image, that contains thumbnails of Image. """ parent = models.ForeignKey( Image, on_delete=models.CASCADE, related_name='thumbnails', ) resolution = models.CharField( _('resolution'), max_length=11, validators=[resolution_validator], ) # ... File class is base model class for media files in my project. It contains mime_type, origina_file_name, size, etc. My question is how can I write serializer for Image, that will have the following structure: { "2775f83e-1608-4135-91d3-f357484df3b1": { "full_size": "http://localhost:8000/api/media/2775f83e-1608-4135-91d3-f357484df3b1/", "358x227": "http://localhost:8000/api/media/8809a43d-c387-4a8e-9c84-8419c406ecd8/", "190x121": "http://localhost:8000/api/media/cb32967e-a576-44ee-b636-6e3a65ec93ba/" } } Where "2775f...df3b1" is pk of Image, "full_size" its own get url (model has method/property api_url, that generate endpoint url to media file get view) and other fields ("358x227" and "190x121") are urls of related thumbnails (keys are from resolution fields in Thumbnail). This structure is not common for DRF, so I've not found the solution in documentation... Serializer will be used in other ModelSerializers. Image contains foreignkeys to other models, those need media files (I'm not using Django Content Type, just nullable OneToOnes), and in api_url there … -
I was just hosting my django project on heroku and it is getting internal server error
2022-07-11T09:25:52.180154+00:00 app[web.1]: from django.urls import path, include,re_path,url 2022-07-11T09:25:52.180154+00:00 app[web.1]: ImportError: cannot import name 'url' from 'django.urls' (/app/.heroku/python/lib/python3.10/site-packages/django/urls/init.py) 2022-07-11T09:25:52.180154+00:00 app[web.1]: 2022-07-11T09:25:52.180154+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2022-07-11T09:25:52.180154+00:00 app[web.1]: 2022-07-11T09:25:52.180155+00:00 app[web.1]: Traceback (most recent call last): 2022-07-11T09:25:52.180155+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner 2022-07-11T09:25:52.180155+00:00 app[web.1]: response = get_response(request) 2022-07-11T09:25:52.180158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/whitenoise/middleware.py", line 60, in call 2022-07-11T09:25:52.180158+00:00 app[web.1]: response = self.get_response(request) 2022-07-11T09:25:52.180158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 57, in inner 2022-07-11T09:25:52.180158+00:00 app[web.1]: response = response_for_exception(request, exc) 2022-07-11T09:25:52.180159+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 139, in response_for_exception 2022-07-11T09:25:52.180159+00:00 app[web.1]: response = handle_uncaught_exception( 2022-07-11T09:25:52.180159+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 183, in handle_uncaught_exception 2022-07-11T09:25:52.180159+00:00 app[web.1]: callback = resolver.resolve_error_handler(500) 2022-07-11T09:25:52.180160+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/resolvers.py", line 710, in resolve_error_handler 2022-07-11T09:25:52.180160+00:00 app[web.1]: callback = getattr(self.urlconf_module, "handler%s" % view_type, None) 2022-07-11T09:25:52.180160+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/functional.py", line 49, in get 2022-07-11T09:25:52.180160+00:00 app[web.1]: res = instance.dict[self.name] = self.func(instance) 2022-07-11T09:25:52.180160+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/resolvers.py", line 689, in urlconf_module 2022-07-11T09:25:52.180160+00:00 app[web.1]: return import_module(self.urlconf_name) 2022-07-11T09:25:52.180161+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/init.py", line 126, in import_module 2022-07-11T09:25:52.180161+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-07-11T09:25:52.180162+00:00 app[web.1]: File "", line 1050, in _gcd_import 2022-07-11T09:25:52.180162+00:00 app[web.1]: File "", line 1027, in _find_and_load 2022-07-11T09:25:52.180162+00:00 app[web.1]: File "", line 1006, in _find_and_load_unlocked 2022-07-11T09:25:52.180162+00:00 app[web.1]: File "", line 688, in _load_unlocked 2022-07-11T09:25:52.180162+00:00 app[web.1]: File "", line … -
Will it be correct if property will change the data?
@property def check_too_much_sent_confirmation(self): if self._count_of_hashes_sent >= 3: if UTC.localize(datetime.now()) <= self.updated_at + timedelta(minutes=10): return True else: self.reset_count_of_hashes_sent() return False def reset_count_of_hashes_sent(self, commit=False): self._count_of_hashes_sent = 0 self._save_if_commit(commit) In the code above, check_too_much_sent_confirmation checks if the user can send the confirmation code again, he is given 3 attempts every 10 minutes. self.reset_count_of_hashes_sent() The line above resets the number of attempts. Is it correct that a method is called from a property function that changes the data in the database? Or is it better to call this function separately? -
model form has no attribute 'cleaned_data'
I want to sign in to be able to use the site. However, I'm having a problem: 'LoginForm' object has no attribute 'cleaned_data'. Please tell me how can I solve it. I apologize in advance for my English My forms.py class LoginForm(forms.Form): user_name = forms.CharField(max_length=20, widget=TextInput(attrs={'type':'text','class': 'form-control','placeholder': 'Input username'})) passWord = forms.CharField(max_length=25, widget=TextInput(attrs={'type':'password','class': 'form-control','placeholder': 'Input password'})) class Meta: fields = ['user_name', 'passWord'] My views.py def login_view(request): template_name = 'main/login.html' action_detail = '' if request.method == "POST": form = LoginForm(request.POST) if form.is_valid: username = form.cleaned_data.get('user_name') password = form.cleaned_data.get('passWord') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: action_detail = 'invalid username or password' else: form = LoginForm() context={ 'title': 'Login', 'form': form, 'action_detail': action_detail, } return render(request, template_name, context) -
Is there a way to deploy Django with other web applications?
I'm starting a new personal server in a VPS (debian). I am doing the mainpage with django. I will like to add to this server/site other external apps (such as GitLab CE, Veloren , FluxRSS and Wallabag). The idea is to centralize everything through django. To have something like : Blog : webpage.com GitLab : gitlab.webpage.com Nevertheless, I cannot seem to find any tutorials or information to do this. I think there is something related to nginx and reverse proxy, but still cant find good information. I know the question is very broad but I'm out of resources and do not know where to search... I've been searching through the web (including stackoverflow) and can't seem to find what I'm looking for, so even if it is just keyword recommendations or links to possible solutions/implementations I'll be extremely happy. -
Foreach Answer calculate score
I have a set of questionnaires, each with questions and each question has an answer, an answer value, and an answer weight. I need to get each answer and multiple the answer value.count by the answer weight value For example question, 1 answer value is -- which is given a value of -2 and the weight is 20 so I need to calculate -2 x 20 and so on for each question to give me a total score of all the questions in the questionnaire. my view so far questionnaires = ProjectQuestionnaire.objects.all() results = [] for q in questionnaires: if ProjectQuestionnaireResponse.objects.filter(project_name_id=project_id, questionnaire_id = q.id).exists(): q_response = ProjectQuestionnaireResponse.objects.get(project_name_id=project_id, questionnaire_id = q.id) q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False).count() if q_answered > 1: q_count = (100 / ProjectQuestionnaireQuestion.objects.filter(questionnaire_id = q.id).count() * q_answered) else: q_count = 0 ###### Trying to calculate here ###### the_score = [] for answer in q_answered: answer_score = ProjectQuestionnaireAnswer.objects.filter() ###### END of Calculation ###### Models: class ProjectQuestionnaire(models.Model): title = models.CharField(max_length=50, blank=False, unique=True) description = models.TextField(blank=True) def __str__(self): return str(self.title) class ProjectQuestionnaireQuestion(models.Model): questionnaire = models.ForeignKey(ProjectQuestionnaire, on_delete=models.CASCADE) sequence = models.IntegerField() question = models.TextField() description = models.TextField(blank=True) def __str__(self): return str(self.question) class ProjectQuestionnaireResponse(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE) questionnaire = models.ForeignKey(ProjectQuestionnaire, on_delete=models.CASCADE) user = … -
redis.exceptions.ConnectionError: Error -3 connecting to redis:6379. Temporary failure in name resolution
redis.service is active and I can connect to redis-cli but in Django I got the issue when Celery try to get access to redis:6379 (as I understand). CELERY_RESULT_BACKEND = os.environ.get('REDISCLOUD_URL', 'redis://localhost:6379/0') CACHEOPS_REDIS = os.environ.get('CACHEOPS_REDIS', 'redis://localhost:6379/9') CACHES = { 'default': { 'BACKEND': 'redis_lock.django_cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'DB': 3, } } } It happened after I reinstalled Ubuntu. Before was ok. Kindly help :) -
Not getting name of the object even with correct function StringRelatedField
I am doing CRUD with foreign keys using serializers and I am getting the data like this not only am I getting the names of "sub_categories" wrong(as I am getting ),but also not getting the names of size and colors that I have added below are the serializers class POLLSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" class pollSerializer(serializers.ModelSerializer): categories = serializers.StringRelatedField() sub_categories = serializers.StringRelatedField() color = serializers.StringRelatedField() size = serializers.StringRelatedField() class Meta: model = Products fields = "__all__" below is the model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE)A # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) insert and show function def show(request): showall = Products.objects.filter(isactive=True) print("show all data:",showall) serializer = pollSerializer(showall,many=True) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): data = {} if request.method == "POST": print('POST',id) data['categories'] = request.POST.get('categories') data['sub_categories'] = request.POST.get('sub_categories') data['color'] = request.POST.get('color') data['size'] = request.POST.get('size') data['title'] = request.POST.get('title') data['price'] = request.POST.get('price') data['sku_number'] = request.POST.get('sku_number') data['product_details'] = request.POST.get('product_details') data['quantity'] = request.POST.get('quantity') form = pollSerializer(data=data) print(form) if form.is_valid(): print('form after valid:',form) print("error of form:",form.errors) form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("polls:show") else: print('form not valid') print(form.errors) …