Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku adds an extra "/checkout" in the URL when completing order with Stripe using Django
I have a small ecommerce project hosted on Heroku that I've built using Django, when clicking "complete order" on the checkout page I should be taken to the template "checkout_success" but instead I get stuck on the same page due to the URL trying to find a path with an extra "/checkout". I've posted some screenshots below to further explain. Checkout app URLS.py: from django.urls import path from . import views from .webhooks import webhook urlpatterns = [ path('', views.checkout, name='checkout'), path('checkout_success/<order_number>', views.checkout_success, name='checkout_success'), path('cache_checkout_data/', views.cache_checkout_data, name='cache_checkout_data'), path('wh/', webhook, name='webhook'), ] Heroku Logs Error: **notice the extra "/checkout" in the POST URL. Same in the browser console URL I've tried an array things from adding and taking away "/" in my settings.py file and other URL paths. I'm sure this is something im overlooking but i've been stuck with this bug for days now. If anyone could help that would be great! And if any additional info is needed i'll be happy to provide. Thanks! -
Returned a template response with no `template_name` attribute set on either the view or response (drf-yasg2)
I setup everything as per the docs of drf-yasg2 but I'm getting this error and I can't find whats causing it. I went through the docs and there is nothing I can use from there. It looks like every response is falling back to the TemplateHTMLRenderer instead of using drf-yasg2 ReDoc or SwaggerUI renderers. def render(self, swagger, accepted_media_type=None, renderer_context=None): if not isinstance(swagger, Swagger): # pragma: no cover return TemplateHTMLRenderer().render( swagger, accepted_media_type, renderer_context ) self.set_context(renderer_context, swagger) return render_to_string( self.template, renderer_context, renderer_context["request"] ) This condition will never return false if not isinstance(swagger, Swagger): because the Response class from djangorestgramework (response.py) is calling this method with the self.data instead of a rendered as a parameter: ret = renderer.render(self.data, accepted_media_type, context) I have no idea what I'm doing wrong here. In my project I use: drf-yasg2==1.18.5 djangorestframework==3.8.0 Django==2.0.1 urls.py from rest_framework import permissions from drf_yasg2.views import get_schema_view from drf_yasg2 import openapi schema_view = get_schema_view( openapi.Info( title="Snippets API", default_version='v1', description="Test description", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), settings.py -> INSTALLED_APPS INSTALLED_APPS = [ 'rest_framework', 'myappname', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fcm_django', 'storages', 'colorfield', 'drf_yasg2', ] The error Internal Server Error: /swagger/ … -
Heroku - Django App Crased Error H10 status
heroku logs --tail --app the-milky-way-airlines 2020-10-16T10:26:30.053966+00:00 app[web.1]: [2020-10-16 10:26:30 +0000] [9] [INFO] Booting worker with pid: 9 2020-10-16T10:26:30.059087+00:00 app[web.1]: [2020-10-16 10:26:30 +0000] [9] [ERROR] Exception in worker process 2020-10-16T10:26:30.059088+00:00 app[web.1]: Traceback (most recent call last): 2020-10-16T10:26:30.059088+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-10-16T10:26:30.059089+00:00 app[web.1]: worker.init_process() 2020-10-16T10:26:30.059089+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-10-16T10:26:30.059089+00:00 app[web.1]: self.load_wsgi() 2020-10-16T10:26:30.059089+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-10-16T10:26:30.059090+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-10-16T10:26:30.059090+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-10-16T10:26:30.059090+00:00 app[web.1]: self.callable = self.load() 2020-10-16T10:26:30.059091+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-10-16T10:26:30.059091+00:00 app[web.1]: return self.load_wsgiapp() 2020-10-16T10:26:30.059091+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-10-16T10:26:30.059091+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-10-16T10:26:30.059092+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2020-10-16T10:26:30.059092+00:00 app[web.1]: mod = importlib.import_module(module) 2020-10-16T10:26:30.059092+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/init.py", line 127, in import_module 2020-10-16T10:26:30.059092+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-10-16T10:26:30.059092+00:00 app[web.1]: File "", line 1014, in _gcd_import 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 991, in _find_and_load 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 961, in _find_and_load_unlocked 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 219, in _call_with_frames_removed 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 1014, in _gcd_import 2020-10-16T10:26:30.059094+00:00 app[web.1]: File "", line 991, in _find_and_load 2020-10-16T10:26:30.059094+00:00 app[web.1]: File "", line 973, in _find_and_load_unlocked 2020-10-16T10:26:30.059094+00:00 app[web.1]: ModuleNotFoundError: No module named 'the_milky_way_airlines' 2020-10-16T10:26:30.059216+00:00 app[web.1]: [2020-10-16 … -
Django - document.querySelector finds the base.html tags only
I have the django app with traditional base.html approach, which is extended in every other template. However, I have a problem with reaching out html tags which are outside the base.html template. var myHeading = document.querySelector(".contentfont"); console.log(myHeading); gives me: <div class="contentfont"> <!-- JS --> <script src="/static/js/squad_picker.js" type="text/javascript"></script> <h1 id="test" class="heading test"> test page </h1> <div class="container"> <div class="jumbotron"> </div> </div> </div> but when I try for example var myHeading = document.querySelector(".contentfont > h1"); it always gives me null. The same happens while trying to access anything which is not inside base.html directly by id or class. I add the part of base.html: <div class="contentfont"> {% block content %} {% endblock %} </div> and the html which is extending it: {% extends 'my_app/base.html' %} {% load static %} {% block content %} <!-- JS --> <script src="{% static 'js/squad_picker.js' %}" type="text/javascript"></script> <h1 id='test' class="heading test">test page </h1> <div class="container"> <div class="jumbotron"> </div> </div> {% endblock %} -
Can't get django pagination work with related fk set
I'm a django beginner and i'm trying to build a website using only generic CBV. In my models i have a class called Project and another class called ProjectFile as follow: class Project(models.Model): STATUS = ( ('Ongoing', 'Ongoing'), ('Ended', 'Ended'), ('Abandoned', 'Abandoned'), ) name = models.CharField(max_length=200, unique=True, error_messages={'unique':"This project name already exists"}, null=True) description = models.TextField(null=True) status = models.CharField(max_length=100, null=True, choices=STATUS) start_date = models.DateField(null=True) end_date = models.DateField(blank=True, null=True) team = models.ForeignKey(Team, on_delete=models.CASCADE) def __str__(self): return self.name class ProjectFile(models.Model): file = models.FileField(upload_to='project_files/') date_created = models.DateTimeField(auto_now_add=True, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) I've created a CBV view to list all the projects called ProjectList as follow: class ProjectList(ListView): model = Project context_object_name = 'projects' paginate_by = 5 def get_queryset(self): return Project.objects.all().order_by('name') def get_context_data(self, **kwargs): ctx = super(ProjectList, self).get_context_data(**kwargs) ctx['projects_count'] = self.get_queryset().count() ctx['ongoing_count'] = Project.objects.filter(status='Ongoing').count() ctx['ended_count'] = Project.objects.filter(status='Ended').count() return ctx and i added the pagination in template like this: {% if is_paginated %} <nav class="pagination is-centered is-rounded"> {% if page_obj.has_previous %} <a class="pagination-previous" href="?page= {{ page_obj.previous_page_number|stringformat:"d" }}{{ getvars }}{{ hashtag }}"><i class="fa fa-hand-o-left"></i>&nbsp;{% trans "Previous" %}</a> {% else %} <a class="pagination-previous" disabled>{% trans "Previous" %}</a> {% endif %} {% if page_obj.has_next %} <a class="pagination-next" href="?page={{ page_obj.next_page_number|stringformat:"d" }}{{ getvars }}{{ hashtag }}">{% trans "Next" %}&nbsp;<i … -
Django - ListView url not connecting to desired view
I am new to Django and have hit a wall with a certain part of my project and I hope someone can help. I have two ListViews in my views.py file which I would like to work similar to published/draft posts (I'm actually using sanitised and unsanitised reports). Currently, every time I try to access the "Unsanitised" list view (unsanitised_list.html), it just directs me to the the sanitised list view (intelreport_list.html) views.py: class IntelReportListView(ListView): model = IntelReport context_object_name = 'all_logs' def get_queryset(self): return IntelReport.objects.filter(create_date__lte=timezone.now()).order_by('-create_date') class UnsanitisedListView(LoginRequiredMixin, ListView): login_url = '/login/' redirect_field_name = 'intel_db/unsanitised_list.html' model = IntelReport def get_queryset(self): return IntelReport.objects.filter(sanitised__isnull=True).order_by('-create_date') models.py class IntelReport(models.Model): gpms_choices = ( ***REDACTED*** ) gpms = models.CharField(max_length=20, blank=True, null=True, choices=gpms_choices) officer = models.CharField(max_length=50) create_date = models.DateTimeField(auto_now_add=True) sanitised = models.BooleanField(default=False) source_eval_choices = ( ***REDACTED**** ) source_eval = models.CharField(max_length=50, blank=True, null=True, choices=source_eval_choices) intel_eval_choices = ( ***REDACTED*** ) intel_eval = models.CharField(max_length=100, blank=True, null=True, choices=intel_eval_choices) report = models.TextField(max_length=5000, blank=True, null=True) def sanitised_log(self): self.sanitised = True self.save() def get_absolute_url(self): return reverse('log_details', kwargs={'pk':self.pk}) def __str__(self): return str(self.pk) urls.py from django.urls import path from intel_db import views urlpatterns = [ path('welcome/', views.AboutView.as_view(), name='about'), path('logs/', views.IntelReportListView.as_view(), name='log_list'), path('logs/<int:pk>/', views.IntelReportDetailView.as_view(), name='log_detail'), path('logs/new_log/', views.IntelReportCreateView.as_view(), name='new_log'), path('unsanitised/', views.UnsanitisedListView.as_view(), name='unsanitised'), path('logs/<int:pk>/sanitise_log/', views.sanitsed_report, name='sanitised_report'), ] and on my landing … -
How to handle django application having multiple databases in celery
I am using multiple databases in my django application and the database is selected on the basis of url. All the views are working properly and use the database as required. Now, I have an API which exports the data into excel and I am trying to shift main logic of this API to a background tasks using celery. The issue I am facing is that celery is using default database for querying which is not required. So how can I make celery use database based on url. I am using python 3.7, django 2.2.11, django rest framework 3.11.0, celery 4.4.3. Any help would be appreciated. Thanks in advance! -
How to save for a simple model I need to save the User key automatically How to get objects owned by a user? in Django
i have such a model class Summaries(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) father_name = models.CharField(max_length=60, blank=True) myfile = models.FileField(upload_to="document") class Summary_Createes(models.Model): suser = models.ForeignKey(Summaries, on_delete = models.CASCADE) for the active, current user "Summary_Createes" The user who saved this model should only see it for himself how can i filter such data i need filter -
Python Django prevent password reuse
I'm currently trying to prevent users from using their old passwords (configurable, like say last 5 passwords) I have the following Infos: User passwort in cleartext from the form during validation (form.cleaned_data['new_password1']) Their current hashed Password (pwd_before_change) Their last x passwords also hashed (pws) Funnily enough my code works for the current password, but not for my old ones: pwd_before_change = user_to_change.password .... old_pws = Passwords.objects.filter(username=user_to_change).order_by('-password_changed')[:allowed_reuse].values_list('password', flat=True) .... if old_pws: for pws in old_pws: if check_password(form.cleaned_data['new_password1'], pws) or \ check_password(form.cleaned_data['new_password1'], pwd_before_change) messages.error(request, f'You are not allowed a password which was already used in the last ' f'{allowed_reuse + 1} iterations') return render(request, 'registration/password_change.html', { 'form': form }) Any ideas what the issue may be? (additional info, I'm using Argon2). Do I really need to encode the cleartext password again with all possible "salt" in the old passwords and check? (this would make the method depending on the hasher function which would not be ideal + I thought the check passwort function was exactly for scenarios like this?) -
Django trying to add images with forms
I have two models with two different forms. One has a ForeignKey for another model, making a 1-N relationship. The problem is when i try to add images , is not working. The form where i change the (name/TabletForm2) is working so , only when i try to add (image/TabletFormImagem) is not working. The problem is that My model's def get_image(instance, filename): return os.path.join('intervencao/fotografias', str(instance.intervencao), filename) class Intervencao(models.Model): name= models.CharField(verbose_name="Name", max_length=200, blank=True, null=True) class Imagem(models.Model): intervencao = models.ForeignKey(Intervencao, related_name='intervencaoObjectsImagem', on_delete=models.CASCADE) imagem = models.ImageField(upload_to=get_image, blank=True, null=True, verbose_name="Fotografia") def __str__(self, ): return str(self.intervencao) My View def project_detail_chefe(request, pk): form = TabletForm2(request.POST) form2 = TabletFormImagem(request.POST, request.FILES) if request.method == "POST": if form.is_valid(): form.save() return redirect('index') else: form = TabletForm2(request.POST) if form2.is_valid(): //when i print something here to see if the form2 is valid , never enter here. form2.save() return redirect('home') else: form2 = TabletFormImagem() context = { 'form':form, 'form2':form2, } return render(request, 'tablet/info_chefes.html', context) tablet/info_chefes.html <div class="col-md-12"> <div class='form-group'> <label for="{{ form.subject.id_for_label }}" id="titulo">Name:</label> <em>{{ form.name}}</em> </div> </div> <div class="col-md-12"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form2.as_p }} <button type="submit">Upload</button> </form> </div> Forms class TabletForm2(forms.ModelForm): class Meta: model=Intervencao fields = ['data_intervencao_fim','ferramenta'] class TabletFormImagem(forms.ModelForm): class Meta: model=Imagem fields = ['imagem'] -
Include the same Django Admin class to multiple apps
For example, I have 3 apps: app1, app2 and all_apps. First 2 apps are nested in apps and have a lot of models. Now I want to include some admin classes to app1 and app2, and also to all_apps/admin.py (for example some configuration). What I need to do make that admin classes visible in both appX and all_apps? I tried to import it to both, but it appeared only in admin of app where it is located. Is it possible to include the same admin class twice (if it is for 2 different apps)? I know that it requires proxy-class if I need to include it twice to the same app, but what if they are different? -
Could not find path on running the django-private-chat, am I doing something wrong?
Details: django-private-chat version: 0.3.0 Django version: 3.1.2 Python version: 3.8.3 Operating System: Windows 10 I have installed all the requirements in my virtual environment, Django-private-chat is giving this error on running the server: Using the URLconf defined in tests.urls, Django tried these URL patterns, in this order: ^dialogs/(?P<username>[\w.@+-]+)$ [name='dialogs_detail'] ^dialogs/$ [name='dialogs'] The empty path didn't match any of these. Could someone point out what I am doing wrong? -
Failed to start gunicorn daemon, gunicorn.service: Failed to load environment
When i run sudo journalctl -u gunicorn I get: Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: gunicorn.service: Failed to load environment > Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: gunicorn.service: Failed to run 'start' task:> Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: gunicorn.service: Failed with result 'resourc> Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: Failed to start gunicorn daemon. I suppose something doesn’t add up with my directories. I have /etc/systemd/system/gunicorn.service which is: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myname Group=myname EnvironmentFile=/home/myname/myapp/env WorkingDirectory=/home/myname/myapp ExecStart=/home/myname/myapp/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myapp.wsgi:application [Install] WantedBy=multi-user.target The directories I’m working in are as follows. myapp/ has my requirements.txt file, env/, and another app/ dir. Within myapp/app, I have manage.py, an env file that containt my SECRET_KEY which I've exported, and another app/ dir. Within myapp/app/app, I have settings.py and wsgi.py. What am I doing wrong? -
Django. An autocomplete field of a form doesn't work
I faced a problem during developing a search filter for my web-app. I need one field of a filter to be an autocomplete field, but unfortunately it doesn't work as expected. When I type smth in this field it displays nothing although it has to display some options. I use Bootstrap for this field, the class is 'basicAutoComplete', and as you can see in the picture below (please do not pay attention to bad positioning of the fields) there is no information displayed. But if I remove 'basicAutoComplete', all my buildings appears in dropdown list as you can see in the second picture. Can someone tell me how to fix it? class 'basicAutoComplete' no class Here is my code: views.py def device_rooms_search(request): device_rooms = DeviceRooms.objects.all() deviceRoomsFilter = DeviceRoomsFilter(request.GET, queryset=device_rooms) device_rooms = deviceRoomsFilter.qs builds = Buildings.objects.all() context = {'device_rooms_list': device_rooms, 'deviceRoomsFilter': deviceRoomsFilter} return render(request, "database/device_rooms/device_rooms_search.html", context) filters.py class DeviceRoomsFilter(df.FilterSet): name = df.CharFilter(field_name='room_number', lookup_expr='icontains') descr = df.CharFilter(field_name='description', lookup_expr='icontains') class Meta: model = DeviceRooms fields = ['name', 'facility_id', 'building_id', 'device_room_type', 'descr'] models.py class DeviceRooms(models.Model): id = models.CharField(max_length=7, primary_key=True) room_number = models.CharField(max_length=30, unique=True) device_room_type = models.ForeignKey(DeviceRoomTypes, on_delete=models.CASCADE) building_id = models.ForeignKey(Buildings, on_delete=models.CASCADE) facility_id = models.ForeignKey(Facilities, on_delete=models.CASCADE) description = models.CharField(max_length=200, null=True) search.html <form method="get" action=""> {% … -
(Django)Should I use same function for similar kind of function or create different for each
They are somewhat similar like all are comment related function. def someFucntion(request,query): if query == 'func1': # to something... elif query == 'func2': # to something... else: # to something else... -
How to highlight word in Django template from query keyword?
I want to highlight keywords in Django template which are the same keywords getting from the query. The below image illustrates how it highlights the keyword. In this example, the query contains two keywords "plastic" and "automotive" I want Django template to get those query keywords and highlight the same keyword contained in each Description. I guess it may uses {{ request.GET.query }} but I can not figure out any more. Please teach me how to make it. -
How can I count my followers in django template?
Well I have count the my following (people who i follow) but i dont understand how can i count my follower (people who follow me). model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() def __str__(self): return f'{self.user.username}' views.py(profiledetailview) def get_context_data(self, *args, **kwargs): context = super(UserProfileDetailView, self).get_context_data(*args, **kwargs) user = context['user'] '''#Trying with this but it is not working i guess this is wrong way to this but i am not sure!!''' allprofile = UserProfile.objects.all() followers = 0 for u in allprofile.follower: if u == user.userprofile: followers+=1 context['followers']=followers return context (My roughly idea: I was thinking somehow i gain all the profiles and than loop through them to check the particular user profile if there is profile within their follower than add one some follower variable.) You can ignore this if you know other way i have tried my idea but that couldn't work. you guys know them please tell me. -
(Django)How open diffrent templete .html for diffrent category like Mobile, Cars?
I have a category model. I want to open mobile form for mobile category and Cars form for car models -
Ruby has_many :through Association to python django
How to write this in django.There are two class models:users and advertiser_users. has_many :users, through: :advertiser_users -
How to access existing MySQL data table using Django
I am new in Django. I have some data table in MySQL, how can I access and query data from existing table. Thanks. -
Writing a user registration form that doesn't extend UserCreationForm, having trouble with clean() function not executing at all
So as the title says, I have to make my own form to register a user as a learning task. The form works as intended however i want to validate the data that is entered(right now only that pwd1 and pwd2 match). I wrote a clean function but it does nothing and reports no errors. form.py: from django import forms import phonenumbers from phonenumber_field.formfields import PhoneNumberField class RegisterForm(forms.Form): email = forms.EmailField( label='email address', max_length=255) f_name = forms.CharField(max_length=30) country = forms.CharField(max_length=30) mobile = PhoneNumberField(region="IN") address = forms.CharField(max_length=300) pwd1 = forms.CharField(max_length=32, widget=forms.PasswordInput) pwd2 = forms.CharField(max_length=32, widget=forms.PasswordInput) def clean(self): cleaned_data = super().clean() pwd1 = cleaned_data.get("pwd1") pwd2 = cleaned_data.get("pwd2") if pwd1!= pwd2: raise forms.ValidationError("Passwords don't match", code='password_mismatch',) views.py def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] f_name = form.cleaned_data['f_name'] address = form.cleaned_data['address'] country = form.cleaned_data['country'] mobile = form.cleaned_data['mobile'] password = form.cleaned_data['pwd1'] pwd2 = form.cleaned_data['pwd2'] user = User.objects.create( email=email, f_name=f_name, address= address, country= country, mobile= mobile, ) user.set_password(password) user.save() return redirect('/accounts/login/') else: return redirect('failure') else: form = RegisterForm return render(request, 'register.html', {'form':form}) return redirect('/register/') register.html <!DOCTYPE = 'html'> <html> {% load static %} <link rel="stylesheet" href="{% static 'accounts/file.css' %}"> <head> <div class="header"> <a href="/" class="logo">task1</a> <div class="header-right"> <a href="/">Home</a> … -
How to pass an object to celery in django request?
Here i initialize an object which can't be serialized in django view. I want to share this object among different requests and celery. Among requests i share the object with middleware. But I get problem when passing this object to celery. I have tried singleton. In middleware, I instantiate the singleton and assign value (a dict of {uuid:object} ) to member of it from request. But when i get the singleton in celery task, I got empty dict. How can i get the dict in celery? -
Django admin view design error/acting funny
Anyone faced this before? I have never. I installed Django 3.1 along with Python 3.9 and started facing this(see the image). Even when I scroll up, the top half stays there, its fixed, only the bottom half scrolls. I am using ckeditor for the body field in my app. Could that package be the reason? -
Dynamically removing a form from Django formset with Ajax
I would like to remove form dynamically when I press remove link. I have tried this solution but the problem with this solution is that it only removes form from html, it does not remove form from formset. So, I tried to alter from this solution and from this blog. Here is my progress: <form class="form-horizontal" method="POST" action=""> {% csrf_token %} <h3>Ingredients</h3> {{ formset.management_form }} <div class="form-list"> {% for form in formset.forms %} <div class='table'> <a class="remove-form" href="#">remove</a> <table class='no_error'> {{ form.as_table }} </table> </div> {% endfor %} </div> <input type="button" value="Add More" id="add_more"> <div class="row spacer"> <div class="col-4 offset-2"> <button type="submit" class="btn btn-block btn-primary">Create</button> </div> </div> </form> <script> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function cloneMore(selector, type) { var newElement = $(selector).clone(true); var total = $('#id_' + type + '-TOTAL_FORMS').val(); newElement.find(':input').each(function() { var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' … -
ImportError: cannot import name 'ProductDetails' from 'pages.views'
I have written test case for views for details page. Here is below code I have written, When I am runing pytest in terminal i t raising these error. My project structure is as below vikreya mysite .cache .idea .pytest_cache logs media mysute init.py manage.py settings.py urls.py wsgi.py pages .cache migrations static templates tests test_views.py init.py admin.py apps.py cron.py Forms.py functions.py models.py urls.py views.py ``` from django.test import RequestFactory from django.urls import reverse from django.contrib.auth.models import User from pages.models import vk_customer from mixer.backend.django import mixer import pytest from pages.views import ProductDetails @pytest.mark.django_db class TestViews: def test_product_detail_authenticated(self): mixer.blend('pages.vk_master_table') path = reverse('detail', kwargs={'pk': 1516}) request = RequestFactory().get(path) request.user = mixer.blend(vk_customer) response = ProductDetails(request, pk=1516) print(response) assert response.status_code == 200 ``` This the error i am getting..... ____________________________________________________________ ERROR collecting pages/tests/test_views.py ____________________________________________________________ ImportError while importing test module 'H:\vikreya\mysite\pages\tests\test_views.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: c:\users\user\appdata\local\programs\python\python38\lib\importlib\__init__.py:127: in import_module return _bootstrap._gcd_import(name[level:], package, level) pages\tests\test_views.py:8: in <module> from pages.views import ProductDetails E ImportError: cannot import name 'ProductDetails' from 'pages.views' (H:\vikreya\mysite\pages\views.py) Please help me out to solve this error, Thank you, ~Salima