Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django profile not being updated
Enabling my users to update their profile information. However, when I send new profile information, Django sends my back the profile information I had prior to updating. Simply put I would to receive updated profile information when I update a user profile along with a new access_token (I use the information to populate my profile). This is my serializers.py: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}} def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): user = self.context['request'].user if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] instance.save() return instance urls.py: path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile'), and my views.py: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer @action(detail=True, methods=['PUT']) def perform_update(self, serializer, pk=None): serializer.save(user=self.request.user.id) -
PAGINATION using class APIView in Django Rest Framework
I have try to paginate my data.. but this is not work , I'm still getting all data from DataBase this is views.py : class User_apiView(APIView): pagination_class=PageNumberPagination def get(self, request): user = User.objects.all() # pagination_class=PageNumberPagination serializer = TripSerializer(user, many = True) return Response(serializer.data) this is settings.py : REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, } this the data I recieve in this url http://127.0.0.1:8000/api/users/?PAGE=4&PAGE_SIZE=1 HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, ] -
How i can ouput categiries in django on dpopdown in navbar?
Views, functions from categories def get_categories(request, cat_id): product = Product.objects.filter(cat_id=cat_id) cats = Category.objects.all() if len(product) == 0: raise Http404() context = { 'product': product, 'cats': cats, 'menu': menu, 'title': 'Отображение по категориям', 'cat_selected': cat_id, } return render(request, 'task1/get_category.html', context=context) Models with get_absolute_url class Category(models.Model): name = models.CharField(max_length=255, verbose_name='Категории') slug = models.SlugField(max_length=255, unique=True, verbose_name='URL', db_index=True) class Meta: verbose_name = 'Категории' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('сategory', kwargs={'cat_id': self.pk}) Urls.py path('category/', get_categories, name='category'), This is piece of code from base.html. Dpodown from navbar. <div class="collapse navbar-collapse" id="navbarNavDarkDropdown"> {% for c in cats %} <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Категории </a> <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink"> <li><a class="dropdown-item" href="#">{{ c.name }}</a></li> {% else %} <li><a class="dropdown-item" href="#">{{ c.name }}</a></li> </ul> {% endif %} </li> </ul> {% endfor %} </div> I'm really idk what to do, help me please I've tried, but i get mistake Navbar looks like, i have 4 categories and i get 4 columns in navbar -
How to make Whitelisted IPs won't be blocked and other IPs should be blocked if crosses the certain time in django rate limited?
@method_decorator(ratelimit(key='ip', rate='10/m', block=True), name="process_request") Class SomeMiddleware (object): def process_request(request): Pass I have ALLOWED_IPS = ["SOME IP"] in settings.py and i imported here. If any IPs matching with this list, they won't be blocked under this condition otherwise it does. How can I achieve this? -
Get username of authenticated user in middleware [Djoser] Django
Im using django with rest framework and djoser. I have a code to check the latest activity on the website. But i have problem to get username of authenticated user. request.user.is_authenticated always return false. On frontend i have vue. p.s When i login to admin panel of 127.0.0.1:8000 show "true" from django.utils import timezone from .models import CustomUser class UpdateLastActivityMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') print(CustomUser.objects.filter(is_online=True)) print(request.user.is_authenticated) if request.user.is_authenticated: CustomUser.objects.filter(user__id=request.user.id) \ .update(last_online_at=timezone.now()) -
django-social-auth redirect to different url based on params
I am using social-auth-app-django to enable OAuth2 from google. My application has two types of users and both are given an option to use google auth. Now after these users register using google, I want to redirect to some page where they add additional information based on the type of user. I am not able to figure out a way how to identify them based on the type of user. I am looking for a way where I can send extra parameter to google and then google return that parameter. This way I can identify the user type. I am simply providing the following in django template. <a href="{% url "social:begin" "google-oauth2" %}"><button>Google</button></a> Edit: One way I am thinking is of having two redirect URL configured in google. Then I can simply add function for these two redirect URL and my problem will be solved. I am not able to figure out how to add that redirect URL in the request to google. -
"Cannot call delete() after .distinct()" error after django update
I am using djangocms_blog. Today I updated django from 3.1 to 3.2.12 and suddenly when I try to delete post object, there is "Cannot call delete() after .distinct()" error Traceback: env\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … env\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … env\lib\site-packages\django\contrib\admin\options.py, line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) … env\lib\site-packages\django\utils\decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … env\lib\site-packages\django\views\decorators\cache.py, line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) … env\lib\site-packages\django\contrib\admin\sites.py, line 232, in inner return view(request, *args, **kwargs) … env\lib\site-packages\django\utils\decorators.py, line 43, in _wrapper return bound_method(*args, **kwargs) … env\lib\site-packages\django\utils\decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … env\lib\site-packages\django\contrib\admin\options.py, line 1739, in changelist_view response = self.response_action(request, queryset=cl.get_queryset(request)) … env\lib\site-packages\django\contrib\admin\options.py, line 1408, in response_action response = func(self, request, queryset) … env\lib\site-packages\django\contrib\admin\actions.py, line 45, in delete_selected modeladmin.delete_queryset(request, queryset) … env\lib\site-packages\django\contrib\admin\options.py, line 1109, in delete_queryset queryset.delete() … env\lib\site-packages\django\db\models\query.py, line 728, in delete raise TypeError('Cannot call delete() after .distinct().') … I restored Django 3.1 version and everything works fine, but working on old version isn't best solution -
How to make Django username field of LoginView(FormView) lowercase?
I've made it so that any user that signs up with a username will automatically have their username converted to lowercase. user/forms.py I now have the issue where I can't figure a way to convert the username in the login form to become lower when submitted. As I would still like the user to be able to enter their name in the case of their choice. I've tried the python tolower() function on a few things in the LoginView, yet unsuccessful. If anyone has an idea on how I could achieve this please let me know. Here is the user/forms.py class UserSignupForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] def clean_username(self): username = self.cleaned_data["username"].lower() if not re.match(r"^[A-Za-z0-9_]+$", username): raise forms.ValidationError( "Sorry , you can only have alphanumeric, _ or - in username" ) else: return username Here is the user/urls.py path("signup/", user_view.signup, name="signup"), path("login/",auth_view.LoginView.as_view(template_name="user/login.html"),name="login"), -
Form action is not calling the required function from views.py in Django
I am new in Django and doing my first project in it. I had made a form in my index.html file and that form took an image, and sent it to a predictImage function in views.py file. The predictImage function applied YOLO model on the image and returned the image with labels to the same index.html page. This was working fine and I was getting the required results. After the submit button was clicked, I was getting redirected to index.html/predictImage where the results were being shown. (I had conditions added in my index.html to show the results) Then, I decided to add a Users Model and made a Login page for me, user was required to login before he could upload the image. For this, I added sessions as well. Now, I created a Photo model, to store every photo that every user uploads. All of this was successfully made but now, when I tried to do the same thing again, i.e., upload the image and submit it, it didn't work and it instead redirected me to index.html I tried to debug this, and I found out that I was not even going to views.predictImage when I clicked the submit … -
What is the easiest way to create a histogram (with target line) in Chart.js?
I have a matplotlib code that seems to do what I want it to do. I am trying to use it in a django web app. For example: home_totals_dict[a] = [ 140, 130, 120, ...] a = team_name plt.figure() plt.hist(x=home_totals_dict[a], bins='auto', color='#0504aa',alpha=0.7, rwidth=0.5) plt.hist(x=away_totals_dict[b], bins='auto', color='#d62728',alpha=0.7, rwidth=0.5) plt.axvline(x = c, color = "k",linestyle = "--" ) plt.xlabel(a + "/ "+ b) The result is the image attached. Every time I try do something similar in chart.js the x axis gets all messed up and am having trouble normalizing the x-axis prior to adding the data to chart.js -
Serializer returns media files URLs in http not in https in Django Rest Framework
I'm trying to serialize a model and one of its fields is a FileField when calling serialiser.data it returns the URL of the FileField in an HTTP schema, not an HTTPS. I get { "id": 1, "name": "demo", "file": "http://domain-name.com/media/image.png" } I want it to be { "id": 1, "name": "demo", "file": "https://domain-name.com/media/image.png" } I'm using Nginx and set proxy_set_header X-Forwarded-Proto https; Then in your Django settings added the following: USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') And the problem is not fixed, what should I do to solve it? -
send_mail (smtp) from docker-compose (django + nginx + gunicorn)
I am trying to send email via Django. The mail should be sent to the user who would register to our system using Gmail. I am also using docker-compse django, nginx, gunicorn and postgres. This is my email configurations inside the django. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = get_secret("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = get_secret("EMAIL_HOST_PASSWORD") DEFAULT_FROM_EMAIL = EMAIL_HOST_USER and docker-compose version: '3.7' services: web: build: context: ./dj-psych dockerfile: Dockerfile.prod command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/static/ - media_volume:/home/app/web/media/ expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:13.0 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/static - media_volume:/home/app/static ports: - server-port:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: nginx.conf upstream config { server web:8000; } server { listen 80; location / { proxy_pass http://config; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/static/; } location /media/ { alias /home/app/media/; } } I think the smtp server port (586) should be open in docker. So I tried binding port web and nginx. But I can't. how can i do it?? I tried. from django.core.mail import EmailMessage email = EmailMessage('subject', 'body', to=['yj.jeon.gn@gmail.com']) email.send() This is … -
Django: Cannot filter against a non-conditional expression during trying to relate every values written to the current user
I want to relate every values written to the current user ,( the story that i want to print some fields of a form) and am afraid in case more than 1 user logged in the same time and want to generate a pdf, both of them print the same last -values entered in the printout. So i want to filter the values of fields based on the current user logged in with session. First Step: I have add another class in models.py models.py class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.ForeignKey(Session, on_delete=models.CASCADE) Second Step: in views.py:(the function that is responsible for generating the pdf) , I have coded like that: def forms_render_pdf_view(request, *args, **kwargs): template_path = 'pdf.html' user = request.user user_sessions = UserSession.objects.filter(user = user) field_name = 'emploi' obj_m = Loads.objects.filter(user_sessions).last() field_obj_m = Loads._meta.get_field(field_name) field_value_m = field_obj_m.value_from_object(obj_m) emploi = str(field_value_m) when i try to generate my printout it gives me: Cannot filter against a non-conditional expression. Thanks in advance, How i can relate every values written to the current user correcly . -
Adding an object to ManyToMany field doesn't work
I have 2 models: class User(AbstractUser): pass class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() likes = models.IntegerField(default=0) likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts') Post model has a manytomany field to User model. I try to add a user object to the field with the view function below but it doesn't work. When I check the post in the admin page, the user is not added to the likers. @csrf_exempt def likepost(request, like, post_id): if (request.method == 'PUT'): post = Post.objects.get(pk=post_id) if like: post.likers.add(request.user) else: post.likers.remove(request.user) post.save() print(post.likers) return HttpResponse(status=204) else: return JsonResponse({ 'error': 'PUT request required.' }, status=400) I make the request in javascript in this way: fetch(`likepost/${likeValue}/${postId}`, { method: 'PUT' }); -
Python Django django-admin startproject admin problem
I am facing problem when I start making project via Django.....Whenever I cammand in CMD "django-admin startproject clone" It request for USER/ADMIN--- and I forget...That thing please that what to do try to help me...whenever I try to give something in input field it show me an error... After 1year I am switching in Django...It soo me some file which was on my Desktop that time...Please try to Help me...... [Output[\]\[1\]][1] --Shadab -
Basename attribute in the same routes
relatively speaking, I have two simple models: Processor and Motherboard. class Processor(Product): supply_type = models.CharField(max_length=10) socket = models.CharField(max_length=20) cores_amount = models.IntegerField() threads_amount = models.IntegerField() technological_process = models.IntegerField() class Motherboard(Product): socket = models.CharField(max_length=20) ram_generation = models.CharField(max_length=10) ram_type = models.CharField(max_length=10) ram_slots_amount = models.IntegerField() There are also corresponding serializers written for them. class ProcessorSerializer(ModelSerializer): class Meta: model = Processor fields = '__all__' class MotherboardSerializer(ModelSerializer): class Meta: model = Motherboard fields = '__all__' And of course viewsets. class ProcessorViewSet(ModelViewSet): queryset = Processor.objects.filter(is_published=True) serializer_class = ProcessorSerializer lookup_field = 'slug' class MotherboardViewSet(ModelViewSet): queryset = Motherboard.objects.filter(is_published=True) serializer_class = MotherboardSerializer lookup_field = 'slug' SimpleRouter was created in urls, where the following routes were added. router = routers.SimpleRouter() router.register(r'processors', ProcessorViewSet) router.register(r'motherboards', MotherboardSerializer) When I try to make a migration I get the following error: router.register(r'motherboards', MotherboardSerializer) assert queryset is not None, 'basename argument not specified, and could ' AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. I tried to add this attribute, however, an error appears that the get_extra_actions method is not defined. I have three old models added in the same way. The problem appeared precisely when adding new models and routes for … -
Weasyprint how fix html/css that come from email
Weasyprint generate pdfs from emails. Sometimes emails come with some html/css in it. I add example from pdf from paypal in which all pdf in html/css information. Or Microsoft default mail also use some html when send emails. Is it possible to add some default things to fix html/css in a right way? My code: filename = f'{uuid.uuid4()}.pdf' data = {"body": content} context = Context(data) template = Template('{{ body|linebreaks|safe }}') html_string = template.render(context) html = HTML(string=html_string) pdf = html.write_pdf() Some example from paypal email that come <html dir="ltr"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="initial-scale=1.0,minimum- scale=1.0,maximum-scale=1.0,width=device-width,height=device- height,target-densitydpi=device-dpi,user-scalable=no" /> <title>Confirm your new email address</title> <style type="text/css"> /** * PayPal Fonts */ @font-face { font-family: PayPal-Sans; font-style: normal; font-weight: 400; src: local('PayPalSansSmall-Regular'), url('https://www.paypalobjects.com/ui- web/paypal-sans-small/1-0-0/PayPalSansSmall-Regular.eot'); /* IE9 Compat Modes */ src: local('PayPalSansSmall-Regular'), url('https://www.paypalobjects.com/ui-web/paypal-sans-small/1-0-0/ PayPalSansSmall-Regular.woff2') format('woff2'), /* Moderner Browsers */ url('https://www.paypalobjects.com/ui-web/paypal-sans-small/1-0-0/ PayPalSansSmall-Regular.woff') format('woff'), /* Modern Browsers */ url('https://www.paypalobjects.com/ui-web/paypal-sans-small/1-0-0/ PayPalSansSmall-Regular.svg#69ac2c9fc1e0803e59e06e93859bed03') format('svg'); /* Legacy iOS */ /* Fallback font for - MS Outlook older versions (2007,13, 16)*/ mso-font-alt: 'Calibri'; } -
how can i use audio file in pydub through django
Well, i have a code that creates and saves audio and i need to instert in that code a silence cutting system views.py def audio(request): if request.method == 'POST': cu = request.user.customer.pk users = get_object_or_404(Customer, pk=cu) js = get_object_or_404(JsonMap, user_id=users.id) audio = request.FILES['data'] name = audio.name name = name.replace(':', '-') song = Song.objects.create() audio_cut_logic = SoundCutter() song.js = js song.name = name song.audio_file = audio song.save() return render(request, 'action.html', {'file_url': js}) models.py def remove_sil(self, file, format="wav"): sound = AudioSegment.from_file(file, format=format) non_sil_times = detect_nonsilent(sound, min_silence_len=50, silence_thresh=sound.dBFS * 1.5) if len(non_sil_times) > 0: non_sil_times_concat = [non_sil_times[0]] if len(non_sil_times) > 1: for t in non_sil_times[1:]: if t[0] - non_sil_times_concat[-1][-1] < 200: non_sil_times_concat[-1][-1] = t[1] else: non_sil_times_concat.append(t) non_sil_times = [t for t in non_sil_times_concat if t[1] - t[0] > 350] return sound[non_sil_times[0][0]: non_sil_times[-1][1]] i tried to create sound.audio_file through my function song.audio_file = audio_cut_logic.remove_sil(audio) then i tought i need to create that audio file firstly and then use my func song.audio_file = audio song.audio_file = audio_cut_logic.remove_sil(song.audiofile) but all i got is: AttributeError: 'AudioSegment' object has no attribute '_committed' -
How to Give List of Objects IDs and add a click event based on each List IDs in Django
Here in my Django code, I have a list of prices. Now I gave them unique IDs which works well, but when I try to add a click event, the click event only works for only one list item continuously. {% for price in logistic_branch_pricing %} <h1 id="select-delivery-location-{{price.id}}" onclick="calculateDeliveryPrice()">{{ price.id }}-{{price.small_kg_price}} </h1> {% endfor %} {% for price in logistic_branch_pricing %} <script> function calculateDeliveryPrice() { var omo = document.getElementById("select-delivery-location-{{ price.id }}") omo.classList.add('d-none') console.log(omo) } </script> {% endfor %} -
How do I view the profile of the authenticated user in Django Rest Framework using the Token
I am learning DRF and creating a simple DRF app that lets user login, and view the profile and update the profile. I am using Django's default User model and using Knox for Token Authentication (if it can be done easier using Django Rest Authentication, please let me know and also tell me the procedure). I have successfully created the API to register and login the user which works fine, but I am stuck at showing the profile to the Authenticated User through a Token. I am only one Model that is Details which acts as to store the Profile details of the user. I have LoginSerializer which is connected to Login API and MainUserSerializer & UserSerializer, both of which are connected to User API (which acts to show the Profile details on frontend). I have tried a lot, searched everywhere, but all they show is how to authenticate the user with token through a url (some thing like using curl https://localhost:8000/api/user... etc.), postman, somehing like http post -a... command in terminal and other ways, but I don't want to test or implement using these ways. I want something that if I open my user profile url after logging in … -
Django list DB entries if LDAP group and key parameter match
Having hard time to figure out mechanism for my django app. I have tabele in db with list of Agents and every agent has assigned specific name of LDAP group in this table. Now i need to somehow compare LDAP group of logged user this LDAP value from agent table and list only those agents which matches LDAP group. I know how to get LDAP group of user. Just need to figure out how to match this value with list of agents and list them. End effect: User logging in and can list agents only which matches his LDAP group. -
Add object to ManyToMany field doesn't work
I have 2 models: class User(AbstractUser): pass class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() likes = models.IntegerField(default=0) likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts') Post has a manytomany field to User model. I try to a user object to the field with the view function below but it doesn't work: @csrf_exempt def likepost(request, like, post_id): if (request.method == 'PUT'): post = Post.objects.get(pk=post_id) if like: post.likers.add(request.user) else: post.likers.remove(request.user) post.save() print(post.likers) return HttpResponse(status=204) else: return JsonResponse({ 'error': 'PUT request required.' }, status=400) -
How to do Total Sum from JS in Django
let x = document.getElementById("food_price"); console.log(x); I want to get total of food items from js, but i could not get the solution, can anyone help me. -
How can I read csv files from the link stored in django model within views file?
I am creating a map with Folium, Django and Pandas. I created a django model where I store my csv file's url. I want to read csv files from there dynamically so that I can use different data dynamically. How can I do that? I used a url of a csv file. I want to make it dynamic so that I can fetch one from models directly. Here is my code. I will be very grateful for your assistance. def mapview(request, map_pk): srlist = Map.objects.filter(pk=map_pk) bd = pd.read_csv("https://docs.google.com/spreadsheets/d/1IohEgJi8ajDoHyPF315vi13F3m0vDtbl7DzmSmtUHpA/gviz/tq?tqx=out:csv") df = pd.DataFrame(bd) lat = df[['lat']] lng = df[['lng']] m = folium.Map(title='Bangladesh', location=[23.7805733, 90.2792399], zoom_start=7) for i, row in df.iterrows(): folium.Marker(location=[row['lat'], row['lng']]).add_to(m) m = m._repr_html_() context = { 'm':m, 'bd':bd, 'lat': lat, 'lng': lng, 'srlist':srlist, 'df':df, } return render(request, 'map/mapview.html', context) -
one django project two apps, problem with generic views( class view)
i have two apps in one project: store and basket. In urls.py in core of project: urlpatterns = [ path('admin/', admin.site.urls), path('', include('jewelry_store.urls', namespace='jewelry_store')), path('basket/', include('basket.urls', namespace='basket')), ] in urls.py in basket app : from django.urls import path from basket import views app_name = 'basket' urlpatterns = [ path('', views.BasketSummary.as_view(), name='basket_summary') ] in urls.py in jewelry_store app : from django.urls import path from jewelry_store.models import Category from . import views app_name = 'jewelry_store' urlpatterns = [ path('', views.AllListView.as_view(), name='all_products'), path('<slug:slug>', views.ProductView.as_view(), name='product_detail'), path('category/<slug:slug>/', views.CategoryView.as_view(), name='all_categories'), path('collection/<slug:slug>/', views.CollectionView.as_view(), name='all_collections'), ] i wold like to have class based view in views.py, like this : from msilib.schema import ListView from django.shortcuts import render import basket from jewelry_store.models import Product # Create your here. class BasketSummary(ListView): model = Product template_name = "jewelry_store/basket/summary.html" but it generate error like this when it is done in functions mode everything is correct. What is proper configuration for class views ?