Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django listview pagination is too slow on large dataset
I have a django listview that shows filtered data from Catalogue. It works fine on small database, but when database is too large, it takes too long time to return results. views.py: class all_ads(generic.ListView): paginate_by = 12 template_name = 'new_list_view_grid-card.html' def get_queryset(self): city_district = self.request.GET.getlist('city_district') usage = self.request.GET.get('usage') status = self.request.GET.get('status') last2week = datetime.datetime.now() - datetime.timedelta(days=14) status = status.split(',') if usage: usage = usage.split(',') else: usage = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] intersections = list(set(status).intersection(usage)) type_q = (Q(type__in=intersections) & Q(type__isnull=False)) cat_ids = list(models.Catalogue.objects.filter( Q(*[Q(city__contains=x) for x in city_district], _connector=Q.OR) | Q(*[Q(district__contains=x) for x in city_district], _connector=Q.OR) ).values_list('pk', flat=True)) result = models.Catalogue.objects.filter( Q(datetime__gte=last2week), type_q, pk__in=cat_ids ).distinct().order_by('-datetime').prefetch_related('type') return result models.py: class Catalogue(models.Model): city = models.CharField(db_index=True,max_length=100, null=True) district = models.CharField(db_index=True,max_length=100, null=True) type = models.ManyToManyField(Type, db_index=True) class Type(models.Model): name = models.CharField(max_length=100, db_index=True) def __str__(self): return self.name And this is template.html: {% for Catalogue in catalogue_list %} "do something" {% endfor %} -
Django Broken Pipe Message
When creating an instance in Django Admin, I get the 'Broken pipe' message in the terminal. The instance can be seen in Django Admin and everything seems to be okay. Is this something that I can ignore or is there something wrong with my models? models.py from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField( verbose_name=_("Category"), max_length=255, unique=True, ) slug = models.SlugField(verbose_name=_("Category URL"), max_length=255, unique=True) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") class MPTTMeta: order_insertion_by = ["name"] class Meta: verbose_name = _("Category") verbose_name_plural = _("Categories") def get_absolute_url(self): return reverse("store:category_all", args={self.slug}) def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.RESTRICT) title = models.CharField( verbose_name=_("title"), max_length=255, ) description = models.TextField(verbose_name=_("description"), blank=True) slug = models.SlugField(max_length=255) price = models.DecimalField( verbose_name=_("Price"), max_digits=5, decimal_places=2, ) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") def get_absolute_url(self): return reverse("store:prod_details", args=[self.slug]) def __str__(self): return self.title Terminal [03/Jul/2021 12:29:24] "POST /admin/store/category/add/ HTTP/1.1" 302 0 [03/Jul/2021 12:29:24] "GET /admin/store/category/ HTTP/1.1" 200 8094 [03/Jul/2021 12:29:24] "GET /admin/jsi18n/ HTTP/1.1" 200 3195 [03/Jul/2021 12:29:24] - Broken pipe from ('127.0.0.1', 67866) -
Django - The current path, job/all, matched the last one. - But it still returns 404
When I go to this URL http://127.0.0.1:8000/job/all I am always receiving a 404 error with this message: 404 Django Error screenshot However, when I just go to http://127.0.0.1:8000/ or http://127.0.0.1:8000 it always finds the / (index) route correctly regardless if there is a trailing slash, or not. This issue seems to only happen with the /job/WHATEVER_ELSE_GOES_HERE URLs. I have the following URLs setup: My jobs app urls.py: from django.urls import path from .views import * urlpatterns = [ path('', index, name="index"), path('job/<int:job_id>', job_details, name="job_detail"), path('job/all/', all_jobs, name="all_jobs"), path('job/add/', add_job, name="add_job"), path('job/my_posted_jobs/', my_posted_jobs, name="my_posted_jobs"), path('job/delete/<int:job_id>', delete_job, name="delete_job"), path('job/search', search_job, name="search_job"), path('job/apply_for_job/<int:job_id>', apply_for_job, name="apply_for_job") ] My project's urls.py: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('jobs.urls')), path('user/', include('users.urls')), path('payments/', include('payments.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In the error message (screenshot) it also says this: The current path, job/all, matched the last one. How come it matches a URL but returns 404? How do I fix it? Thank you -
@permission_required decorator returns no user attribute in View error
I'm working with Django-admin panel. I have created a custom view file to add a file manager. To make file uploading safe, I just added permission_required decorator. But it throws an error 'FileBrowser' object has no attribute 'user'. Here is my code. class FileBrowser(ListView): model = File paginate_by = 30 template_name = "file_manager/browser.html" extra_context = { 'file_type': type, 'title': "Media Browser", } @permission_required('file_manager.view_file') def dispatch(self, request, *args, **kwargs): file_type = request.GET.get('type') self.queryset = File.objects.filter(type=file_type) self.extra_context['value_to'] = request.GET.get('value_to') self.extra_context['image_to'] = request.GET.get('image_to') self.extra_context['form'] = FileForm() return super().dispatch(request, *args, **kwargs) -
Django href pass multiple parameters to function
I want to pass two parameters from an HTML page throw href to a function first the parameter are: HTML page, {{object.id}} . . {% for item in model_items %} <td>{{item.ID}}</td> <td class="p-1 mb-1 text-dark"> <a href="{% url 'Up_Items' item.id {{object.id}} %}" class="btn btn-info btn-sm">Add Item</a></td> and the second thing is the urls.py; path('Up_Items/<int:id_itm,id_itm2>/', views.ADD_item, name='Up_Items'), and the function in views.py. def ADD_item(request, id_itm, id_itm2): print(id_itm, id_itm2 ) return redirect('Invoices') what I missed here to work correctly plseae? -
what is the meaning of this error-django webframework
[03/Jul/2021 12:37:09] "GET /Calculatorapp HTTP/1.1" 200 2941 [03/Jul/2021 12:37:09] "GET /static/logo.jpg HTTP/1.1" 404 1783 -
Why do I get 'illegal multibyte sequence' error when installing zappa?
so I'm trying to use AWS lambda for my Django project, and learned that I needed zappa. I was following the official guide, tried pip install zappa, then ran into an error message saying "'cp949' codec can't decode byte 0xe2 in position 2339: illegal multibyte sequence". Full error message is this: File "<string>", line 1, in <module> File "C:\Users\user\AppData\Local\Temp\pip-install-4iwakfy4\kappa_5a4d7eb77b754bf2888ab086b2876cb0\setup.py", line 54, in <module> run_setup() File "C:\Users\user\AppData\Local\Temp\pip-install-4iwakfy4\kappa_5a4d7eb77b754bf2888ab086b2876cb0\setup.py", line 22, in run_setup long_description=open_file('README.rst').read(), UnicodeDecodeError: 'cp949' codec can't decode byte 0xe2 in position 2339: illegal multibyte sequence``` <br><br> Any idea on why this occurs? Thank you very much in advance. -
Sendind email after receiving data from POST in Django
I want that the user fills a form (made using Django Model Forms) then receive the data from POST and send a copy though gmail using django send_mail function. Here is my settings.py configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'anyone@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = '' Here is my views.py def GetOrder(request): mymodalform = MyOrderForm(request.POST) if mymodalform.is_valid(): # Save in DB mymodalform.save() # Send a copy via gmail to anyone@gmail.com email_subject = 'Order Credentials/Information from ' + mymodalform.name # email_body = "Congratulations if you receive this email, then your order is already in treatment. Below are the order information..." + "Name : " + MyOrderForm.Name + "Phone Number : " + MyOrderForm.Phone + "Email Address : " + MyOrderForm.Email + "Additional Information : " + MyOrderForm.AdditionalInfo + "Ordered pamphlet : " + MyOrderForm.Product + "Number of copies ordered : " + MyOrderForm.Amount #email_body = mymodalform.Product from_email = 'anyone@gmail.com' to_emails = ['anyone@gmail.com'] send_mail( email_subject, mymodalform.split(','), from_email, to_emails, fail_silently=False ) # Flash message to confirm order placement. messages.add_message( request, messages.SUCCESS, 'Your order was placed successfully! We\'ll soon contact you to confirm the order.' ) return redirect('Order') Here is my forms.py class MyOrderForm(forms.ModelForm): #Metadata class Meta: model … -
Consulta para acceder a los datos de un contexto en django [closed]
Estoy intentando acceder a los datos de una variable generada de la siguiente forma: enter image description here Luego quise desplegarla en mi template, pero no sé cómo acceder a cada dato, por ejemplo acceder uno de la tabla TrabajoRealizado y también acceder a algún dato de la tabla Mecanico. Había intentado la siguiente sintaxis (la cuál está mala por supuesto): enter image description here Adjunto los modelos de ambas tablas para mayor comprensión. De antemano, muchas gracias: class TrabajoRealizado(models.Model): id_trabajo = models.IntegerField( primary_key = True, verbose_name = "Id trabajo realizado", null = False, blank = False ) tipo_trabajo = models.CharField( max_length = 50, verbose_name = "Tipo de trabajo", null = False, blank = False ) mecanico = models.ForeignKey( Mecanico, on_delete=models.CASCADE, verbose_name = "mecanico", null = False, blank = False ) vehiculo = models.ForeignKey( Vehiculo, on_delete=models.CASCADE, verbose_name = "vehiculo", null = False, blank = False ) mas_informacion = models.CharField( max_length = 100, verbose_name = "Mas informacion", null = False, blank = False ) foto_trabajo = models.ImageField(upload_to = "fotosTrabajosDB") def __str__(self): return self.tipo_trabajo class Mecanico(models.Model): id_mecanico = models.IntegerField( primary_key = True, verbose_name = "Id mecanico", null = False, blank = False ) nombre_mecanico = models.CharField( max_length = 50, verbose_name = "Nombre … -
Navigation bar image is not loading
I am trying to add logo to my navigation bar but the image is not loading. code is as showing below, <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="/"><img src="PVPLogo.PNG" width="40" height="40" class="d-inline-block align-top"></a> <a class="navbar-brand" href="/"><h2>Electronic shop</h2></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="true" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> </div> </nav> I added my image in the App > Images folder > PVPLogo.PNG All I can see is -
django - improve performance of __in queryset in M2M filtering
I have a models that has a M2M relationship to another model. These are my models: class Catalogue(models.Model): city = models.CharField(db_index=True,max_length=100, null=True) district = models.CharField(db_index=True,max_length=100, null=True) type = models.ManyToManyField(Type, db_index=True) class Type(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name And this is views.py: class all_ads(generic.ListView): paginate_by = 12 template_name = 'new_list_view_grid-card.html' def get_queryset(self): city_district = self.request.GET.getlist('city_district') usage = self.request.GET.get('usage') status = self.request.GET.get('status') last2week = datetime.datetime.now() - datetime.timedelta(days=14) status = status.split(',') if usage: usage = usage.split(',') else: usage = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] intersections = list(set(status).intersection(usage)) type_q = (Q(type__in=intersections) & Q(type__isnull=False)) result = models.Catalogue.objects.filter( Q(datetime__gte=last2week) & type_q & ((reduce(operator.or_, (Q(city__contains=x) for x in city_district)) & Q(city__isnull=False)) | (reduce(operator.or_, (Q(district__contains=x) for x in city_district)) & Q(district__isnull=False))) ).distinct().order_by('-datetime').prefetch_related('type') return result I want to filter MySQL db with some queries and return result in a listview. It works good on a small database, but with large database it takes over 10 seconds to return results. If I delete type_q query, It takes 2 seconds (reduce 10 second!). How can I improve performance of __in queryset? -
No such File or directory "optimize-images"
I am using optimize-images (PyPi) library for optimizing images in a folder. (which is generated dynamically for every users). (Django Project) I have installed optimize-images using pip. Since, its a long running task i am using celery to first import the images to a directory and then running a command (optimize-images) on that directory for compressing all images. os.chdir(r'/home/django/image-io/accounts/'+dynamic_user+'/optimized/') cwd = os.getcwd() print("CURENT WORKING DIRECTORY") print(cwd) p=subprocess.Popen([r"optimize-images", cwd]) p.wait() where , dynamic_user is a user_name (string) optimized/ is the directory where all images are stored. I am not able to understand , why it says this error "No such file or directory: 'optimize-images'" Since, optimize-images is a command line utility and not a folder/file. Any help would be highly appreaciated. Here's the stack trace for err:-[2021-07-03 06:26:40,107: ERROR/ForkPoolWorker-2] Task home.tasks.product_import[c1a31047-5a11-493e-8e1b-fbc282e74a81] raised unexpected: FileNotFoundError(2, 'No such file or directory') Traceback (most recent call last): File "/home/django/image-io/env/lib/python3.8/site-packages/celery/app/trace.py", line 450, in trace_task R = retval = fun(*args, **kwargs) File "/home/django/image-io/env/lib/python3.8/site-packages/celery/app/trace.py", line 731, in __protected_call__ return self.run(*args, **kwargs) File "/home/django/image-io/home/tasks.py", line 185, in product_import p=subprocess.Popen([r"optimize-images", cwd]) File "/usr/lib/python3.8/subprocess.py", line 858, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib/python3.8/subprocess.py", line 1704, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: … -
Implement multi user login in Nuxt
I am using Nuxt 2.15 and Django 3.2.3. I would want to implement a multi user login with Nuxt. In the django project, I have an single model with an option of either a student or a teacher. On the frontend (NUXT), user can register as either a student or a teacher. When it gets to the login, if a user is a teacher, it should be directed to a teachers and if a student, to student's page. I would be grateful with any assistance on the latter case. -
Heroku application error (Django) deploy with github. at=error code=H10 desc="App crashed" dyno= connect= service= status=503 bytes= protocol=https
I am an absolute beginner to Django and python and created a website from Django. I am trying to host my website on Heroku and deploy it with GitHub but showing an application error. I am finding a way to fix this. Please help me. My github project :- Pyshop and heroku project: pysho. It is showing an application error. When I run the command: Heroku logs --tail --app pysho it shows: » Warning: Heroku update available from 7.53.0 to 7.54.1. 2021-07-03T05:04:53.682795+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2021-07-03T05:04:53.682796+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ 2021-07-03T05:04:53.682796+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2021-07-03T05:04:53.682796+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-07-03T05:04:53.682797+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-07-03T05:04:53.682797+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-07-03T05:04:53.682797+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-07-03T05:04:53.682798+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked 2021-07-03T05:04:53.682798+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-07-03T05:04:53.682798+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-07-03T05:04:53.682799+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-07-03T05:04:53.682799+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2021-07-03T05:04:53.682799+00:00 app[web.1]: ModuleNotFoundError: No module named 'ebgymmie' 2021-07-03T05:04:53.683086+00:00 app[web.1]: [2021-07-03 05:04:53 +0000] [7] [INFO] Worker exiting (pid: 7) 2021-07-03T05:04:53.777109+00:00 app[web.1]: [2021-07-03 05:04:53 +0000] [8] … -
having error (1054, "Unknown column 'order_product.id' in 'field list'") in django
I create the models file with inspectdb, but it gives an error when I want to show it in Admin panel: (1054, "Unknown column 'order_product.id' in 'field list'") In my searches, I realized I had to add a primary key to each of the models, but nothing happened when I did that. Here is my code: models.py class OrderProduct(models.Model): order = models.ForeignKey('Orders', models.DO_NOTHING) product = models.ForeignKey('Products', models.DO_NOTHING) attribute = models.ForeignKey(Attributes, models.DO_NOTHING, blank=True, null=True) color = models.ForeignKey(Colors, models.DO_NOTHING, blank=True, null=True) price = models.IntegerField(blank=True, null=True) attribute_price_differ = models.IntegerField(blank=True, null=True) attribute_price = models.IntegerField(blank=True, null=True) number = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'order_product' class Orders(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey('Users', models.DO_NOTHING) price = models.IntegerField() weight = models.IntegerField() coupon = models.ForeignKey(Coupons, models.DO_NOTHING, blank=True, null=True) status = models.IntegerField() process_status = models.IntegerField() code = models.CharField(max_length=255) hash = models.CharField(max_length=255) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'orders' #admin.py @admin.register(OrderProduct) class PostAdmin(admin.ModelAdmin): pass -
Django database routers - how do you test them, especially for migrations?
I've read the documentation on database routers in Django 2.2. I more or less understand the concept - including keeping certain tables together - except that it seems somewhat tricky to do in practice. I have defined the routers in settings: DATABASES = { "default": { "ENGINE": constants.POSTGRES_ENGINE, "NAME": constants.SYSDBNAME, ... }, "userdb": { "ENGINE": constants.POSTGRES_ENGINE, "NAME": constants.USERDBNAME, } DATABASE_ROUTERS = [ #the user database - userdb - which gets the auths and user-related stuff "bme.websec.database_routers.UserdbRouter", #the default database - sysdb "bme.websec.database_routers.SysdbMigrateRouter", ] Ideally I would use unit tests to submit all my models one by one to the routers' allow_migrate, db_for_read, db_for_write methods, and for each call, verify that I got the expected test results. But is there a way to do that? I suppose I can use models = django.apps.apps.get_models( include_auto_created=True, include_swapped=True ) and then drive those methods calls from unittests. But to take just def allow_migrate(self, db, app_label, model_name=None, **hints): How do I know when to have **hints and whether model_name is always provided or not? And most importantly, how do I simulate what the master router ultimately decides as stated in the doc (my emphasis)? Among other things, it doesn't rely on just one router, it … -
Multiple QuerySet to another Model
I'm writing the following code to search about category in profile model using Django ninja framework, if i retrieve only the fields in profile all query return, but when i need to get the username from the user model only one record return from the loop. profile.py class Profile(models.Model): SERVICEPROVIDER = 'service_provider' CUSTOMER = 'customer' user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') conf_password = models.CharField(max_length= 124) category = models.CharField(max_length= 80, blank=True, null=True) click = models.IntegerField(blank=True, default=0) date_clicked = models.DateTimeField(auto_now_add=True, blank=True,null=True) image_path = models.ImageField(upload_to='user_uploads/', blank=True) role = models.CharField(max_length=100, choices=[ (SERVICEPROVIDER, SERVICEPROVIDER), (CUSTOMER, CUSTOMER),]) profile_info = models.JSONField(blank=True, null=True) def __str__(self): return f'{self.user.username}' auth.py @auth.get("/search/{category}", auth=None, response={200: searchSchemaout, 404: MessageOut}) def search(request, category:str): profile = Profile.objects.filter(category__icontains=category).values() for i in range(len(profile)): user = get_object_or_404(User,id=profile[i]['id']) return 200, { "user": user, "profile": profile[i] } auth.py Schema class UserSchemaOut(Schema): username: str class profileSchemaout(Schema): role: str category: str class searchSchemaout(Schema): user: UserSchemaOut profile: profileSchemaout The result: { "user": { "username": "ahmed" }, "profile": { "role": "service_provider", "category": "doors" } } -
"Invalid data. Expected a dictionary, but got property."
Before this issue, when I tried to use request.data, it showed me an error saying attribute doesn't exist on WSGI Serializer class EmployeeSerializer(serializers.Serializer): # students = serializers.RelatedField(many=True, read_only=True) user = serializers.CharField(max_length=30) id = serializers.CharField(max_length=30) students = StudentSerializer(many=True,read_only=True) first_name = serializers.CharField() last_name = serializers.CharField(max_length=30) designation = serializers.CharField(max_length=40) # Data will be generally in JSON format def create(self, validated_data): # Student_det = validated_data.pop('stud_det') """ Create and return a new `Employee` instance, given the validated data. """ emp = Employee.objects.create(**validated_data) return emp def update(self, instance, validated_data): """ Update and return an existing `Employee` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance Serializer view @csrf_exempt def employee_list(request): if request.method == 'GET': employees = Employee.objects.all() user = User.objects.all() serializer = EmployeeSerializer(employees, many=True) serializer2 = UserSerializer(user, many=True) return JsonResponse(serializer.data, safe=False) if request.method == "POST": data_ = Request.data print(data_) serializer = EmployeeSerializer(data=data_) # serializer.data['user'] = user if serializer.is_valid(): print(serializer.data['user']) serializer.save() return JsonResponse(serializer.data, status=status.HTTP_201_CREATED) else: return JsonResponse(serializer.errors) Response trying to do an API post-call and what I am receiving is this, showing data is an attribute { "non_field_errors": [ "Invalid data. Expected a dictionary, but got property." … -
TypeError : verificationview() got an unexpected keyword argument 'uidb64' in django while email verification
I am trying to add email verification in my django app but when I click on the link which I get on email it gives out an error saying it got and unexpected argument views.py def sendmail(request): emailaddress=request.POST['email'] username=request.POST['username'] password=request.POST['password'] user = User.objects.create_user(email=emailaddress,username=username,password=password) user.is_active=False user.save() uidb64= urlsafe_base64_encode(force_bytes(user.pk)) domain = get_current_site(request).domain link= reverse('activate',kwargs={'uidb64':uidb64,'token':token_generator.make_token(user)}) activate_url='http://'+domain+link subject = 'Activate your Account' message = 'Hi' + user.username + "Please use the link for verification\n" + activate_url email_from = settings.EMAIL_HOST_USER recipient_list = [emailaddress] send_mail( subject, message, email_from, recipient_list ) messages.add_message(request,messages.SUCCESS,"Email sent") return render(request,'index.html') def verificationview(View): def get(self, request, uidb64, token): messages.add_message(request,messages.SUCCESS,"Account Activated") return redirect('/') utils.py class AppTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.is_active)+text_type(user.pk)+text_type(timestamp)) token_generator = AppTokenGenerator() urls.py urlpatterns = [ path('',views.loadpage), path('submit/',views.sendmail), path('activate/<uidb64>/<token>',views.verificationview,name='activate'), ] -
WHY request.GET.get('key') have two results?
I am using django for website. I want to send data from veiws.py to search_test.html. In terminal, they operate correctly. but in search_test.html, the data is none. why they have two different result? I used ajax to send input data to views.py. in views.py, I used request.GET.get('keyinput') for inputText variable using. here is my source code. please help me... search_test.html ... <form method = "GET" action = "{% url 'video:search' %} " id ="goSubmit"> <input name = "post_search_keyword" id = "post_search_keyword"> <button type = "submit" >submit</button> </form> <script> var oldVal var goSubmit = document.goSubmit; $("#post_search_keyword").on("propertychange change keyup paste input", function() { var currentVal = $(this).val(); if(currentVal == oldVal) { return; } oldVal = currentVal; var allData = { "keyinput": currentVal }; $.ajax({ url:"{% url 'video:search' %}", type:'GET', dataType:'json', data:allData }) aaa = "{{data}}" console.log(aaa) }); </script> <script> $(function () { //화면 다 뜨면 시작 var a = "{{restaurant|safe}}"; var array = a.split(","); console.log(array); var searchSource = array; // 배열 형태로 $("#post_search_keyword").autocomplete({ //오토 컴플릿트 시작 source: searchSource, // source 는 자동 완성 대상 select: function (event, ui) { //아이템 선택시 console.log(ui.item); }, focus: function (event, ui) { //포커스 가면 return false;//한글 에러 잡기용도로 사용됨 }, minLength: 1,// 최소 글자수 autoFocus: true, … -
React js Trying to Fetch data from my Django backend with state but I have multiple state obj
So here's the problem. I have multiple states that are being changed in my form, but I also want to change the value of all the key's when I fetch the data. How do I do this? Here's my code. class UserInfo extends Component { state = { userInfo: { birthPlace: "", bio: "", school: "", firstName: "", lastName: "", occupation: "", what_are_you_seeking_on_site: "", age: "", } } handleSubmit = (userInfo) => { //Fix backEnd where UserFields are saved because you only want one of the users not all fetch('http://localhost:8000/allUsers',{ method: "POST", headers: { 'content-type': "application/json" }, body: JSON.stringify(userInfo) }) .then(res => res.json()) .then(data => { this.setState({ }) }) } handleChange = (event) => { this.setState({ what_are_you_seeking_on_site: event.target.value }) } render() { const {classes} = this.props return ( <div> <Container component="main" maxWidth="xs"> <CssBaseline /> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign up </Typography> <form className={classes.form} onSubmit={this.handleSubmit} noValidate> <Grid container spacing={2}> <Grid item xs={12} sm={12}> <TextField autoComplete="fname" name="firstName" variant="outlined" required fullWidth id="firstName" label="First Name" autoFocus value={this.state.firstName} onChange={e => { this.setState({ firstName: e.target.value }) }} /> </Grid> <Grid item xs={12}> <TextField variant="outlined" required fullWidth id="lastName" label="Last Name" name="lastName" value={this.state.lastName} onChange={e => { this.setState({ lastName: e.target.value }) }} /> … -
Django rest framework access related custom fields
I want to sum all the Bars progress value in the FooSerializer The code order is FooSerializer.get_progress -> BarSerializer , I can't access BarSerializer.progess in FooSerializer. from django.db import models from rest_framework import serializers from rest_framework.viewsets import ModelViewSet class Foo(models.Model): name = models.CharField(max_length=180) class Bar(models.Model): foo = models.ForeignKey(Foo, related_name='bars', on_delete=models.CASCADE) class BarSerializer(serializers.ModelSerializer): progress = serializers.SerializerMethodField() def get_progress(self, instance): return 100 # some computed value class FooSerializer(serializers.ModelSerializer): bars = BarSerializer(many=True) progress = serializers.SerializerMethodField() def get_progress(self, instance): # how to access barSerializer's progress ? total = sum(x.progress for x in instance.bars) return total -
Getting 403 Forbidden error on post requests when serving django app on Amazon cloud front through heroku
I have a django app deployed in heroku, which was working previously, however after adding the Edge add-on, which serves your static files from Amazon cloudfront for caching, all of my post requests are getting 403 errors. I do pass the csrf token correctly, as my post requests still work when not served from cloudfront, but on cloudfront I am getting the error that the CSRF Verification failed It also mentions that the referer header is missing, however I can see referer specified in the request headers in the network tab of the developer tools. Any idea what I am missing here? -
It is possible to use spotify API to everyone listen a song?
I'm plannig to do a chat app with djano and django-channels that will allow me to run te application asyncronous, I want to implement the spotify API for everyone in the room listen to some music, it is possible to do this in an async application? -
Django Q task result decrypt
Can somehow tell me how to decrypt the result in django_q_task table when the task failed I check the documentation and still cant get it https://django-q.readthedocs.io/en/latest/tasks.html