Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to group by json field data in django-mongodb
Hi, Thanks in advance... I am using Django 3.0.5, Python 3.8.0, and MongoDB 5.0 My requirement: Group the data by matching the value of Width, Height, Thickness, and Type fields. While grouping the data, do the summation of Length. I tried this way list(UploadCableTrayData.objects.filter(creator_id__in=selected_users).filter(date_added__range=(selected_start_date, selected_end_date)).values( 'Thickness__value', 'Width__value', 'Height__value', 'Selection').annotate(dcount=Count(['Thickness', 'Width', 'Height']), Length=Sum('Length__value')).order_by("date_updated")) But I am getting errors like this NameError: name 'Thickness__value' is not defined Here is my model class UploadCableTrayData(BaseModel, models.Model): """ Model to store Cable Tray data """ order_upload_id = models.AutoField(primary_key=True) Order_number = jsonfield.JSONField(null=True, blank=True) Type = jsonfield.JSONField(null=True, blank=True) Selection = jsonfield.JSONField(null=True, blank=True) Height = jsonfield.JSONField(null=True, blank=True) Width = jsonfield.JSONField(null=True) Box_width = jsonfield.JSONField(null=True) Box_height = jsonfield.JSONField(null=True) Length = jsonfield.JSONField(null=True) Inner_bend1 = jsonfield.JSONField(null=True, blank=True) Inner_bend2 = jsonfield.JSONField(null=True, blank=True) Thickness = jsonfield.JSONField(null=True, blank=True) Rung_width = jsonfield.JSONField(null=True, blank=True) Rung_height = jsonfield.JSONField(null=True, blank=True) Distance_between_rungs = jsonfield.JSONField(null=True, blank=True) project = models.ForeignKey('project.Project', on_delete=models.DO_NOTHING) def __str__(self): return str(self.order_upload_id) class Meta: db_table = 'UploadCableTrayData' Data stored in the model is like this { "_id": { "$oid": "62384f772d6545101709083b" }, "order_upload_id": 4, "creator_id": 3, "updater_id": 3, "date_added": { "$date": { "$numberLong": "1647857527370" } }, "date_updated": { "$date": { "$numberLong": "1647857527370" } }, "is_deleted": false, "Order_number": { "key": "order", "value": "o1" }, "Type": { "key": "type", "value": "pct" }, … -
Reverse for 'category_list' not found. 'category_list' is not a valid view function or pattern name
i want to do pages for my categories,but when i added get_absolute_url,i got issue that url pattern is doesnt exist.I have done it with functions,and previously didnt work with classes,like ListView.And this is a little bit problem for me views.py model = Category active_tab = 'category_list' template_name = 'products/category_list.html' def get_ordered_grade_info(self): return [] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['grade_info'] = self.get_ordered_grade_info() return context models.py name = models.CharField(_('Name'), max_length=200) slug = models.SlugField(_('Slug'), unique=True) PARAMS = Choices( ('following', 'following'), ('price_to', 'price_to'), ('price_from', 'price_from'), ) def __str__(self): return self.slug def get_absolute_url(self): return reverse('category_list', kwargs={'category_slug': self.pk}) urls.py url(r'^$', views.CategoryListView.as_view(), name='category_list') html {% block content %} <h2>Categories</h2> <div class="list-group"> {% for category in category_list %} <a href="{{ category.get_absolute_url }}" class="list-group-item"> <h4 class="list-group-item-heading">{{ category.name }}</h4> </a> {% endfor %} </div> -
External URL into a iframe to embed an external url within Django
I would like to embed a pptx that is uploaded into a folder in OneDrive within a iframe tag in a Django template. I have the urls stored in a model and saved into the SQLite database. In this sense, in the views.py file, I have the following code: context = { 'selectedunit': selectedunit, 'url_to_be_inserted': MyModel.objects.filter(unit=selectedunit) } return render(request, 'web.html', context) The code for web.html is very easy: {% extends 'base.html' %} {% load static %} {% block content %} <div class="container col-lg-8"> <div class="center"> <iframe class="center" src={{ url_to_be_inserted.url }} width="100%" height="300%" frameborder="0"/> </div> </div> {% endblock %} The result is the snapshot below: While, I would like to embed the ppt into the web site. If I directly insert the URL, instead of using the context variable, it works. That is to say: <iframe class="center" src="https://..." width="100%" height="300%" frameborder="0"/> In this case, the result is as follows (ppt embedded into the Web site): The reason why doing in this sense is because, depending on the selectedunit variable, I would like to address a different pptx with a different URL and I would like to dynamically change the pointer (as you see above by filtering the model). How could I … -
Is there a better way to dynamically change the content of a div in django othen than AJAX?
I have an HTML page with a select in a form, when I select a value and hit submit I want to load dynamically something different in the div following the select. I read that AJAX gives you this opportunity. But is there another way? Maybe something more native? -
Django-filters query params conflict
I am trying to work with filtering db by query params from the link that looks like this: {{url}}/api/books?author="XXX"&from=2003&to=2051&acquired=true I already handled author and acquired params but am stuck with from and to. My filter.py looks like this: class BookFilter(django_filters.FilterSet): author = django_filters.CharFilter(field_name="authors__fullname", lookup_expr="icontains") from = django_filters.NumberFilter(field_name="published_year", lookup_expr="gte") to = django_filters.NumberFilter(field_name="published_year", lookup_expr="lte") acquired = django_filters.BooleanFilter(field_name="acquired") class Meta: model = Book fields = [ "author", "from", "to", "acquired" ] I am looking for a way to assign these query params without overwriting key words (from and to) which is obviously a terrible idea. -
django nginx DisallowedHost
i'm using aws ubuntu instance and nginx i tried to reach my app and i get this error : DisallowedHost at / Invalid HTTP_HOST header: '34.227.190.72'. You may need to add '34.227.190.72' to ALLOWED_HOSTS. Request Method: GET Request URL: http://34.227.190.72/ Django Version: 4.0.4 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: '34.227.190.72'. You may need to add '34.227.190.72' to ALLOWED_HOSTS. Exception Location: /home/ubuntu/env/lib/python3.8/site-packages/django/http/request.py, line 149, in get_host Python Executable: /home/ubuntu/env/bin/python3 Python Version: 3.8.10 Python Path: ['/home/ubuntu/authentication', '/home/ubuntu/env/bin', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/ubuntu/env/lib/python3.8/site-packages'] Server time: Tue, 31 May 2022 10:46:53 +0000 i tried to add my public adress to ALLOWED_HOSTS in setting.py file but it doesn't work my setting.py file : SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['34.227.190.72', 'localhost', '127.0.0.1'] -
Reading from excel in python when cells have multiple operations
I am currently doing a project where all computations are done in excel i have multiple references and if conditions, the output of all of this is a number. The input is computed in python, it carries the information to the excel which has all the formulas to compute the output. I am trying to use the openpyxl library to get this value into my python programm, the written input works well but the last computed number that needs to be extracted as the result or output of the excel is not being done correctly. The output gives the operation not the result of the operation. I have tries using the data_only=True but does not work and the xlwings library solution dies not work either. I just need a command that once I introduce the input, executes all excel operations so that I can extract the result onto my python programm. ¿how can i do this? -
Django overriding get_context_data() not rendering in template
I'm relatively new to Django and I'm learning to work with CBV's and I am currently working on a simple todo list, I want to get specific user data for specific users. The way I am doing this is by overriding the get_context_data() method in my ListView class, but the data is not showing in my template. I have created multiple users and created multiple tasks, but still does not work even though I can access them through the admin page. Here is my code: views.py: class TaskList(LoginRequiredMixin, ListView): model = Task template_name = 'app/home.html' context_object_name = 'tasks' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) context['count'] = context['tasks'].filter( complete=False).count() return context urls.py: from django.urls import path from .views import ( TaskList, TaskDetail, TaskCreate, TaskUpdate, TaskDelete, UserLogin, UserLogout ) urlpatterns = [ path('login/', UserLogin.as_view(), name='login'), path('logout/', UserLogout.as_view(), name='logout'), path('', TaskList.as_view(), name='home'), path('task-detail/<int:pk>/', TaskDetail.as_view(), name='task-detail'), path('task-create/', TaskCreate.as_view(), name='task-create'), path('task-update/<int:pk>/', TaskUpdate.as_view(), name='task-update'), path('task-delete/<int:pk>/', TaskDelete.as_view(), name='task-delete') ] home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>To Do List</title> </head> <body> {% if request.user.is_authenticated %} <p>{{ request.user }}</p> <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} <hr> <a href="{% url 'task-create' %}">Add Task</a> <table> <tr> … -
Django no such table after migrations after cloning from git
My first ques here and am new so sorry if I made any mistake. environment using: ubuntu 18, python 2.7, django version 1.8.2 I am migrating the work environment from one PC to another by cloning git repo. But on new PC am getting error django.db.utils.OperationalError: no such table: tableName for all commend like python manage.py runserver/makemigrations/migrate/flush etc I spend whole day looking for solution. Some link with same problem on stackoverflow django.db.utils.OperationalError: no such table: price_category AFTER GIT CLONE Make migrations error in django: "no such table" and many more. The common solution given in all these answer: delete all migration file except init.py (ques: should i also keep init.pyc?) delete database run makemigrations/migrate I had done 1st. For 2nd google says to delete .sqlite3 file. But there is no such file. In settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'IITMSAT_Telecommands_database', } } Structure of Folders (I deleted things marked with red lines) Error: File "manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 198, in import_models self.models_module = … -
getting TypeError: 'NoneType' on assigning django json field value to a variable
here's the code def energy_capacity_before_losses_for_tranche_gt_one_for_year(self, year, tranche, tranche_year_value): print('tranche', tranche) tranche_stack_quantity = self.tranches_stack_quantity[1] ----> Error here if tranche_year_value in ["-", ""] or tranche_stack_quantity in ["-", ""]: return D(0.0) if int(tranche_year_value) <= year: if tranche_stack_quantity and self.contracted_stack_capacity_tranche: result = ( D(DEGRADATION_WITH_PG_MATRIX_TRANCHE_GREATER_THAN_ONE / 100) * int(tranche_stack_quantity) * D(self.contracted_stack_capacity_tranche / 1000) ) return result return D(0.0) def energy_capacity_before_losses_for_tranche_gt_one(self, tranche, tranche_year_value): return { year: self.energy_capacity_before_losses_for_tranche_gt_one_for_year(year, tranche, tranche_year_value) for year in self.years } def energy_capacity_before_losses_for_tranches(self): result = { 1: self.energy_capacity_before_losses_for_tranche_one() } for tranche, tranche_value in enumerate(self.augmentation_before_start_of_year[1:], start=2): result[tranche] = self.energy_capacity_before_losses_for_tranche_gt_one( tranche=tranche, tranche_year_value=tranche_value ) return result i'm getting error in this line line 63, in energy_capacity_before_losses_for_tranche_gt_one_for_year tranche_stack_quantity = self.tranches_stack_quantity[1] TypeError: 'NoneType' object is not subscriptable and , values of self.tranches_stack_quantity are ["", "2", "", "", "", "", "", "", "", "", ""] i'm trying to assign tranche_stack_quantity = self.tranches_stack_quantity[1] for me it seems fine but i do not know why it's happening Note: the rest of the values are coming from constants or formula calculations and energy_capacity_before_losses_for_tranches() is parent functions and rest are sequentially dependent functions -
using formsets with images does not show the error when the image has not loaded
I have a function with a formset that needs a product that I take from the id that I pass in the function and of the formset creates 3 boxes to insert the images which I then save, the problem is that if these images are not compiled, the redirect is done anyway while in reality the error should come out. Where is the problem? view def product_gallery_create_view(request, id): ProductGalleryFormset = modelformset_factory(ProductGallery, fields = ('image',), extra = 3) product = Product.objects.get(id = id) if request.method == "POST": formset = ProductGalleryFormset(request.POST, request.FILES) if formset.is_valid(): for form in formset: instance = form.save(commit = False) instance.product = product instance.save() return redirect('home') else: formset = ProductGalleryFormset() context = {'formset':formset} return render(request, 'crud/product_gallery_create.html', context) model class ProductGallery(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE, related_name = 'product_gallery') image = models.ImageField(upload_to ='galleria/', null = False, blank = False) html <div class="container mt-3"> <h4>galleria prodotto</h4> <hr> {% if formset.errors %} <div class="alert alert-danger"> {{ formset.errors }} </div> {% endif %} <form method="post" enctype='multipart/form-data' class="notifica" autocomplete="off" novalidate> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="d-flex align-item-center justify-content-between"> <div><small>img</small> {{ form.image }}</div> </div> <hr class="mt-4 mb-4"> {% endfor %} <input type="submit" value="crea galleria" class="btn … -
Django: how to filter by most selling item
i have a course models and user are allowed to purchase this courses, now i want to filter the courses by the most selling course, i have tried using django agreegate but it seems not to be giving me what i want or maybe i am not doing it the right way. i have models.py that is storing the courses class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) course_title = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(unique=True) i also have this model that stores the courses that are purchased and enrolled in class UserCourse(models.Model): user = models.ForeignKey(User , null = False , on_delete=models.CASCADE) course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) i dont know how to write the view to filter the courses by the most selling from the image below you can see that learn angular updated is the most selling course for the creator destiny. so how do i filter this for each user, thier most selling course? -
Passwordless Registration got "Please, enter valid credentials" (Django GraphQL Auth)
Using email and password, I could register a user with the GraphQL below: mutation { register( email:"test1@gmail.com" password1:"test1test1" password2:"test1test1" ){ success errors token refreshToken } } But, using only email(Passwordless Registration), I couldn't register a user with the GraphQL below: mutation { register( email:"test2@gmail.com" ){ success errors token refreshToken } } Then, I got the error below: { "errors": [ { "message": "Please, enter valid credentials", "locations": [ { "line": 70, "column": 3 } ], "path": [ "register" ] } ], "data": { "register": null } } Actually, I added "ALLOW_PASSWORDLESS_REGISTRATION" with "True" to GRAPHQL_AUTH as shown below: GRAPHQL_AUTH = { 'LOGIN_ALLOWED_FIELDS': ['email'], 'REGISTER_MUTATION_FIELDS': ['email'], 'ALLOW_PASSWORDLESS_REGISTRATION': True, # Here 'USER_NODE_FILTER_FIELDS': { "email": ["exact"], "is_active": ["exact"], "status__archived": ["exact"], "status__verified": ["exact"], "status__secondary_email": ["exact"], } } Are there any ways to solve the error to register a user using only email(Passwordless Registration)? -
Why isn't a django database object created?
I'm trying to create a drink database app in django. I have created a drinkRecipe model with ManyToManyField relation to Ingredients model. I can successfully add Ingredients to database via app UI, but for some reason when creating a drink, I get no errors nor do I add the drink to database, instead of going back to the index page only the URL of current page changes. What am I missing? models.py: class DrinkRecipe(models.Model): drinkName = models.CharField(max_length=100) ingredients = models.ManyToManyField(Ingredients) utensil = models.IntegerField(choices=requiredUtensil, default=0) preparation = models.CharField(max_length=1000) def __str__(self): return self.drinkName forms.py: class DrinkForm(forms.Form): name = forms.CharField(max_length=100, label="Name:") utensil = forms.ChoiceField(choices=requiredUtensil, label="Required utensil:") ingredients = forms.ModelChoiceField(queryset=Ingredients.objects.all(), widget=forms.CheckboxSelectMultiple()) preparation = forms.CharField(widget=forms.Textarea) views.py: class AddDrinkView(View): def get(self, request): form_drinks = DrinkForm() drinks_list = DrinkRecipe.objects.all() context = { 'form_drinks': form_drinks, 'drinks_list': drinks_list, } return render(request, 'shakerApp/add_drink.html', context) def post(self, request): form_drinks = DrinkForm(request.POST) if form_drinks.is_valid(): DrinkRecipe.objects.create( name=form_drinks.cleaned_data('name'), utensil=form_drinks.cleaned_data('utensil'), ingredients=form_drinks.cleaned_data('ingredients'), preparation=form_drinks.cleaned_data('preparation') ) else: messages.error(request, "Drink form is invalid.") return HttpResponseRedirect(reverse('shakerApp:index')) -
How to pass an object's id to a js function outside of a for ? DJANGO
I have a delete button that deletes an object from the database. This button has a js windows.confirm function for deletion. I need to pass servico.id to function so I can reference the object in the view. How do I do this? <a href="#" class="btn btn-danger btn-sm" onclick="return myFunction()">Delete</a> Script <script> function myFunction() { if (window.confirm("Você tem certeza que deseja excluir ?")) { window.location.href="{% url 'servico:excluir-servico' servico.id %}"; } } </script> -
in Django User Registration
I'm developing my backend on Django. I wrote a code for user registration under RegistrationView class, and it worked fine before. I had to incorporate email confirmation in it, which also worked fine on its own. However, after all of that was done, I added some conditions to ensure proper working, but I get the "Forbidden: /api/v1.0/user/register-patient/" error. My models.py file: from django.db import models from django.contrib.auth.models import User class VerificatonToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') verification_token = models.CharField( max_length=256, blank=True, null=True) My serializers.py file: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings from .models import VerificatonToken class TokenSerializer(serializers.ModelSerializer): class Meta: model = VerificatonToken fields = ('user', 'verification_token',) class PatientSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField(read_only=True) email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) first_name = serializers.CharField( required=True, max_length=32 ) last_name = serializers.CharField( required=True, max_length=32 ) # DOB = serializers.DateField( # required=True # ) # gender = serializers.CharField( # required=True # ) # address = serializers.CharField( # required=True, # max_length=60 # ) # contactNo = serializers.IntegerField( # required=True, # max_length=11 # ) password = serializers.CharField( required=True, min_length=8, write_only=True ) def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) … -
CRUD API in Django for User Model inherited with AbstractBaseUser and also has Manager Class
view.py class User(APIView): def get(self, request): queryset = User.object.all() serializer = UserDetails(queryset, many=True) return Response(serializer.data) serializer.py class UserDetails(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'hardware_id', 'created_by'] user Model [separately created model] from django.db import models from django.contrib.auth.models import AbstractBaseUser from wijungleapp.Manager import UserManager class User(AbstractBaseUser): username = models.CharField(max_length=100, verbose_name="username", unique=True) password = models.CharField(max_length=100) hardware_id = models.CharField(max_length=150, null=True) created_by = models.DateField(verbose_name="created_by", auto_now_add=True) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['password', 'hardware_id'] is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_role_vendor = models.BooleanField(default=False) is_role_customer = models.BooleanField(default=True) def __str__(self): return self.username def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin object = UserManager() managers.py from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, username, password=None, password2=None, hardware_id=None): if not username: raise ValueError("UserName is Required !!!") user = self.model( username=username, ) user.set_password(password) user.save(using=self._db) return user # Create Super User Here def create_superuser(self, username, password, hardware_id): user = self.create_user( username=username, password=password, hardware_id=hardware_id, ) user.is_admin = True user.save(using=self._db) … -
django error: "asc() got an unexpected keyword argument 'nulls_last' "
class CustomOrderFilter(OrderingFilter): allowed_custom_filters = ['target_item__type_service', 'target_item__level', 'target_item__room__name', 'client__user_full_name', 'designer__user_full_name', 'status', 'date_due_decorist', 'target_item__date_answered'] def get_ordering(self, request, queryset, view): params = request.query_params.get(self.ordering_param) if params: fields = [param.strip() for param in params.split(',')] ordering = [f for f in fields if f.lstrip('-') in self.allowed_custom_filters] if ordering: return ordering return self.get_default_ordering(view) def filter_queryset(self, request, queryset, view): order_fields = [] ordering = self.get_ordering(request, queryset, view) if not ordering: return queryset order_fields.append(ordering[0]) if 'status' in order_fields or '-status' in order_fields: ids = [0, 1, 2, 18, 3, 6, 9, 7, 21, 5, 8, 11, 12, 10, 14, 15, 16, 20, 4, 13, 17] rev_ids = [11, 8, 5, 21, 7, 9, 6, 3, 18, 2, 1, 0, 12, 10, 14, 15, 16, 20, 4, 13, 17] if '-status' in order_fields: order = Case(*[When(status=id, then=pos) for pos, id in enumerate(rev_ids)]) else: order = Case(*[When(status=id, then=pos) for pos, id in enumerate(ids)]) return queryset.order_by(order) if '-date_due_decorist' in order_fields: return queryset.order_by(F('date_due_decorist').desc(nulls_last=True)) elif 'date_due_decorist' in order_fields: return queryset.order_by(F('date_due_decorist').asc(nulls_last=True)) return queryset.order_by(ordering[0]) In custom ordering django, I am getting error as "asc() got an unexpected keyword argument 'nulls_last' ". I want to show null values always at last in date_due_decorist column while sorting. Please let me know if django version 1.10 supports 'nulls_last' or … -
Could I use memcached as a channel layer in Django?
I would like to use Django Channels in my application and I need a channel layer but I don't want to use Redis because, it is not available in my hosting plan. I have to get a dedicated or VPS server and I'm not ready for this yet. Instead, Memcached is available. I have searched the documentation of channels and Django and the internet I found nothing about it. But I know that before Redis, Memcached was used to implement the same. Basically I would like to configure my settings.py like that CHANNEL_LAYERS = { "default": { "BACKEND": "channels_mencached.core.MemcachedChannelLayer", "CONFIG": { "host": "amqp://guest:guest@127.0.0.1:5672/", }, }, } This is really a pseudocode, in reality I have no idea about how to configure Django for Memcached. I know Memcached is not officially supported but, is there a way to hack it and make it work on Django? If not, is there any alternative to be used in production, aside from Redis and RabbigMQ? -
Allow more then one serializer_class in one ModelViewSet class Django REST
How do I define more than one serializer_class in one ModelViewSet? I have four functions in one ModelViewSet, and any positions have their serializer. And I want to place four serializer in one serializer_class? -
Page not found error while trying to reset password in Django3
Here i am using Python 3.7 and Django 3.0 Where when user clicks the forgot password an email is sent to the user with a link to reset the password when the user is clicking this link i am getting page not found error Here is my views.py ..... ...... associated_users= ClientUser.objects.filter(email= data) if associated_users.exists(): for user in associated_users: c = { 'email': user.email, 'domain': request.META['HTTP_HOST'], 'site_name': 'your site', 'uid': urlsafe_b64encode(force_bytes(user.pk)), 'user': user.name, 'token': default_token_generator.make_token(user), 'protocol': 'http', } self.request.session['e_data'] = { 'email': user.email, } subject_template_name='core/reset_subject.txt' # copied from django/contrib/admin/templates/registration/password_reset_subject.txt to templates directory email_template_name='core/reset_email.html' # copied from django/contrib/admin/templates/registration/password_reset_email.html to templates directory subject = loader.render_to_string(subject_template_name, c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) email = loader.render_to_string(email_template_name, c) send_mail(subject, email, settings.DEFAULT_FROM_EMAIL , [user.email], fail_silently=False) result = self.form_valid(form) messages.success(request, 'An email has been sent to ' + data +". Please check its inbox to continue reseting password.") return result result = self.form_invalid(form) messages.error(request, 'No user is associated with this email address') return result here is my reset_email.html {% load i18n %}{% autoescape off %} {% trans "There has been a request to reset your password for Degree. To reset your password use this link:" %} {% block reset_link %} "{%if secure … -
Django redirect doesn't reach the root url
Looks like redirect(<url>) is adding <url> to the current view url, ignoring urls.py, with respect to the Code below redirecting to "<mydomain>.com/savePersonalEdits/account/" while what I wanted is: "<mydomain>.com/account/" Code: At the end of some Django view function I have: return redirect('account/') urls: path('account/', views.accountSettings), path('savePersonalEdits/', views.saveEdits, name="savePersonalEdits") #name needed for HTML form action url -
How to delete an object with a windows.confirm?
I have a template that lists all the activities of a client. In this template, I have a button to delete any activity I choose. This button has a confirmation to delete through a windows.confirm. But it's not working the way you expect. Sometimes the button works, sometimes it doesn't. {% for servico in object_list %} {{ servico.refferring_funcionario }} {{ servico.get_lista_servico_display }} {{ servico.data_servico }} R$ {{ servico.valor_servico }} <a href="{% url 'servico:editar-servico' servico.id %}" class="btn btn-secondary btn-sm">Edit</a> <a href="" class="btn btn-danger btn-sm" onclick="return myFunction()">Delete</a> {% endfor %} Js <script> function myFunction() { if (window.confirm("Você tem certeza que deseja excluir ?")) { window.location.href="{% url 'servico:excluir-servico' servico.id %}"; } } -
configure urls in django, cmd prints: AttributeError: module 'myapp.views' has no attribute 'index'
i have been trying to run this code but it doesn't show the Hey, Welcome inthe views.py myproject/myapp/views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<h1>Hey, Welcome</h1>") myproject/myapp/urls.py urlpatterns=[ path(" ",views.index, name="index") ] myproject/urls.py urlpatterns = [ path('admin/', admin.site.urls),<br> path(' ', include('myapp.urls') ), ] pls can you help me figure out what im doing wrong, when i run the code, it only shows 'the install worked successfully! congratulation!!' without run the html code that i pass inthe views.py -
share file between admin user and staffusers in django
I have a user_type named a staff_user and Admin here the admin in supposed to share the file with staff_user.On the file_list page of admin we are supposed to have an option called share_with_staff_user when clicked it will display the list of staff_users when selected and shared the file should be displayed on the page of staff_user file page. how can i acheive this. models.py class StaffUserDocument(BaseModel): staffuser = models.ForeignKey(StaffUser, related_name='documents', on_delete=models.CASCADE) uploaded_by = models.ForeignKey('User', related_name='+', null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255) file = models.FileField(upload_to='protected/') class AdminDocument(BaseModel): uploaded_by = models.ForeignKey('User',related_name='+',null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) file = models.FileField() views.py class AdminDocumentListView(LoginRequiredMixin, TemplateView): template_name = 'admin_documents_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['urlParams'] = self.request.GET context['instanceData'] = {} return context @login_required def staff_user_profile_documents_view(request): staffuser = request.user.person.staffuser data = {'staffuser': staffuser, 'documents': staffuser.documents.all()} return render(request, template, data)