Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding a field to custom Django Form Field
I just need one custom extra attribute in my Django form fields which is icon. I will take the example of my custom CharField. custom_fields.py: class ICharField(forms.CharField): """ Django CharField with custom icon field to use along with Bulma. """ icon = '' def __init__(self, *, icon='', max_length=None, min_length=None, strip=True, empty_value='', **kwargs): super().__init__(**kwargs) self.icon = icon forms.py: from utils.forms import custom_fields class SignUpForm(forms.Form): company_name = custom_fields.ICharField( icon='fas fa-envelope', widget=forms.TextInput(attrs={ 'class': 'input', 'placeholder': _('Name of your company'), 'label': _('Company'), }) ) That's it, but when in the HTML I try to access to {{ field.icon }} I'm getting nothing. the.html: {% extends 'template_composition/main.html' %} {% load i18n %} {% block content %} {% for field in form %} <div class="field"> <b>{{ field.label }}:</b> <p class="control has-icons-left"> {{ field }} <span class="icon is-small is-left"> <i class="{{ field.icon }}"></i> </span> </p> </div> {% endfor %} {% endblock %} It's obvious I'm overriding __init__ wrong, right? -
Django: How to detect the focus out in django template and call a function on it
I am working on a project. Need help in template focus out events on Django. model.py class Route(models.Model): route_no = models.SmallIntegerField(default=0) xname = models.CharField(max_length=40) class Booth(models.Model): booth_no = models.SmallIntegerField(default=0) route_no = models.ForeignKey(Route, on_delete=models.CASCADE, db_column='route_no') View.py class BoothCreateListView(CreateView, ListView): model = models.Booth form_class = booth.BoothForm template_name = 'booth/booth_create_list.html' context_object_name = 'booth_list' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) js_data = list(models.Route.objects.all().values_list('route_no', 'xname')) context['js_data'] = json.dumps(list(js_data), cls=DjangoJSONEncoder) return context template/booth_create_list.html <div class="col-sm-12 col-md-5"> <form method="post"> {% csrf_token %} <table class="table table-borderless"> {{ form.as_table }} </table> <input class="btn btn-success" type="submit" value="Save"> </form> {{ form.route.value }} </div> <div id='route_no'></div> <script> var route_no = document.getElementById('route_no') var myfunction = function (){ console.log('changing'); route.innerHTML = '{{ check_route_no form.route.value }}' } </script> form/booth.py class BoothForm(ModelForm): class Meta: fields = [ 'route_no', 'booth_no', ] model = models.Booth widgets = { 'route_no': forms.TextInput(), } labels = { 'route_no': 'Route No.', 'booth_no': 'Booth No', } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['route_no'].widget.attrs.update( {'onfocusout':'myfunction()'} ) for name, field in self.fields.items(): field.widget.attrs.update( {'class': 'form-control form-control-user'} ) templatetags/booth_template_tags.py from booth import models register = template.Library() @register.simple_tag def check_route_no(route_no): print(route_no) route = models.Route.objects.filter(route_no=route_no) if route.count() == 1: return route.xname else: return "not present" I want to check the route as user types it in the form … -
I'm facing some issues with pip verrsion 20.1.1. Down below is the exact error I'm getting in CMD
Here is the code which I'm geting from CMD. I'm running winows 10 What to do here? I can vsee pip version and other options with main but can't download/install any packages. D:\Python>python.exe -m pip install --upgrade pip Traceback (most recent call last): File "D:\Python\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "D:\Python\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:\Python\lib\site-packages\pip\__main__.py", line 26, in <module> sys.exit(_main()) File "D:\Python\lib\site-packages\pip\_internal\cli\main.py", line 73, in main command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) File "D:\Python\lib\site-packages\pip\_internal\commands\__init__.py", line 104, in create_command module = importlib.import_module(module_path) File "D:\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\Python\lib\site-packages\pip\_internal\commands\install.py", line 24, in <module> from pip._internal.cli.req_command import RequirementCommand, with_cleanup File "D:\Python\lib\site-packages\pip\_internal\cli\req_command.py", line 16, in <module> from pip._internal.index.package_finder import PackageFinder File "D:\Python\lib\site-packages\pip\_internal\index\package_finder.py", line 21, in <module> from pip._internal.index.collector import parse_links File "D:\Python\lib\site-packages\pip\_internal\index\collector.py", line 14, in <module> from pip._vendor import html5lib, requests File "D:\Python\lib\site-packages\pip\_vendor\html5lib\__init__.py", line 25, in <module> from .html5parser import HTMLParser, parse, parseFragment File "D:\Python\lib\site-packages\pip\_vendor\html5lib\html5parser.py", line 7, in <module> from … -
Using CSRF in an AJAX Call causes Uncaught TypeError: Cannot read property 'value' of null
I am struggling to figure out why my code is returning an error that is being caused by using CSRF in an Ajax call. The error is this: Uncaught TypeError: Cannot read property 'value' of null at HTMLUListElement.<anonymous> Here is my AJAX Call including setup: var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ type: "POST", url : '/api/uservenue/', data: { 'cafeName': cafeName, 'list_id': 1, csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value }, success: function(data){ console.log('User clicked: ' + data) }, failure: function(errMsg) { alert(errMsg); } }); Here is my views.py file [...] class UserVenue(viewsets.ModelViewSet): serializer_class = UserVenueSerializer queryset = UserVenue.objects.all() @ensure_csrf_cookie def get_queryset(self): cafeName = self.request.GET.get('cafeName', None) print(cafeName) return UserVenue.objects.all() [...] What I've tried My JS script is at bottom of html file. I've tried a bunch of different edits and tweaks based on reading through documentation/SO/Reddit suggestions. I tried using method_decorators, but this seemed to raise more errors. I'd be grateful for any advice. Thanks! -
Delete item from InlineForm in Django
I've created an InlineForm to add some Staff Members to a Project, but the form needs to be editable, and when I try to delete 1 of the Staff Members I get an error: get() returned more than one Colaboradores -- it returned 8! I can't send the ID to the view and can't get the Staff Member to be deleted. How can I fix it? edit_form.py def editar_projeto(request, projeto_id): if request.method == 'GET': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = EditForm(instance=projeto_editar) form_colab_factory = inlineformset_factory(Projeto, Colaboradores, form=ColabForm, extra=1, max_num=5) form_colab = form_colab_factory(instance=projeto_editar) context = { 'form': form, 'form_colab': form_colab, } return render(request, 'editar_projeto.html', context) elif request.method == 'POST': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = EditForm(request.POST, request.FILES, instance=projeto_editar) form_colab_factory = inlineformset_factory(Projeto, Colaboradores, form=ColabForm, extra=1, max_num=5) form_colab = form_colab_factory(request.POST, instance=projeto_editar) if form.is_valid() and form_colab.is_valid(): projeto_editado = form.save() form_colab.instance = projeto_editado form_colab.save() return redirect('projeto', projeto_editar.id) else: context = { 'form': form, 'form_colab': form_colab, } return render(request, 'editar_projeto.html', context) def deletar_colaborador(request, colaborador): colaborador = Colaboradores.objects.get(colaborador_projeto=colaborador) colaborador.delete() return redirect('editar_projeto') urls.py path('deletar_colaborador/<str:colaborador>', views.deletar_colaborador, name='deletar_colaborador') models.py class ColabForm(forms.ModelForm): class Meta: model = Colaboradores fields = '__all__' colaborador_projeto = forms.CharField(label="Colaborador do Projeto", widget=forms.TextInput( attrs={ 'class': 'form-control col-8', 'maxlength': '200', … -
Django cyclic imports and typechecking with mypy
I'm trying to create a simple custom manager with one of my Django models. It causes a cyclic import since I'm trying to import the manager from models.py and the model from managers.py. However, because my manager is creating the model and adding some extra attributes, the type hint for the method is the model instance. I'm having trouble with fixing that type hint since it's not yet imported. # models.py from .managers import PublishedBundleManager class PublishedBundle(models.Model): data = JSONField() md5_checksum = models.CharField(max_length=128) objects = PublishedBundleManager() The manager has a method to help me create the model instance, but as a convenience, calculates a checksum to fill in during creation. To fix the cyclic imports, I made use of typing.TYPE_CHECKING # managers.py import typing as t from django.apps import apps from django.db import models if t.TYPE_CHECKING: PublishedBundle = apps.get_model(app_label="the_hugh", model_name="PublishedBundle") class PublishedBundleManager(models.Manager): # Error 1 def create_publish(self, data: t.Dict, description: str) -> PublishedBundle: # Error 2 PublishedBundle = apps.get_model(app_label="my_app", model_name="PublishedBundle") json_data = json.dumps(data, sort_keys=True) md5_checksum = hashlib.md5(json_data.encode("utf-8")).hexdigest() return PublishedBundle.objects.create(data=data, md5_checksum=md5_checksum) However, I'm getting 2 errors. Missing type parameters for generic type "Manager" [type-arg]mypy(error) name 'PublishedBundle' is not defined I'm fairly new with typed python and never faced this issue before. … -
how to solve problem related to add to cart function in views.py
Basically, I am a beginner and following a tutorial of e-commerce project in django. when it comes to add_to_cart() function I do not understand the main concept of add_to_cart(). Code is given below and I want to clear my concepts that how add_to_cart's code is functioning? please help me to understand the concept. def add_to_cart(request): item = get_or_404(Item, slug=slug) order_item = OrderItem.objects.get_or_create(item = item ) # it is bothering me order_qs = Order.objects.filter(user = request.user, ordered = False) # it is bothering me if order_qs.exists(): order = order_qs[0] # it is bothering me. # check if order item is in the order. if order.items.filter(item__slug = item.slug).exists() order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: ordered_date = timezone.now() order = Order.objects.create(user = request.user, ordered_date =ordered_date) order.items.add(order_item) return render(request, 'URL's Name') -
Django 3: get_object_or_404 for UpdateView
I have a problem: I'd like to update a specific data/product, but a can't use get_object_or_404 views.py from django.shortcuts import render,get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib import messages from django.views.generic import ( UpdateView, DeleteView ) from product.models import Product from pages.forms import ProductForm def ProductUpdateView(request, pk): # queryset = Product.objects.all()[0].pk_id <-- I tried this # queryset = Product.objects.get() <-- and this queryset = Product.objects.all() product1 = get_object_or_404(queryset, pk=pk) #product1 = get_object_or_404(Product, pk=pk) <-- and this if request.method == 'POST': productUpdate_form = ProductForm(data=request.POST,files=request.FILES,instance=request.product1)) # Check to see the form is valid if productUpdate_form.is_valid(): # and profile_default.is_valid() : # Sava o produto productUpdate_form.save() # Registration Successful! messages.success messages.success(request, 'Produto Modificado com Sucesso') #Go to Index return HttpResponseRedirect(reverse('index')) else: # One of the forms was invalid if this else gets called. print(productUpdate_form.errors) else: # render the forms with data. productUpdate_form = ProductForm(instance=request.product1) context = {'productUpdate_form': productUpdate_form,} return render(request, 'base/update.html',context) urls.py from django.urls import include, path from pages.views import (ProductListView, ProductUpdateView, ProductDeleteView) urlpatterns = [ path('listProduct/', ProductListView, name='listProduct'), path('<int:pk>/update/', ProductUpdateView, name='product-update'), <--this link is ok ] Error: AttributeError at /1/update/ 'WSGIRequest' object has no attribute 'product1' Request Method: GET Request URL: http://127.0.0.1:8000/1/update/ Django Version: 3.1.1 Exception Type: AttributeError … -
How can a unique timestamp be incremented on constraint violation in a Django model?
As part of using TimescaleDB, which requires a timestamp as the primary key (time in SensorReading), I need to handle the case when the same timestamp is used by different sensor values. One elegant solution might be to smear colliding timestamps (add a microsecond on collision). How can this problem be solved in a robust and performant manner for the following models? class Sensor(models.Model): name = models.CharField(max_length=50) class SensorReading(models.Model): time = models.DateTimeField(primary_key=True, default=datetime.now) sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE) value = models.FloatField() P.S. This is a workaround as Django does not support composite primary keys. Otherwise it would be possible to set the sensor and timestamp as a composite primary key. -
ImportError Django (but I think its because of python)
I working in a project that uses python 3.6.9 and django 3.1.1 using it on a virtual enviroment with virtualenv, somerall python in my computer updated to the version 3.8.2 and somerall changed the virtual enviroment too , and now i can't even run the server. this is the steps that i do: source bin/activate in the folder of my project i do that: python manage.py runserver but It keeps given this error: Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? if I enter : $ python3 --version Python 3.8.2 if I miss some information about the problem please tell me... I new here :) -
Template is giving wrong path to media directory and Django can't find the images
I have 2 models and their relationship it's OneToMany. So, one "imovel" (portuguese word to property) has many pictures ("fotos" or "imagens" in portuguese). My web application structure is very simple and I configured at settings: settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('', index, name='index'), path('sobre_nos/', sobre_nos, name='sobre_nos'), path('', include('imoveis.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So every picture that is uploaded, goes directly to 'media' structure and the images for properties goes to 'media/imoveis/%Y/%m/%d'. I want to show all pictures associated to a property in a template using a basic bootstrap carousel: imovel.html <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for foto in fotos_do_imovel %} {% if foto.imagem %} <div class="carousel-item activate"> <img class="d-block w-100" src="{{ foto.imagem }}"> </div> {% else %} <div class="carousel-item"> <img class="d-block w-100" src="{{ imovel.foto_principal }}"> </div> {% endif %} </div> {% endfor %} <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Anterior</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Proxima</span> </a> </div> The problem is, when I access the page to imovel.html, the pictures are not found: imoveis/2020/10/01/pexels-photo-1571463.jpeg imoveis/2020/10/01/pexels-photo-1643383.jpeg [01/Oct/2020 21:20:35] "GET /imovel/3 HTTP/1.1" 200 5952 Not Found: /imovel/imoveis/2020/10/01/pexels-photo-1643383.jpeg Not Found: /imovel/imoveis/2020/10/01/pexels-photo-1571463.jpeg [01/Oct/2020 … -
Unable to run Django Test Server in Ubuntu Server 16.04
I have 2 servers. I am attempting to setup one for continuous integration for my main website server Web server 1(cloud-hosting): Python3.6 Django3.1 Ubuntu16.04 Webserver 2(VPS): Python3.7 Django3.1 Ubuntu16.04 Jenkins --ShiningPanda(plugin) Im new to web development, so if it seems odd as far as my web server types, that is why. I have been following along in the book Test Driven Development with Python. My issue is that when running python manage.py test [app] My [app] inherits from the class StaticLiveSever to generate a testing environment. On webserver 1, this works fine. On webserver 2, i get an error that the request address cannot be assigned. I use jenkins to build the environment, but the error i get is OSerror[99]:cannot assign to requested address. I dont understand why this is happening when i run the same commands in Web Sever 1. It runs fine. Although again, the commands are run by jenkins and jenkins is configured to run python3.7 Full Traceback(Main Issue) Traceback (most recent call last): File "/var/lib/jenkins/shiningpanda/jobs/ddc1aed1/virtualenvs/d41d8cd9/lib/python3.7/site-packages/django/test/testcases.py", line 1449, in setUpClass raise cls.server_thread.error File "/var/lib/jenkins/shiningpanda/jobs/ddc1aed1/virtualenvs/d41d8cd9/lib/python3.7/site-packages/django/test/testcases.py", line 1374, in run self.httpd = self._create_server() File "/var/lib/jenkins/shiningpanda/jobs/ddc1aed1/virtualenvs/d41d8cd9/lib/python3.7/site-packages/django/test/testcases.py", line 1389, in _create_server return ThreadedWSGIServer((self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False) File "/var/lib/jenkins/shiningpanda/jobs/ddc1aed1/virtualenvs/d41d8cd9/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 67, in … -
Automatically update database field to True with django background tasks
I have a Model Job that has a field filled. I want to automatically update filled to True if the current date and time is greater than or equal to the Job's end date and time. The end date is set when creating the job. I am using Django background task to check all Jobs in the DB and repeat the process always, but I can't get it to work. Here is my code Model.py class Job(models.Model): # title, description, requirements, job type etc. end_date = models.DateTimeField() current_date = models.DateTimeField(null=True, blank=True) filled = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title task.py @background(schedule=60) def auto_mark_as_filled(job_id): jobs = Job.objects.filter(pk=job_id, filled=False) for job in jobs: job.current_date = timezone.localtime(timezone.now()) if job.current_date >= job.end_date: job.filled = True job.save() I am calling the task from my forms.py. when I create a new job I register it. forms.py class CreateJobForm(forms.ModelForm): def __init__(self, *args, **kwargs): # first call parent's constructor super(CreateJobForm, self).__init__(*args, **kwargs) # there's a `fields` property now self.fields['end_date'].required = True class Meta: model = Job fields = ('title', 'location', 'description', 'requirement', 'years_of_experience', 'job_type', 'end_date') exclude = ('user', 'created_at', 'current_date', 'filled') widgets = { 'end_date': DateTimePickerInput(format='%Y-%m-%d %H:%M') } def save(self, commit=True): job = super(CreateJobForm, self).save(commit=False) job.save() … -
How to use an image generated in Javascript in a function inside my Django's view?
I'm making an application where my view renders a template with information, then inside my template with Javascript I create a canvas element, I have the data:URI in my Javascript code, but I want to save correctly that image in my MEDIA_ROOT (supposed in /media/report directory) on my server in a Django's way, as I do in another view with a form, but this is not a form! Is a success page where render the template with information and in the same view I have a function that I need that image, maybe my problem can be a little tricky but I will put a screenshot and my view to show what I want to do. I don't know if I'm thinking correctly. I really don't need to save that image, just need to use in the function do_something_with_image() def success(request, report_id): data1 = data2 = '' try: report = Report.objects.get(id=report_id) data1= report.data1 data2= report.data2 #picture_path is /media/report/report_id.png or the file generated in Javascript do_something_with_image(picture_path) except: messages.error(request, "Error") context={ 'report_id': report_id, 'data1': data1, 'data2': data2, } return render(request, 'exito.html', context) Maybe I need to do a POST request? Here is my template code with the javascript code: <div id="report"> {{data1}} … -
who to write url in django
form in navbar I have one form in navbar template and I want to fetch the data of this form from any page of my site how should I write my URL. views.py url.py -
How to assign a value to AArrayField?
In my models: class User(models.Model): ... transactions = ArrayField(models.CharField(max_length=100), default=list()) my views: @api_view(['GET', 'POST', 'DELETE']) def user(request): if request.method == 'POST': user_data = JSONParser().parse(request) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse(user_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) When try to test the api with postman with this input, the transaction stays empty. { ... "transactions": ["test"] } -
django rest framework serializer - doesn't return empty list field
I have a serializer for a model that contains JsonField. I want to always return specific fields, even when they are not found within the jsonField. When calling 'get' - it does return all fields in the serializer, but when calling 'update', it returns the instance with the updated fields and allow_null=True, so default=list field that wasn't update - would not return in the response. The question is how can I still return all serializer fields in response, including the default=list fields, even when they weren't updated and not exist? this is the serializer - class ObjectsListSerializer(serializers.Serializer): days = serializers.IntegerField(allow_null=True, source='objects_list.days') user_list = serializers.ListField(child=serializers.CharField(), default=list, allow_empty=True, required=False, source='objects_list.user_list') manager = serializers.CharField(allow_null=True, source='objects_list.manager') def update(instance, validated_data): if 'objects_list' in validated_data: for attr, value in validated_data['objects_list'].items(): instance.objects_list[attr] = value instance.save() return instance As mentioned, when sending 'get' request, even when 'objects_list' is empty, I would get days=None user_list=[] manager=None in the response But when user_list doesn't exist and I'm updating other field ('days' for example), 'user_list' will not exist in the response. Any idea how can I still return the empty list when it doesn't exist? -
Implementing reset password for different user app in django
PLease I have two two apps that handle two kinds of users in my project. The two kinds of user have different privileges on the site (I also have groups based on these two user account apps). The problem am having is that the default. from django.contrib.auth import views as auth_views has only one file structure in contrib/admin/templates/registration. I have this in urls.py for the diferent apps: path('reset_password/', auth_views.PasswordResetView.as_view(template_name="users/reset_password.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="users/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="users/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="users/password_reset_done.html"), name="password_reset_complete"), For the second app, I have this in the urls.py path('reset_password/', auth_views.PasswordResetView.as_view(template_name="companyusers/reset_password.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="companyusers/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="companyusers/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="companyusers/password_reset_done.html"), name="password_reset_complete"), but django does not seem to find the template paths unless I put the html files in the general templates folder for the project thus: path('reset_password/', auth_views.PasswordResetView.as_view(template_name="reset_password.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name="password_reset_complete"), So when a user resets to password, the final login page points to just the login page for one user. Meanwhile the two apps in the project has two different login pages. when I try to use url name-spacing for the reset password url paths, django is not able to find them since they are not in the root directly. Please how … -
fix JavaScript LoadMore button to load 5 items per page - Django
fix JavaScript #LoadMore button to load 5 items per page - Django i want show 5 item per once then user click on LoadMore button then it will load more 5 items how to do that with js ? html code : {% for mobile in mobileforhome %} <div class="card-deck"> <div class="card mb-3" style="max-width: 800px;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="Mobile/{{ mobile.slug }}"><img style="height:100%;width:100%;border-radius:6.5px;" src="{{ mobile.get_image }}" class="rounded float-right" alt="..."></a> </div> <div class="col-md-8"> <div class="card-body"> <a href="Mobile/{{ mobile.slug }}"> <h5 class="card-title" id="primary_site_pages_app_name_control"> <b>{{ mobile.name }}</b></h5></a> <p class="card-text" id="font_control_for_all_pages">{{ mobile.app_contect|truncatechars_html:153|safe}}</p> </div> <div class="card-footer"> <small class="text-muted" id="date_post_control">{{ mobile.post_date}}</small> <small class="firstsmall"><a class="bg-orange" href="{% url 'mobile' %}" id="tag_name_control">هواتف</a></small> </div> </div> </div> </div> </div> <hr> {% endfor %} <!-- show more button --> <div class="text-center mt-4"> <a role="presentation" type="button" class="btn btn-secondary btn-lg loadMore" style="width:40%;color:white">Show More</a> </div> <!-- script controll the games ( show 6 game per page ) --> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <script> const thumbnails = $(".card-deck .card mb-3"); let visibleThumbnails = 0; function showThumbnailsUntil(index) { for (var i = visibleThumbnails; i <= index; i++) { if (i < thumbnails.length) { $(thumbnails[i]).addClass('visible'); visibleThumbnails++; } else { break; } } } showThumbnailsUntil(2); $(".loadMore").on("click",function(){ showThumbnailsUntil(visibleThumbnails + 2) if(visibleThumbnails === thumbnails.length) { $(".loadMore").fadeOut(); //this will hide //button when … -
Like Button Django Ajax
I'm trying to create my like button with Ajax but this stopped me at the beggining. The function wont preventDefault. <script> var a = "{{ post.id }}" $(document).ready(function(){ $("#demo"+a).modal({show:true}); $('.like-form').submit(function(e){ e.preventDefault() console.log('works')}); }); </script> <input type="hidden" name="post_id" value="{{post.id}}"> <button type="submit" class="ui bwhite-sm button like-btn{{post.id}}"> {% if user.profile not in post.liked.all %} LIKE {% else %} UNLIKE {% endif %} </button> <div>{{post.liked.all.count}}</div> </form> -
KeyError in graphql when reusing DRF serializer
So I am trying to implement graphql and reuse my serializer.py file but am getting "name 'request' is not defined". I can see what it's referencing on the serializer but no clue how to fix it. It seems to be hanging on the self.context["request"] I used to pop the password field from my put methods when using drf. any ideas as to how best to get around this. I am still learning and seem to be hitting a wall. Any help would be greatly appreciated. Thank you in advance. serializer.py class UserSerializer(serializers.ModelSerializer): """Serializes the user model""" # name = serializers.CharField(max_length=10) specialties = serializers.PrimaryKeyRelatedField( many=True, queryset=models.Specialty.objects.all() ) class Meta: model = models.User fields = "__all__" extra_kwargs = { "password": {"write_only": True, "style": {"input_type": "password"}} } def __init__(self, *args, **kwargs): super(UserSerializer, self).__init__(*args, **kwargs) if self.context["request"].method == "PUT": self.fields.pop("password") def create(self, validated_data): """Create and return a new user""" user = models.User.objects.create_user( email=validated_data["email"], first_name=validated_data["first_name"], last_name=validated_data["first_name"], password=validated_data["password"], ) return user mutations.py class CreateUser(SerializerMutation): class Meta: serializer_class = UserSerializer error NameError at /graphql/ name 'request' is not defined Request Method: GET Request URL: http://localhost:8000/graphql/ Django Version: 3.0.10 Exception Type: NameError Exception Value: name 'request' is not defined Exception Location: /dsinfinitum/backend/ds_admin/schema.py in Meta, line 106 Python Executable: … -
cant import the file itself in pyinstaller
i am trying to use pyinstaller to pack my single file web application as follow, which can be run normally by tested, hoping to use it in another computer without python import os this = os.path.splitext(os.path.basename(__file__))[0] if __name__ == '__main__': import sys from daphne.cli import CommandLineInterface sys.exit(CommandLineInterface().run(["-p", "30003", this + ":application"])) else: import django from django.conf import settings from django.core.asgi import get_asgi_application from django.urls import re_path from django.http import JsonResponse DEBUG = True urlpatterns = [ re_path(r'^', lambda x: JsonResponse({'msg': 'success'})) ] SETTINGS = dict( DEBUG=DEBUG, ROOT_URLCONF=this ) settings.configure(**SETTINGS) django.setup() application = get_asgi_application() but when i run the packed file, it returns Error daphne/server.py:11: UserWarning: Something has already installed a non-asyncio Twisted reactor. Attempting to uninstall it; you can fix this warning by importing daphne.server early in your codebase or finding the package that imports Twisted and importing it later on. Traceback (most recent call last): File "single.py", line 9, in <module> File "daphne/cli.py", line 252, in run File "daphne/utils.py", line 12, in import_by_path File "importlib/__init__.py", line 127, in import_module File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'single' [596096] Failed to execute … -
How to change Django static files
I know this might be a really obvious question, but I'm doing a Django project where I have Javascript in my static files. However, I have noticed that whenever I make a change to those files, my web server doesn't reflect the changes. Is there some migration or something else I need to do to make my web server reflect changes to my static Javascript files? Thanks. -
How to access djagno built in login system fields
So when I look on tutorials online on how to use the django built in login system I found that they use {{ form.as_p }} in templates, how can I access each field individualy in tmeplates so I can put them in my own styled template ? -
How can i set permission on url
I am new on Django, I have implemented a valid form and now i want to set permission on url. When a form is submit then it redirects me to this url http://127.0.0.1:8000/success/. Without submitting a form i can manually type the name of the url "http://127.0.0.1:8000/success/" and it will take me to the same page. How can i set permission on "success" url, so that user can not manually view the page unless the form is valid and submitted. Do i need a decorator for this? Model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) profile_pic = models.ImageField(upload_to='ProfilePicture/', default="ProfilePicture/avatar.png", blank=True) phone = models.IntegerField(default='0', blank=True) email = models.EmailField(blank=True) date_of_birth = models.CharField(max_length=50, blank=True) address = models.TextField(blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' ordering = ['-date'] '''Method to filter database results''' def __str__(self): return self.user.username class CotCode(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) cot_code = models.IntegerField(default='0', blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'CotCode' verbose_name_plural = 'CotCode' ordering = ['-date'] def __str__(self): return self.user.username Url: path('cot/', TransferCOTView, name='transfer_cot'), path('success/', SuccessfulView, name='successful_trans'), Views: @login_required def TransferCOTView(request): form = CotCodeForm(request.POST) if request.method == "POST": if form.is_valid(): cot_code = form.cleaned_data.get('cot_code') try: match = CotCode.objects.get(cot_code=cot_code) return redirect('site:successful_trans') except CotCode.DoesNotExist: messages.info(request, "Wrong code") else: form = …