Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get_object_or_404(), handler404, Http404 response. How do these things works?
Could you help me with something in Django, please? I would like to understand the sequence of execution of 404 page not found error Let me put the code here... url.py -----------file from django project from django.contrib import admin from django.urls import path, include from django.conf.urls import handler404, handler500 from core import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), ] handler404 = views.error404 handler500 = views.error500 url.py -----------file from django app from django.urls import path from .views import index from .views import contact from .views import product urlpatterns = [ path('', index, name='index'), path('contact', contato, name='contact'), path('product/<int:pk>', produto, name='product'), ] view.py def produto(request, pk): print(f'PK: {pk}') prod = get_object_or_404(Product, id=pk) context = { 'product': prod } return render(request, 'product.html', context) def error404(request, exception): template = loader.get_template('404.html') return HttpResponse(content=template.render(), content_type='text/html; charset=utf8', status=404) def error500(request): template = loader.get_template('500.html') return HttpResponse(content=template.render(), content_type='text/html; charset=utf8', status=500) I would like to understand the following: Let's suppose that in the table 'Product' there are only 5 instances...so for the 5th instance, the URL is http://127.0.0.1:8000/product/5 ok? Let's suppose that I try to get the 10th instance in the table that does not exist, so the line of code prod = get_object_or_404(Product, id=pk) will return the instance … -
How to attach user to request object
I'm using JWT for authentication in a django rest framework. It works like this: Creating a JWT token token = jwt.encode(payload, os.environ.get('SECRET'), algorithm='HS256') Sending the JWT token as a cookie with the httponly flag response.set_cookie(key='jwt', value=token, httponly=True) To verfiy that user is logged in any view I look for the cookie and decode it. The problem is that it wont use permission classes for the request object. I would like to know how I can do that. -
Django, Not SupportedError: Mari aDB 10.4 or later is required
I have a simple django project what i used some libraries like PyMySql, pillow and... But problem is on my host, when i enter this command: python manage.py makemigrations Unfortunately, i've got this error: Not SupportedError: Mari aDB 10.4 or later is required(found 10 .3.38). Please help me to resolve and understand this problem. Thanks for your attention. -
Django. Error writing database from csv via custom commands
I want to write my own command to quickly get data from csv. The script successfully fills the table User, Category, Genre. But when it comes to the Title model, I get the error ValueError: Cannot assign '1': 'Title.category' must be an instance of 'Category'. How to make beautiful without using additional modules? models = { User: 'users.csv', Category: 'category.csv', Genre: 'genre.csv', Title: 'titles.csv', } class Command(BaseCommand): help = 'Command to automatically populate the database' def handle(self, *args, **options): path = str(BASE_DIR / 'static/data/') for model, csv_file in models.items(): with open(path + '/' + csv_file, 'r', encoding='utf-8') as file: rows = csv.DictReader(file) records = [model(**row) for row in rows] model.objects.bulk_create(records) self.stdout.write(self.style.SUCCESS(f'Done {model.__name__})')) Example CSV files: users.csv id,username,email,role,bio,first_name,last_name 100,bingobongo,bingobongo@mail.fake,user category.csv id,name,slug 1,Movie,movie genre.csv id,name,slug 1,Drama,drama titles.csv id,name,year,category 1,The Shawshank Redemption,1994,1 -
Django SearchRank not taking full text search operators into account
I'm trying to add a new endpoint that does full text search with AND, OR, NOT operators and also tolerates typos with TriagramSimilarity. I came across this question: Combine trigram with ranked searching in django 1.10 and was trying to use that approach but SearchRank is not behaving as I'd expect, and I'm confused about how it works. When my code looks like the basic implementation of full text search the negative filter is working fine @action(detail=False, methods=["get"]) def search(self, request, *args, **kwargs): search_query = request.query_params.get("search") vector = SearchVector("name", weight="A") query = SearchQuery(search_query, search_type="websearch") qs = Project.objects.annotate( search=vector, ).filter( search=query, ) return Response({ "results": qs.values() }) But I need to implement this using SearchRank so I can later do some logic with the rank score and the similarity score. This is what my code looks like annotating for rank instead of using the tsvector annotation: @action(detail=False, methods=["get"]) def search(self, request, *args, **kwargs): search_query = request.query_params.get("search") vector = SearchVector("name", weight="A") query = SearchQuery(search_query, search_type="websearch") rank = SearchRank(vector, query, cover_density=True) qs = Project.objects.annotate( rank=rank, ).order_by("-rank") return Response({ "results": qs.values() }) And the response looks like: The rank given to the document named "APT29 Attack Graph" is 1. I'd expect the - operator … -
How to link an automatically updating model object with Django Template Language
I'm making a blog, on the index page I have a list that links every single blog post with some details about it <ul> {% for post in object_list %} <li><a href="{% url 'article_detail' pk=post.pk %}">{{ post.title }}</a> - {{ post.author.first_name }} {{ post.author.last_name }}<br/> {{ post.summary }}</li> {{ post.adventure_date }}<br/> {% endfor %} </ul> </div> Now what I want is on the home page to have a featured article section that will automatically update with the two most recently posted articles without having to manually change the code every time the posts are added. I'm struggling to come up with a solution to this, I'm thinking that I would create another variable in my model that was like featured = BooleanField(default=True) But I'm not sure how the true or false would be automatically updated without me going into django admin and manually checking the boxes each time it needed updated -
How to run tasks in django?
I have a Dynamic programming algorithm that takes 2 arrays as an input and returns an array as an output (The arrays are fetched from my django model). I usually just write the algorithm in the view Example: #Model class input(models.Model): arr1 = ArrayField(models.CharField( null=False, max_length=200), blank=False) arr2 = ArrayField(models.CharField( null=False, max_length=200), blank=False) #View @api_view(['GET','POST']) def process(request): arr1 = ... # fetch arr1 arr2 = ... # fetch arr2 def my_algorithm(arr1 , arr2 ): ... ... return arr3 arr3 = process(arr1,arr2) ... ... return Response("Success") There is a tool called celery that does asynchronous task queue/job but it doesn't support windows anymore. What's the alternative or how can i execute the algorithm as a task and call it in the view? -
Get the top 3 elements of a Django nested query
Using django with a MySQL DB and given these models: class Post(models.Model): title = models.CharField(max_length=255, db_index=True) . . . author = models.ForeignKey('Account', on_delete=models.SET_NULL, null=True ) tags = models.ManyToManyField('Tag', blank=True) reactions = models.ManyToManyField('Reaction', through="PostReaction", related_name='reactions', blank=True) class Account(AbstractUser): slug = models.SlugField(max_length=150, db_index=True, blank=True, null=True) avatar = models.URLField(default='', blank=True) class PostReaction(models.Model): reaction = models.ForeignKey('Reaction', on_delete=models.CASCADE, ) post = models.ForeignKey('Post', on_delete=models.CASCADE,) reacted_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey('Account', on_delete=models.CASCADE, ) class Reaction(models.Model): reaction_name = models.CharField(max_length=250, unique=True) reaction_url = models.CharField(max_length=2048) reaction_category = models.ForeignKey('ReactionCategory', on_delete=models.CASCADE) View for a list of published posts : class PostListView(generics.ListAPIView): queryset= Post.objects.filter(is_publish = True).select_related('author').prefetch_related('tags','reactions') serializer_class = PostListReadSerializer Serialisers to produce a JSON list of posts: class TagListSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class PostShortReactionSerializer(serializers.ModelSerializer): class Meta: model = Reaction fields = ["reaction_name", "reaction_url", "id"] class PostAccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ["username", "avatar"] class PostListReadSerializer(serializers.ModelSerializer): tags = TagListSerializer(many=True, read_only=True) reactions = PostShortReactionSerializer(many=True, read_only=True) author = PostAccountSerializer(read_only=True) class Meta: model = Post fields='__all__' Tried to form a subquery to retrieve the required data, but the query is not executed in the output: Option one: sq= Subquery(PostReaction.objects.filter(post=OuterRef('id')).values_list('id', flat=True)[:3]) subquery = PostReaction.objects.filter(post=68).values('reaction__id').annotate(reaction_count=Count('reaction__id')).order_by('-reaction_count')[:3] queryset = Post.objects.filter(is_publish = True).select_related('author').prefetch_related('tags', Prefetch('reactions', queryset=PostReaction.objects.filter(post=sq))) In the second option, grouping fails (naturally) and outputs rows … -
Default error display in HTML is not working for formset factory in Django
I am new to Django and I'm trying to create Recipe web app. I am trying to make formset factory which create forms for ingredients. User can dynamically add ingredient by clicking button. I would like to ask you how displaying errors in HTML template works. For ingredient name field in Ingredient form if length of string is less than 3 it display automatic error message. Display error if length of string is less than 3 Unfortunately when field is empty the error is displaying in another way: Display error if string is empty Could someone tell me why this default display is working when length is less than 3 but is not working when string is empty? There is my code: Ingredient Form: class IngredientForm(forms.Form): ingredient_name = forms.CharField(max_length=64, required=True, min_length=3, label="Nazwa składniku") amount = forms.FloatField(initial=0, label="Ilość", required=True) unit = forms.ChoiceField(choices=unit_choices, required=True, label="Jednostka") class IngredientFormSet(BaseFormSet): def clean(self): """Checks that every ingredient is non-empty""" if any(self.errors): return for form in self.forms: data = form.cleaned_data if not data: raise ValidationError("Form doesn't have any data") Recipe View: class RecipeAddView(View): ingredient_formset = formset_factory(IngredientForm, formset=IngredientFormSet) recipe_form = RecipeForm() template_name = "add_recipe.html" def get(self, request): context = {"ingredient_formset": self.ingredient_formset(), "recipe_formset": self.recipe_form} return render(request, "add_recipe.html", context) def … -
Offline deployment of python scypy and django
I've got a django/pandas/scipy application. I need to deploy them on a Windows Server 2012 machine without Internet access. So, I can't make a pip install in that machine. Furthermore, to install numpy, scipy and more, some of the libraries need to compile some libraries like openblas and more, so deployment is a nightmare. You need too many things to do for this deployment. Docker is not an option. I've got a VM right now, but I want to get rid of it. Is there any posibility to encapsulate a python - scipy to make a deployment on a machine without making it a real nightmare? -
Problem with connecting Django and Mongoengine
I have a problem with connecting django and mongoengine. I do all things as tutorial describes but it is not working. The problem is in part of commenting DATABASE part in settings.py. How could I resolve it? dependencies: djangorestframework==3.14.0 django-rest-framework-mongoengine==3.4.1 django-cors-headers==3.14.0 pymongo[snappy,gssapi,srv,tls]==4.3.3 mongoengine==0.27.0 dnspython settings.py import mongoengine mongoengine.connect(db="mongo", host="mongodb://localhost:27017") # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': 'db_name', # 'USER': 'my-name', # 'PASSWORD': 'my-pass', # 'HOST': '127.0.0.1', # 'PORT': '5432', # } # } error: (venv) PS C:\Users\barma\PycharmProjects\spr_django> python manage.py migrate Traceback (most recent call last): File "C:\Users\barma\PycharmProjects\spr_django\manage.py", line 22, in <module> main() File "C:\Users\barma\PycharmProjects\spr_django\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\commands\migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) (venv) PS C:\Users\barma\PycharmProjects\spr_django> python manage.py migrate Traceback (most recent call last): File "C:\Users\barma\PycharmProjects\spr_django\manage.py", line 22, in <module> main() File "C:\Users\barma\PycharmProjects\spr_django\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\base.py", line … -
Add textearea in forms (Django)
Sorry for bad english, im from Argentina. class Formulario_Contacto(forms.Form): asunto=forms.CharField(label="Nombre", required=True) email=forms.EmailField(label="Email", required=True) mensaje=forms.CharField(label="Contenido", required=True, widget=forms.Textarea) enter image description here Here is my views.py def contacto(request): #Si el metodo de request es POST, pasa esto, eso quiere decir el codigo de abajo if request.method=="POST": miFormulario=Formulario_Contacto(request.POST) if miFormulario.is_valid(): #Si el formulario es valido, hay que crear una variable donde almacenar la info que se ingreso, en este caso la llame formularioFinal formularioFinal=miFormulario.cleaned_data send_mail(formularioFinal["asunto"], formularioFinal["mensaje"], formularioFinal.get("email",""),["julian_regueira@hotmail.com"],) return render (request, "Contacto/gracias.html") else: miFormulario=Formulario_Contacto() return render(request, "Contacto/Form_Contacto.html", {"form":miFormulario}) I want to expand the text area in "mensaje" -
Django: manage.py makemigrations causes this: django.db.utils.OperationalError: no such table
I'm new on Django and I'm learning how to use DBs (SQLite). When I try to create a table gestione_libro inside an app called gestione from a class in models.py with the command python manage.py makemigrations gestione I get this error Traceback (most recent call last): File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: gestione_libro The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/filippobologna/Desktop/Università/TERZO_ANNO/2_semestre/Tecnologie Web/prova/manage.py", line 22, in <module> main() File "/Users/filippobologna/Desktop/Università/TERZO_ANNO/2_semestre/Tecnologie Web/prova/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/management/base.py", line 443, in execute self.check() File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/urls/resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/utils/functional.py", … -
How to check if username is already exist in database in django and show the error "username is already taken "in template html page
I'm new in Django and web develoment. So, I have a costum user model looks like this in my models.py class MyAccount(AbstractBaseUser): first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) username = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=254, blank=True) club_favorite = models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) object = MyAccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'middle_name', 'last_name', 'club_favorite', 'email'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class MyAccountManager(BaseUserManager): def create_user(self, username, first_name, middle_name, last_name, club_favorite, email, password=None): if not username: raise ValueError("Users must have a username") user = self.model( username = self.normalize_email(username), first_name = first_name, middle_name = middle_name, last_name = last_name, club_favorite = club_favorite, email = email, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, first_name, middle_name, last_name, club_favorite, email, password=None): user = self.create_user( username, password = password, first_name = first_name, middle_name = middle_name, last_name = last_name, club_favorite = club_favorite, email = email, ) user.is_admin = True user.save(using=self._db) return user from views.py def register(request): if request.method == 'POST': if(request.method == "POST"): first_name = request.POST.get('first_name') middle_name = request.POST.get('middle_name') last_name = request.POST.get('last_name') username = request.POST.get('username') password1 = request.POST.get('password1') password2 = request.POST.get('password2') email = request.POST.get('email') club_favorite … -
password reset in Django
can you please help. So I did a password reset on the site but could not find on the Internet how to change this data to my own. Thanks in advance type here ---enter image description here Please help solve this problem. -
Django Reverse Not Found, upgrade from 2.0 to 3.2
Template: {% url 'activate' uidb64=uid token=token %} Views: def email_activate(user, generated_token): message = render_to_string('e_activate.html', { 'user': user, 'domain': settings.DOMAIN, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': generated_token, 'base_domain': settings.DOMAIN, }) #etc... def activate(request, uidb64, token): uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) #etc... Urls: re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate') Previously I was using Django 2.0 and this method worked fine. Now I have upgraded to 3.2 and its causing errors. The first error I got is related to urlsafe_base64_encode(force_bytes(user.pk)).decode() which I have changed to urlsafe_base64_encode(force_bytes(user.pk)) as its already returning string (Django 3.2) instead of bytes (Django 2.0) The current ongoing issue: Error during template rendering In template /path/etc Reverse for 'activate' with keyword arguments '{'uid64': 'etc', 'token': 'etc'}' not found. 1 pattern(s) tried: ['computerapp\\/activate/(?P<uid64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] Any thoughts as to why this is happening since upgrading to 3.2? I did have a look at Django 3.2 Docs.. -
Static files not found error deploy django nginx gunicorn ubuntu 18.04
I'm a python Django developer and I'm facing a problem in my deploy. THE SERVER IS WORKING NORMALLY, BUT IT DOES NOT FIND AND DOES NOT RECOGNIZE THE STATIC FILES. I'm using an ubuntu 18.04 server. I made all the necessary configurations: I created the file gunicorn.socket and the gunicorn.service and they are already working normally. The next step was to create the server{}. At the moment, I haven't applied https and security, I just want to access the server by the same ip, in an http way. My file is like this: server { listen 80; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/myproject; } location /media { alias /root/myproject/media/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The user is: root The root path of my project is this: /root/myproject -> It doesn't have the /home folder like it usually does. I already checked it STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'templates/static' ] STATIC_ROOT = BASE_DIR / 'static' Regarding the settings in settings.py, I already put the STATIC_ROOT and I already made the python manage.py collectstatic Another detail: I put the {% static load %} and … -
django-rest-framework web interface is showing datetime in this format DD-MM-YY --:-- --
When I send a post request from drf web interface I am getting this error - "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm:ss.uuuuuu[+HHMM|-HHMM]." I have tried all the resources on the internet, but none of them worked for me. So, I am posting here, and if anyone can help, it will be appreciated. Thank you in advance **- This is what I am doing - ** [models.py] from django.db import models from UserAuthenticator.models import User # Create your models here. class UserInsuranceModel(models.Model): customer_name = models.ForeignKey(User, on_delete=models.CASCADE, null=True) insurance_id = models.CharField(max_length=100, unique=True) vehicle_number = models.CharField(max_length=100, unique=True) rc_front = models.ImageField(upload_to="media", null=False, blank=False) rc_back = models.ImageField(upload_to="media", null=True, blank=True) nominee_name = models.CharField(max_length=100) nominee_dob = models.DateField(null=True, blank=True) insurance_created_at = models.DateTimeField(auto_created=True) insurance_started_at = models.DateTimeField(null=True) insurance_valid_till = models.DateTimeField(null=True) is_insurance_verified = models.BooleanField(default=False) is_insurance_cancelled = models.BooleanField(default=False) def __str__(self): return str(self.customer_name)` [serializer.py] from rest_framework import serializers from .models import UserInsuranceModel from UserAuthenticator.models import User class UserInsuranceSerializer(serializers.ModelSerializer): insurance_started_at = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S.%fZ") insurance_valid_till = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S.%fZ") class Meta: model = UserInsuranceModel fields = ('customer_name', 'insurance_id', 'vehicle_number', 'rc_front', 'rc_back', 'nominee_name', 'nominee_dob', 'insurance_created_at', 'insurance_started_at', 'insurance_valid_till' 'is_insurance_verified', 'is_insurance_cancelled')` [views.py] from rest_framework import generics, status from .models import UserInsuranceModel from .serializer import UserInsuranceSerializer from rest_framework.views import Response class UserInsuranceApiView(generics.CreateAPIView): queryset = UserInsuranceModel.objects.all() serializer_class = … -
django-how to upload main folder and subfolder,subdirectory,subfiles using forms.py and store data main foldername in models.py
I do select folder but select all subfiles only and include subfolder files are select. Example: I select one folder but folder inside 16 files is there, that files are stored in one bye one in database and storage area this is my probelm. Try: views.py def upload_folder(request): if request.method == 'POST': form = FormFiles(request.POST, request.FILES) if form.is_valid(): files = request.FILES.getlist('file') for file in files: myfile = FolderModel(file=file) myfile.save() return HttpResponse("success") else: form = FormFiles() return render(request, 'folderupload.html', {'form': form}) forms.py class FormFiles(forms.Form): folder = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True, 'webkitdirectory': True})) class Meta: model = FolderModel fields = ['file'] Expected: I store main folder name on database. Then how to i expect of my Media storage how to upload Tree format same format stored in. -
json_script and concatenate variable name
I need to concatenate the variable name from a template variable and hand it to the json_script template tag. I tried: {% with sensorname|add:"-data" as SensorNameData %} {{ values|json_script:SensorNameData }} output: {{ SensorNameData }} {% endwith %} Which did not work, so I created a filter templatetag: @register.filter def combined(str1, str2): return f"""{str1}{str2}""" and tried: {{ values|json_script:sensorname|combined:"-data" }} but when applying it, I end up with the parsed list of values and then -data. Can I somehow tell the template processor to validate sensorname first and then values|json_script:xxx? -
Django project - JS not loading after moving it out of HTML to own file in static folder
Here is my folder organization When i had the JS directly in the HTML file, everything worked as expected. Since I moved it to a spots.js file, it doesn't load or appear in the network tab, but i can reach it by going to file location in the server. I am in Debug mode. In my settings.py I have: STATIC_URL = '/users/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'var', 'static') In my urls.py, I have: urlpatterns = [ path('', home, name='users-home'), path('register/', RegisterView.as_view(), name='users-register'), path('profile/', profile, name='users-profile'), path('select-spots/', select_spots, name='select-spots'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In my views.py I have: @login_required def select_spots(request): spots = [] with open('spotscsv.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: spots.append({ 'name': row['name'], 'latitude': float(row['latitude']), 'longitude': float(row['longitude']), }) return render(request, 'users/select_spots.html', {'spots': spots}) And in my select_spots.html, I have: {% extends 'users/base.html' %} {% load static %} <script src="{% static 'myapp/spots.js' %}"></script> I have tried so many different variations but it still doesn't load on page. Do you know why not? I tried changing the spots location, i tried collecting static, I tried different code. -
after change language stay same page in django?
I try this way: <a class="dropdown-item" href="/{{ language.code }}/{{ request.get_full_path|slice:"4:" }}">{{ language.name_local }} and it work but in some page it don't work for example: I have a url like this http://127.0.0.1:8000/products/ but after changing language it will like this: http://127.0.0.1:8000/en/ducts/ but if I enter url like this http://127.0.0.1:8000/fa/products/ then change language it's fine. and url it's correct: http://127.0.0.1:8000/en/products/ I wanna after changing language stay same page -
Python - Creating two models with 1-1 relationship in a same model.py file (hierarchy problem) in Django
Hey I'm facing this problem when I want to create 1:1 relationship IDK if I'm missing something here or what am I doing wrong here in one app.model.py I'm trying to create 2 models like below : class Manager(models.Model): user_id = models.ForeignKey('BeautySalon.Salon',on_delete=models.DO_NOTHING) #FK businessL_id = models.BooleanField(default = False, blank = False) salon_id = models.ForeignKey(Salon,on_delete=models.DO_NOTHING) #FK class Salon(models.Model): # name, manager_id--Manager, city_id--City, address, tell, description, starting hour , closing hour, PTG, rank--Rank name = models.CharField(max_length=200) manager = models.ForeignKey(Manager,on_delete=models.DO_NOTHING) # FK city = models.ForeignKey(City,on_delete=models.DO_NOTHING) #FK address = models.TextField(null = False, max_length = 1000) tell = models.CharField(max_length=24) description = models.TextField(null= False, max_length = 1000) strHour = models.TimeField() clsHour = models.TimeField() PTG = models.BooleanField(default = False, blank = False) rank = models.ForeignKey(Rank,on_delete=models.DO_NOTHING) #FK but when I try to make migrations I get this error Field defines a relation with model 'Salon', which is either not installed, or is abstract. In C++ I would face the same problem but we could call the name at the top to let it know, IDK how to do it in python I've tried this : class Salon (models.Model): pass but it didn't work I appreciate your help -
Using class-based views save a form with 2 related models (via foreign key)
WANT TO DO using CreateView I launch an hmtm page containing a form. This page has had two embedded forms sent in like {{address}} and {{ship}}. The ship model has a foreign key linking it to the address table address_id. I can do this easily using function-based views, but I want to do it via class-based. I create my models, then I do something like this in the view that launches the html page: context = { 'address_form': AddressForm(), 'ship_form': ShipForm(), ) } return render(request, 'app/registration.html', context) The html looks sommething like this: ` {{ address_form }} {{ ship_form }} <input type="submit" value="Register"> ` When I click on submit, the form does connect to the database BUT it tries to save the ship form but it fails because it doesn´t have the address_id and of course, the reason is that the address_form could not be saved first, and this is what is blocking my progress. I know I can do ´some´ manipulation inside the CreateView that launched the html page, like in here def form_valid(self, form): # This method is called when valid form data has been POSTed. but there is no way I can reach the address form, it … -
Django approach for simple app structure?
I'm back to coding after almost 20 years working as a manager. Decided to play with python as I like the language started with some simple desktop apps and now I want use django and do some web development. I'm creating a series of small apps to help me with daily stuff at the company (time management, reading logs, creating slides based on those logs etc. Now question is: Django has a "front end" section and an "Admin" section. If I'm creating that kind of apps what approach should I go for? Develop everything in the Admin area or do that in the front area and save the admin if I need to create some configurations and stuff? I will use authentication for it in case this can be a issue. No access if you dont have an user and password that will be created by me. No self registering Guidance how to add an app to django the best way to suit my needs without loosing the power of the framework