Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ERR_EMPTY_RESPONSE
I am currently running a Django site on ec2. The site sends a csv back to the client. The CSV is of varying sizes. If it is small the site works fine and client is able to download the file. However, if the file gets large, I get an ERR_EMPTY_RESPONSE. I am guessing this is because the connection is aborting without giving adequate time for the process to run fully. Is there a way to increase this time span? -
Non-social Provider with Django
Is there a 3rd party package to handle authentication for Django via OAuth? I've looked into OAuth Toolkit but it only seems to be a provider that provision tokens. I'm looking for something that can consume an existing provider much like All Auth does with Google, Facebook, etc. The problem is that I want to integrate with a private provider, not a popular social provider as mentioned above. Is there any package that could do this or do I have to write the OAuth flow entirely by myself? -
Configurations of Django application deployed on DigitalOcean
I have a little trouble such as: I've created a Django application and deployed it on DigitalOcean via Nginx, Unicorn. Everything works very well with an IP address. But now I've bought a domain address and set it to my application. After this trouble has come. I can't open my admin dashboard on my computer, application is not opening on my phone, but opens on friend's phone, and so on. I just want to know, are my configurations right for replacing IP address with domain name ? settings.py: ALLOWED_HOSTS = ['134.209.39.229','challengers.az'] nginx: server { listen 80; server_name challengers.az; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/project; } location / { include proxy_params; proxy_pass http://unix:/home/username/myproject.sock; } } -
Python:3.7-alpine [AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' ]
Minimal reproduce: FROM python:3.7-alpine [DockerFile] https://gist.github.com/andresfabianguerrero/9474203eeb27cee8fa2a5285a4e10dae Output -
Django Authentication not working on deployed heroku app when using abstractBaseUser
So I have added some new fields to the Django user profile by subclassing AbstractBaseUser like this: from __future__ import unicode_literals from datetime import timedelta from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.conf import settings from django_countries.fields import CountryField from .managers import CustomUserManager BOOLEAN_YN = ( (True, u'Yes'), (False, u'No'), ) class UserProfile(AbstractUser): full_name = models.CharField(_("fullname"),max_length=100,blank=True,null=True) timezone = models.CharField(_("time zone"), max_length=32, default='UTC',null=True,blank=True) is_active = models.BooleanField(_("activated"),default=False) is_verified = models.BooleanField( _('verified'), default=False, help_text=_( 'Designates whether the user has verified his ' 'account by email or by other means. Un-select this ' 'to let the user activate his account.')) position = models.CharField(max_length=100,null=True,blank=True) institution = models.CharField(max_length=100, null=True, blank=True) resident_country = CountryField(null=True, blank=True) home_country = CountryField(null=True, blank=True) introduction = models.TextField(max_length=1500,blank=True,null=True) gdpr = models.BooleanField(default=True,choices=BOOLEAN_YN) email_contact = models.BooleanField(default=True,choices=BOOLEAN_YN) REQUIRED_FIELDS = ['email'] objects = CustomUserManager() def __str__(self): return self.first_name + ' ' + self.last_name class Meta: verbose_name = _("User profile") verbose_name_plural = _("user profiles") def save(self, *args, **kwargs): if self.is_superuser: self.is_administrator = True self.full_name = self.first_name + ' ' + self.last_name super(UserProfile, self).save(*args, **kwargs) Obviously, this led to issues with the: python manage.py createsuperuser not creating superusers. I created the CustomUserManager in managers.py like this: from … -
Error handling media images in tamplate tagging Django Python
I feel I am overlooking something small, but I am trying to use template tagging display uploaded media files for clothing items: settings.py MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' MEDIA_ROOT = [ MEDIA_DIR, ] models.py class Uniform(models.Model): category = models.CharField(choices = CATEGORY_CHOICES, max_length=11) description = models.CharField(max_length = 50) price = models.FloatField(max_length = 6) size = models.CharField(choices=CLOTHES_SIZE, max_length=4, blank=True) style = models.CharField(choices=STYLE_CHOICES, max_length=15, blank=True) image = models.ImageField(upload_to='uniforms/') html <div class="row wow fadeIn"> {% for item in uniform %} <div class="col-lg-3 col-md-6 mb-4"> <div class="card"> <div class="view overlay"> <img src="{{ item.image.url }}" alt="Oh no!"> <a> <div class="mask rgba-white-slight"></div> </a> </div> <div class="card-body text-center"> <label> <h5>{{ item.description }}</h5> </label> <h5> {% if item.description %} <strong> <label for="">{{ item.category }}</label> </strong> </h5> {% endif %} </div> </div> </div> {% endfor %} Even inspecting the page I get the following: The path all looks right to me, even the settings.py set up and uploaded image object path of my Uniform model. Am I missing something? I have looked at some other posts and saw a reccomendation in the urls.py to include: from django.conf.urls.static import static urlpatterns = [ ... ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Still no luck -
How can I select another field instead __str__ method of the model in ForeignKey?
In my models I want to select another field of model instead str method of model. I used to_field but is not working, are there other ways to accomplish that? My models class Porumbei(models.Model): ... id_porumbel = models.AutoField(primary_key=True) data_adaugare = models.DateTimeField(default=timezone.now, null=True, blank=True) crescator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, blank=True, related_name='porumbeii') serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True, help_text="Seria de pe inel. Ex: RO 123456") anul = models.CharField(max_length=4, null=False, blank=False) culoare = models.ForeignKey(CuloriPorumbei, on_delete=models.CASCADE, null=False, blank=False, ) culoare_ochi = models.ForeignKey(CuloriOchi, on_delete=models.CASCADE, null=False, blank=False, ) sex = models.CharField(max_length=6, choices=SEXE) ecloziune = models.DateField(null=True, blank=True) rasa = models.CharField(max_length=50, null=True, blank=True) linie = models.CharField(max_length=50, null=True, blank=True) nume = models.CharField(max_length=50, null=True, blank=True) tata = models.ForeignKey('Perechi', to_field='mascul', on_delete=models.CASCADE, related_name="porumbei_masculi", null=True, blank=True) mama = models.ForeignKey('Perechi', to_field='femela', on_delete=models.CASCADE, related_name="porumbei_femele", null=True, blank=True) def __str__(self): return self.serie_inel class Perechi(models.Model): boxa = models.PositiveIntegerField(primary_key=True, unique=True) sezon = models.CharField(max_length=4, null=False, blank=False, default=datetime.now().year) mascul = models.ForeignKey(Porumbei, unique=True, on_delete=models.CASCADE, limit_choices_to=Q(sex="Mascul"), related_name="perechi_masculi") femela = models.ForeignKey(Porumbei, unique=True, on_delete=models.CASCADE, limit_choices_to=Q(sex="Femelă"), related_name="perechi_femele") def __str__(self): return self.boxa I want that when add a new Porumbei in tata field to select perechi.mascul instead perechi.boxa. Same with mama field on Porumbei. How could I do that? Thanks in advance! -
only vaildation in Django Rest Framework
Can I use Serializer just for validation purpose? for example if I had CommentSerializer as from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() Is it as as per motive of DRF to use this serializer just for validation of request? For example: from rest_framework.views import APIView from rest_framework.response import Response class MyAPIView(APIView): def post(self, request, format=None): serializer = CommentSerializer(data=dict(request.data)) serializer.is_valid() return Response(serializer.data) or am I fighting against the framework guidance? -
JS code creating issue in Django project ("introduce local variable")
I am running in a ridiculous problem with django. the same code it works here and in VScode (only these 3 files). but when i implement the sets of codes in the django project in pycharm or vscode, the js code, does not respond in a right right, it shows there that i have to "introduce local variable. What is wrong? :( $(document).ready(function() { $(".carousel").carousel(); }); .carousel { height: 250px; perspective:175px; } .carousel .carousel-item { width: 250px; } .carousel .carousel-item img { width: 100%; border-radius: 10px 10px 0 0; } .carousel .carousel-item h2 { margin: -5px 0 0; background: #fff; color: #000; box-sizing: border-box; padding: 10px 5px; font-weight: bold; font-size: 3em; text-align: center; } <html lang=""> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"/> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <link rel="stylesheet" href="/Main/static/blog/imageslider.css" /> <script src="/Main/static/functionality/imageslider.js"></script> <title></title> </head> <body> <div class="carousel"> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt="" /> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""/> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""/> <h2>3D CAROUSEL</h2> </a> </div> </body> </html> -
Django customized chat
pythoneers! :) INTRO: I am new to the python world, so I am gonna ask a question about a chat application using django, because I do not want to build a program from scratch when there MAY BE free source code to use. QUESTION/PROBLEM: I need to build a user to user messenger where the messages must be saved into database, BUT the messages should not be received directly, rather after the superuser approves the messages.THE REASON is that the superuser (owner of the website) does not want that the two parts share their contacts with each other. Is there anything available ready in the django world? I mean what are the suggestions to solve the task? Thanks in advance! -
How to integrate Razorpay in django
I want to integrate Razorpay in Django in the simplest way but i have no idea about third-party integrations. Any idea with sample code example will be helpful, thank you.I have not made any model for it yet. -
parallel tests on Mac OS X Catalina crash with Postgres
After upgrading to Mac OS X Catalina my parallel django tests cash. With this in settings I get a crash, without them (when sqlite is used everything is fine) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xx', 'USER': 'xx', 'PASSWORD': 'xx', 'HOST': '127.0.0.1', 'PORT': '5432', } } Execution command is: python manage.py test --settings=app.settings.test --parallel The crash report contains this: Process: Python [30650] Path: /usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: 3.7.5 (3.7.5) Code Type: X86-64 (Native) Parent Process: Python [30634] Responsible: Terminal [1592] User ID: 501 Date/Time: 2019-12-15 10:04:41.315 -0800 OS Version: Mac OS X 10.15.2 (19C57) Report Version: 12 Bridge OS Version: 4.2 (17P2551) Anonymous UUID: 9B583AD7-1D7E-AA15-3286-DADFF9B92A49 Sleep/Wake UUID: 41900DFA-568F-4B5B-BFA4-0C5FF8D8C05F Time Awake Since Boot: 54000 seconds Time Since Wake: 2000 seconds System Integrity Protection: enabled Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x000000011554baba Exception Note: EXC_CORPSE_NOTIFY Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: exc handler [30650] VM Regions Near 0x11554baba: VM_ALLOCATE 000000011550b000-000000011554b000 [ 256K] rw-/rwx SM=COW --> shared memory 000000011558b000-000000011558f000 [ 16K] r--/r-- SM=SHM Application Specific Information: *** multi-threaded process forked *** crashed on child side of fork pre-exec Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libsystem_trace.dylib … -
Django web application handling post requests
I am new to Django and am confused on handling post requests to my server. I want to accept post requests in this json format: {“username”:”john@doe.com”,”password”:”pass@word1”} and to reply with these json formated responses: {“status”:”success”,”message”:”user_authed”} if the user and password combination is found {“status”:”failure”,”message”:”user_not_found”} if the user and password combination is not found This is my views.py code from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . models import users from . serializers import userSerializer class userList(APIView): def get(self, request): user = users.objects.all() serializer = userSerializer(user, many=True) return Response(serializer.data) def post(self, request): serializer = userSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I want to know how I can format the post function to accept requests in the format above and how to customize the reply as authenticated or not. Any help would be appreciated with this -
CBV pass CBV form with validation
I'm new to django. I'm building a CRUD app using Class-based views as follow: views.py class CreateInterventionView(CreateView): form_class = NewIntervention success_url = reverse_lazy('list') template_name = 'intervention_create.html' def form_valid(self, form): form.instance.speaker = self.request.user return super().form_valid(form) class UpdateInterventionView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Intervention form_class = NewIntervention success_url = reverse_lazy('list') template_name = 'intervention_update.html' def form_valid(self, form): form.instance.speaker = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.speaker: return True return False class DeleteInterventionView(DeleteView): model = Intervention template_name = 'intervention_delete.html' context_object = 'intervention' success_url = reverse_lazy('list') I also have a CBV ListView and i want the user to be able to create/update/delete interventions in same page as ListView (i have buttons for crud operations and when the user click on it it open a materializecss modal with the form) i tried this: class ListInterventionView(ListView): model = Intervention template_name = 'intervention_list.html' ordering = '' paginate_by = 5 def get_queryset(self): return Intervention.objects.filter(speaker=self.request.user) def get_context_data(self, **kwargs): context = super(ListInterventionView, self).get_context_data(**kwargs) context['form'] = CreateInterventionView.form_class return context The modal is working and i have my form inside it but when i create new intervention it's not working and i don't know how to do the validation in my listview. Any advice is welcome. Thanks a lot. … -
Is there a way to documenting a class based view displaying different docstrings in every function in the DRF API view?
I have a Class Based View API with differents default and custom endpoints, also I have different docstring in every endpoint, but when I load my DRF API view in an specific endpoint (not the main), it doesn't display the docstring, what is just exactly happen in the swagger doc. I explain details below: This is one of my main Class (api.py): class CustomDictionaryViewSet(viewsets.ModelViewSet): ''' CustomDictionary: CustomDictionary: is a customizable set of words per user, with positive and negative words ''' queryset = CustomDictionary.objects.filter( is_active=True, is_deleted=False ).order_by('id') permission_classes = [ permissions.AllowAny ] serializer_class = CustomDictionarySerializer pagination_class = StandardResultsSetPagination def __init__(self,*args, **kwargs): self.response_data = {'error': [], 'data': {}} self.code = 0 This docstring is displaying good in the DRF API view Then, this is an extra function inside of the CustomDictionaryViewSet Class @validate_type_of_request @action(methods=['post'], detail=False) def custom_dictionary_kpi(self, *args, **kwargs): """ This text is the description for this Endpoint. --- parameters: - name: user_id description: Foobar long description goes here required: true type: integer paramType: form - name: language_id paramType: form required: true type: integer """ try: '''some code''' self.code = status.HTTP_200_OK except Exception as e: logging.getLogger('error_logger').exception("[CustomDictionaryViewSet] - Error: " + str(e)) self.code = status.HTTP_500_INTERNAL_SERVER_ERROR self.response_data['error'].append("[API - CustomDictionaryViewSet] - Error: " + … -
How Can I Solve Django Formset forms.Select Problem
forms.py models.py template Hi guys, I'm trying to create a formset as a table. Users will be able to add row by clicking a botton. The only problem is the choice field in formset. Here is the problem; Let's say I wanted to add 3 rows and I choosed Option1,Option2 and Option3 in these 3 rows. When I clicked save button the form said you need to fill the required areas which are the choice fields in 2nd and 3rd rows. The other input fields are fine it only gives error for the choice field. Than I add a print function in forms.py to see which values choice field gives and it gaved "Option1","none","none". When I printed out request.POST, it containes a key like "prefix-0-sieve_no":["Option1,"Option2","Option3"] but it should have been like "prefix-0-sieve_no":["Option1"], "prefix-1-sieve_no":["Option2"], "prefix-2-sieve_no":["Option3"]. Here is the real thing that makes me crazy. After the form gives me the error, when I reselect the same values and clicked the save button again, it works correctly. Excuve my bad English, I hope someone has a solution. -
Reading property from object in exception
I'm trying to read property from error object whilst I catch the exception. Error comes from Celery worker. Below I show the console with error from Celery: The Part of my code is: As you can see the problem is in line 20: message = getattr(error_obj, "Text") But why? In console object ERROR_UKNOWN has property 'Text' and value is 'Neznany błąd'. Why it dosen't work? I will be grateful for help. -
implementing user login with django the page is not getting redirected and i think even the login is not working
i tried checking all other stack overflow questions i used crispy forms urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('blogs/',include('blog.urls')), path('register/',include('register.urls')), path('',include('django.contrib.auth.urls')), path('user/',include('userpage.urls')), ] login.html {% extends 'register/registerbase.html' %} {% load crispy_forms_tags %} {% block content%} <form method="post" > {% csrf_token %} {{ form|crispy }} </form> <p>Dont have an account yet??Register<a href="/register" > here</a></p> <button type="submit" class="btn btn-success">Log In</button> {% endblock %} login.html is placed under templates/registration i tried checking out similar questions here but nothing seems to work please help settings.py Django settings for DSS project. Generated by 'django-admin startproject' using Django 3.0. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=nvwitn66%4wbk-6_9e$6ubvj)(5r03=@!z)4ymtiren6k0x0d' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'register.apps.RegisterConfig', 'blog.apps.BlogConfig', 'crispy_forms', 'userpage.apps.UserpageConfig', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' MIDDLEWARE = … -
Exception Value: NOT NULL constraint failed: send_appdata.product_id_id
I am using a custom user model and when i am trying to reference it in other model i am getting an error. Exception Value: NOT NULL constraint failed: send_appdata.product_id_id views.py from django.contrib.auth import get_user_model AppOnboarding = get_user_model() # get data from json @api_view(['POST']) def index(request): product_id = AppOnboarding.objects.get(pk=request.data['product_id']) product_name = request.data['product_name'] product_url = request.data['product_url'] subject = request.data['subject'] body = request.data['body'] recipient_list = request.data['recipient_list'] sender_mail = request.data['sender_mail'] email_type = request.data['email_type'] broadcast_mail = request.data['broadcast_mail'] email_status = status.HTTP_200_OK location = request.data['location'] # make an object of AppData app_data = AppData(product_id=product_id, product_name=product_name, product_url=product_url, subject=subject, body=body, recipient_list=recipient_list, sender_mail=sender_mail, email_type=email_type, broadcast_mail=broadcast_mail, email_status=email_status, location=location) # save it to DB app_data.save() models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.contrib.auth import get_user_model AppOnboarding = get_user_model() class AppData(models.Model): # app_data_id = models.IntegerField(primary_key=True) product_id = models.ForeignKey(AppOnboarding, on_delete=models.PROTECT) product_name = models.CharField(max_length=100) product_url = models.URLField() subject = models.CharField(max_length=100) body = models.TextField() recipient_list = models.TextField() sender_mail = models.EmailField(max_length=254) email_type = models.CharField(max_length=50) broadcast_mail = models.BooleanField() email_status = models.CharField(max_length=50) date_time = models.DateTimeField(auto_now_add=True) location = models.CharField(max_length=100) AppOnboarding is a custom user model in a different app. I explored the similar questions but could not resolve the issue. Any help is highly appreciated. -
Display datetime after selection
I'm using XDSoft datetime picker as inlined <form id="dateForm" action="" method="post"> {{ form }} <script> $(function () { $("#id_scheduled_time").datetimepicker ({ format: 'd - m - Y H:i', inline:true, ... }); }); </script> </form> How can I display the picked datetime value beside the calendar ? I've tried this: var logic = function( currentDateTime ) { div = document.getElementById( 'fieldWrapper' ) div.insertAdjacentHTML( 'beforeend', currentDateTime ); }; but nothing is displayed beside the calendar. This is working but I don't want to use an alert: var logic = function( currentDateTime ) { alert( currentDateTime ); }; -
local variable prblem with the JS code in pycharm
I am running in issues with the pycharm, down below i have the whole sets of home html/css.js. It is interesting how the code i have it works here , also when i try in VScode it works, but when i try to run in my django project in pycharm it says "introduce local variable". Is there anything i am missing? Thank You. $(document).ready(function() { $(".carousel").carousel(); }); .carousel { position: relative; top: 100px; height: 250px; perspective:175px; } .carousel .carousel-item { width: 450px; } .carousel .carousel-item img { width: 100%; border-radius: 10px 10px 0 0; } .carousel .carousel-item h2 { margin: -5px 0 0; background: #fff; color: #000; box-sizing: border-box; padding: 10px 5px; font-weight: bold; font-size: 3em; text-align: center; } <html lang=""> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"/> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <link rel="stylesheet" href="/Main/static/blog/imageslider.css" /> <script src="/Main/static/functionality/imageslider.js"></script> <title></title> </head> <body> <div class="carousel"> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt="" /> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""/> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""/> <h2>3D CAROUSEL</h2> </a> </div> </body> </html> -
'NoReverseMatch at /blog/' even when asking for a list view the program looks for a detail view
This question comes from the book 'Django 2 by example', and has been asked many times before, but even though I checked all the answers I can't fix the problem. The only thing I am doing differently from the book is creating the 'blog' app inside a 'my_project' project (which contains other apps) rather than inside a 'mysite' project directory. my error looks like this: my_project/urls.py """my_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from person import views from accounts.views import RegisterView # register urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view, name='home'), path('person/', include('person.urls')), path('create/', include('person.urls')), path('accounts/', include('django.contrib.auth.urls')), path('accounts/register/', RegisterView.as_view(), name='register'), path('shopping-cart/', include('shopping_cart.urls')), path('blog/', include('blog.urls', namespace='blog')), ] my blog/urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = … -
Django.core.exeptions.ImproperlyConfigured: the included URLconf does not appear to have any patterns in it
from django.contrib import admin from django.urls import path, include import Echo.urls import users.urls #this is the urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('Echo.urls', namespace='Echo')), path('users/', include('users.urls', namespace='users')) ] help? anything will appreciate. django on visual studio -
how to update many to many fields in django?
I'm struggling with this problem for 2 weeks please help me. how to update many to many fields? -
Conditional object class template tagging Django
I am attempting to replicate HTML cards based on a uniform model: Models.py class Uniform(models.Model): category = models.CharField(choices = CATEGORY_CHOICES, max_length=11) description = models.CharField(max_length = 50) price = models.FloatField(max_length = 6) size = models.CharField(choices=CLOTHES_SIZE, max_length=4) image = models.ImageField(upload_to='uniforms/') class Meta: ordering = ['category'] def __str__(self): return '{}: {} - {} - ${}'.format(self.category, self.description, self.size, self.price) Views.py def item_list(request): uniform = Uniform.objects.all() description = Uniform.objects.order_by().values('description').distinct() category = Uniform.objects.order_by().values('category').distinct() context = { 'uniform':uniform, 'description': description, 'category': category } return render(request, 'apparelapp/item_list.html', context) html <div class="row wow fadeIn"> {% for item in description %} <div class="col-lg-3 col-md-6 mb-4"> <div class="card"> <div class="view overlay"> <img src="" alt=""> <a> <div class="mask rgba-white-slight"></div> </a> </div> <div class="card-body text-center"> <label> <h5>{{ item.description }}</h5> </label> <h5> {% if uniform.description %} <strong> <label for="">{{ uniform.category }}</label> </strong> </h5> {% endif %} <!--<h4 class="font-weight-bold blue-text"> <strong>${{item.price}}</strong> <div class="dropdown"> {% for size in item.size %} <ul> {{size}} </ul> {% endfor %} </div> </h4> --> </div> </div> </div> {% endfor %} What I get is the item description, but not the item category: I am trying to say, if the uniform's description is shown, show the uniform's category - but it is blank I have tried formatting to call on just the …