Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add an optional slug in a Django Url
I want to add an optional Stackoverlow like slug to my urls in Django path( r"item/<int:pk>/<slug:slug>", ItemDetailView.as_view(), name="item_detail", ), How do I make the slug optional so that it works in all three cases: item/1 item/1/ item/1/slug -
How to display uploaded Dicom image metadata in detailed view in Django?
I am a new to coding and working on a small Django project in which I want to display Dicom image metadata. I included FileField in the Django model to upload a Dicom image and I want to display the uploaded Dicom image metadata in Generic detailed view. I tried overriding the context method and accessing the image path but getting an error. How do I proceed with it? Please help! #My model class Patient(models.Model): name = models.CharField(max_length=100) ailment = models.TextField(max_length=200) date_tested = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='.',default='download.jpg') dicom = models.FileField(upload_to='dicom/',null=True) #My Detailed view class PatientDetailView(LoginRequiredMixin,DetailView): model = Patient def get_context_data(self,**kwargs): medinfo = dict() context = super().get_context_data(**kwargs) dcpimg = imageio.imread(self.dicom.path) for keys in dcpimg.meta: medinfo[keys] = str(dcpimg.meta[keys]) context['medinfo'] = medinfo return context ##Iam getting this error AttributeError: 'PatientDetailView' object has no attribute 'dicom' -
Django raw sql or stored proc to run paramatised view?
Thanks in advance for advice. I'm new-ish to Django, creating a site with (amongst other things) products that people can upvote (ie 'like'). I'm showing related liked products at the end of the product detail page (ie people that likes this product also liked these products). Method I'm doing recording likes is a link table that pairs product ID with user ID. To get the related products is a reverse lookup on the upvote table. My SQL code does this fine, and I can feed the result to get a collection of related products in a class function: def related_products(self, max_results=4): sql = f"\ SELECT PRODUCT_ID AS ID\ FROM PRODUCTS_UPVOTE\ WHERE VOTER_ID IN ( \ SELECT VOTER_ID\ FROM PRODUCTS_UPVOTE\ WHERE PRODUCT_ID = {product_id} \ )\ GROUP BY PRODUCT_ID\ HAVING PRODUCT_ID != {product_id}\ ORDER BY COUNT(PRODUCT_ID) DESC\ FETCH FIRST {max_results} ROWS ONLY" return Product.objects.raw(sql) This works fine, but it doesn't 'feel' right putting lines of SQL code in the model like this - surely better to use a stored proc? But I see many sites warning against this. Or maybe there's a better way to handle running views with parameters in this that I'm not seeing? What's the recommended method for … -
How to upload a File from a form in Django
I want to upload a file to an S3 location from a form. I'm using Python3 and django This is what I have in my model: class MediaSubtitle(models.Model): media = models.ForeignKey( "Media", related_name='%(app_label)s_%(class)s_media', verbose_name="Media") language = models.CharField( max_length=255, db_index=True, verbose_name="Taal", blank=False, null=False) source = models.FileField( upload_to='subtitles/%Y/%m/%d', blank=True, validators=[FileExtensionValidator(allowed_extensions=['srt', 'sub'])]) def __str__(self): return "%s" % (self.media,) class Meta: verbose_name = "Media Ondertitel" verbose_name_plural = "Media Ondertitels" And this is what I use in my forms.py: class AddSubtitleForm(forms.ModelForm): def __init__(self, parent, **kwargs): super().__init__(**kwargs) self.parent = parent self.fields["language"].required = True self.fields["source"].required = False def save(self): result = MediaSubtitle( language=self.cleaned_data["language"], source=self.data["source"], media=self.parent) return result.save() class Meta: model = MediaSubtitle fields = ("language", "source") How Can I make sure that the moment the save is executed that the file is uploaded? -
I want to render a page only when the user is logged in, otherwise render the login page. I'm using firebase for authentication
from django.shortcuts import render from django.contrib import auth import pyrebase config = { 'apiKey': "", 'authDomain': "", 'databaseURL': "", 'projectId': "", 'storageBucket': "", 'messagingSenderId': "", } firebase = pyrebase.initialize_app(config) database = firebase.database() _auth_ = firebase.auth() def loggedin(request): email = request.POST.get('email') password = request.POST.get('password') try: user = _auth_.sign_in_with_email_and_password(email,password) except: message = "Invalid Credentials" return render(request,'signin.html',{"messg":message}) session_id = user['idToken'] request.session['uid'] = str(session_id) return render(request,'loggedin.html',{"e":email}) def logout (request): auth.logout(request) return render(request,'signin.html') def joinexam(request): #i want to render this page only when the user is logged in return render(request,"joinexam.html") I want to render the "joinexam.html" page only when the user is logged in. If the user isn't logged in and tries to access 127.0.0.1:8000/joinexam i want to redirect the user to login page -
OnetoOneRelatedField model details are not populating while trying to post details through APIVIew in Django Rest Framework
models.py class Address(models.Model): name=models.CharField(max_length=100,default='') place=models.CharField(max_length=100,default='') class wish(models.Model): created=models.DateField(auto_now_add=True) title=models.CharField(default='',null=True,blank=True,max_length=100) wishtext=models.CharField(max_length=1000) address=models.OneToOneField(Address,null=True,on_delete=models.CASCADE,) serializers.py file. class WishSerializer(serializers.ModelSerializer): class Meta: model = wish fields = ['id','title','wishtext','address'] depth=1 views.py class WishList(generics.ListCreateAPIView): #permission_classes = [permissions.IsAuthenticated] queryset=wish.objects.all() serializer_class = WishSerializer Note: am able to get the all details including address model details. But when i am trying to post details ,able to see only wish model fields but not the address object drop down field. Please help me on this? -
Unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'
I am trying to calculate the difference between 2 dates in weeks. One date gets fetched from database and the field is defined as models.DateField(blank=True, null=True). I want to calculate the difference between the date from database and today. After watching some tutorials, I came up with this implementation: serializer.py: foo = Foo.objects.get(id=1) calculate_difference_between_two_dates_in_weeks(get_today(), foo.start_date) The value of start_date in database is only 2020-10-23. utils.py: from datetime import datetime, timedelta from django.utils import timezone def get_date_in_datetime(date): time = datetime.min.time() return datetime.combine(date, time) def get_today(): return timezone.now() def calculate_difference_between_two_dates_in_weeks(date_one, date_two): d1 = get_date_in_datetime(date_one) d2 = get_date_in_datetime(date_two) d1 = (date_one - timedelta(days=date_one.weekday())) d2 = (date_two - timedelta(days=date_two.weekday())) return (d2 - d1).days / 7 I keep getting an error saying unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'. When I print d1 and d2 after d2 = get_date_in_datetime(date_two), I get 2020-10-21 00:00:00 for d1, and 2020-10-23 00:00:00 for d2. They look the same but I still get the same error. How can I convert datetime.datetime to datetime.date or vice versa to have the same type so the calculate_difference_between_two_dates_in_weeks function can work? -
Disable original text error messages in Django
I have a model in which for each field I have written text messages for errors. But if you enter incorrect data, native Django messages are displayed. How do I display mine? class AbstractUser(AbstractBaseUser, PermissionsMixin): """Создал абстрактоного юзера от которого будут унаследованны остальные юзеры""" phone_number = models.CharField( _('phone number'), max_length=14, unique=True, help_text='Enter your phone number', error_messages={'blank': "This field cannot be blank", 'invalid': "Phone number field is not valid", 'unique': "This phone number is already registered", } ) According to my model, if the field is empty, there should be an error "Phone number field cannot be blank" -
Count number of element exits on db: Django
I want to count the car_model that exits on db. if car_model do not exits then it should count zero. Any help would be much appreciated. Thank you so much in advance. models.py class CarOwnerCarDetails(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) car_model = models.CharField(max_length=10) views.py class CarModelListView(ListAPIView): # permission_classes = (IsAuthenticated,) def get(self,request,*args,**kwargs): qs = CarModel.objects.all() serializer = CarModelListSerializer(qs,many=True) data = serializer.data return Response({ 'success' : 'True', 'message' : 'Data retreived successfully', 'data' : data, },status=HTTP_200_OK) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data["car_model"] = CarOwnerCarDetails.objects.count() data.append(car_model) print(car_model) return data -
How to check if a user has new notifications
my question is this: If a user is returned a list of notifications on a page (via Django api endpoint) , how can I check which notifications have been viewed and which are new? I've been thinking of something along the lines of like: storing the length of the notifications array from the previous session and comparing it to the new array. If the length is longer, then a notifications component is displayed. Can this be done with cookies or something built into Vue? Right now Directors are able to view an application that a user submits and change the status to 'accepted' or 'rejected'. Users can then see that change on their end when they visit /applications. <p>Status: {{application.status}}</p> I was thinking of including a POST request with the director's PATCH request to create a new notification object. Hence, what I described above. Directors can change the application decision via PATCH methods: { applicationDecision($axios, params) { const config = { headers: { "content-type": "application/json; " } }; let response = this.$axios.$patch( `/api/v1/apps/${this.applicants.id}/`, this.application, config ); Users accessing their applications async asyncData({ params, $axios, store }) { try { const body = store.getters.loggedInUser.id; let applications = await $axios.$get(`/api/v1/apps/`, { params: … -
Implementing point search in a polygon using Django
There were some difficulties while implementing my application in django. What the app should do: Accepts and saves Delivery zones as a set of coordinates; Accepts data from Couriers with reference to the delivery area; Accepts the coordinates of the delivery location and returns the Courier data and the Delivery zone ID. I coped with two points, but there were problems with the last one. I found how to solve this problem using Python shell: from django.contrib.gis.geos import GEOSGeometry p = GEOSGeometry(location, srid=4326) DeliveryZone.objects.filter(coordinates__contains=p) But I don't know how to implement this inside my app. My models.py from django.contrib.gis.db import models class DeliveryZone(models.model): coordinates = models.MultipolygonField(srid=4326) def __str__(self): return f"#{self.id}" class Courier(models.model): delivery_zone = models.ForeignKey(DeliveryZone, on_delete=models.protect) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return f"#{self.id} {self.last_name}" class Delivery(models.model): location = models.PointField(srid=4326) def __str__(self): return f"#{self.id}" And views.py from django.contrib.gis.geos import GEOSGeometry from rest_framework import viewsets from .serializers import DeliveryZoneSerializer, CourierSerializer, DeliverySerializer from .models import DeliveryZone, Courier, Delivery class DeliveryZoneViewSet(viewsets.ModelViewSet): queryset = DeliveryZone.objects.all() serializer_class = DeliveryZoneSerializer class CourierViewSet(viewsets.ModelViewSet): queryset = Courier.objects.all() serializer_class = CourierSerializer class DeliveryViewSet(viewsets.ModelViewSet): queryset = Delivery.objects.all() serializer_class = DeliverySerializer I can provide more information if necessary. -
I want to display all the data entered by user in view_project.html page in django
views.py @login_required(login_url="/accounts/login/") def add_project(request): if request.method == 'POST': form = forms.CreateProject(request.POST, request.FILES) if form.is_valid(): # save in db instance = form.save(commit=False) instance.candidate = request.user instance.save() return redirect ('view_project') else : form = forms.CreateProject() return render(request, 'home/add_project.html', {'form': form}) @login_required(login_url="/accounts/login/") def view_project(request): return render(request, 'home/view_project.html') This is the views.py file where the project is added into the database for a particular user and the HTML file used for this is add_project.html -
Mail is not validated because I do not change my username
I have a form that takes "username" from the User model and my own "email" field. I want to change this data for the User model. At first glance everything seems to work fine, the name changes and the mail is the same. But if I only change the mail and I don't touch the username, I get an error: "A user with this name already exists. Is there any way I can make an exception for this situation? file views.py: form=UserUpdateForm(request.POST) if form.is_valid(): user=User.objects.get(username=self.request.user) user.username=form.cleaned_data.get('username') user.email=form.cleaned_data.get('email') user.save() file forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField(required=False) def __init__(self, *args, **kwargs): super(UserUpdateForm, self).__init__(*args, **kwargs) if 'label_suffix' not in kwargs: kwargs['label_suffix'] = '*' self.fields['username'].widget = forms.TextInput(attrs={'class':'input-text'}) self.fields['email'].widget = forms.EmailInput(attrs={'class':'input-text'}) class Meta: model = User fields = ("username","email",) def clean_email(self): cleaned_data = super(UserUpdateForm,self).clean() email=cleaned_data.get('email') return email -
Django , upload multiple images with formset's
I've been trying for days to understand the reason for my error, in the first phase I detected that it was missing {{ formset.management_form }} in the html, which i include and still continues to give the same error: "ManagementForm data is missing or has been tampered with" And I don't know if my views are the way they should be done. Models class Intervencao(models.Model): ........ 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) <!-- e Forms class TabletForm2(forms.ModelForm): class Meta: model=Intervencao fields = __all__ class TabletFormImagem(forms.ModelForm): imagem = forms.ImageField(required=True) class Meta: model=Imagem fields = ['imagem',] Views def project_detail_chefe(request, pk): ImagemFormSet = modelformset_factory(Imagem,form=TabletFormImagem, extra=3) instance = Intervencao.objects.get(id=pk) d1 = datetime.now() intervencaoForm = TabletForm2(request.POST or None, instance=instance) formset = ImagemFormSet(request.POST, request.FILES,queryset=Imagem.objects.none()) if request.method == "POST": if intervencaoForm.is_valid() and formset.is_valid(): instance_form1 = intervencaoForm.save(commit=False) instance_form1.data_intervencao_fim = d1 instance_form1.save() images = formset.save(commit=False) for image in images: image.intervencao = instance_form1 image.save() return redirect('index') else: intervencaoForm = TabletForm2(request.POST) formset = ImagemFormSet(queryset=Imagem.objects.none()) context = { 'intervencaoForm':intervencaoForm, 'formset':formset, } return render(request, 'tablet/info_chefes.html', context) HTML <form method="post" enctype="multipart/form-data" id="gravar"> <div class="row"> <div class="col-md-12"> <table> {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} … -
If statement in Django views
I have followed an ecommerce tutorial by Dennis Ivy in Django (Python). I want to expand on the project by adding product categories. So the idea is that every product has a dropdown menu (models.py) CATEGORIES = ( ('code','CODE'), ('books', 'BOOKS'), ('computer','COMPUTERPARTS'), ('other','OTHER'), ) category = models.CharField(max_length=15, choices=CATEGORIES, default='code') The store.html shall only render products from a given category. If I type 'localhost/code' in my browser it shall only display the items that have the category: 'code'. Currently it just displays everything, when I just goto 'localhost/'. I have thought about making a urlpattern for each individual category, but I think it will get messy pretty quickly. I have a function called store in views.py def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'store/store.html', context) Is there a way to return only a specific category -or to return something else than objects.all()? products = Product.objects.all() The store.html looks like this: {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> {{product.about}}<br><br> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> {{product.category}} <h4 style="display: inline-block; float: right"><strong>${{product.price}}</strong></h4> </div> </div> {% … -
Django Orm Compare to same model querysets
I am trying to convert a sql join query to django orm, not quite getting how to do it. Models class Author(models.Model): author_name = models.CharField( verbose_name='Author', primary_key=True, max_length=250) country = models.CharField(verbose_name='Country', null=False, blank=False, max_length=250) def __str__(self): return self.author_name class Publisher(models.Model): publisher_name = models.CharField( verbose_name='Publisher', primary_key=True, max_length=250) pub_add = models.TextField(verbose_name='Address', blank=False, null=False) def __str__(self): return self.publisher_name class Book(models.Model): isbn = models.IntegerField(verbose_name='ISBN', primary_key=True) title = models.CharField(verbose_name='Title', unique=True, blank=False, null=False, max_length=250) pub_year = models.IntegerField(verbose_name='Publish Year', blank=False, null=False) unit_price = models.IntegerField(verbose_name='Unit Price', blank=False, null=False) authors = models.ForeignKey(Author, verbose_name='Author of book', on_delete=models.DO_NOTHING) publishers = models.ForeignKey(Publisher, verbose_name='Publisher of book', on_delete=models.DO_NOTHING) Sql Query is select distinct B1.title from Book B1, Book B2 where B1.unit_price > B2.unit_price and B2.pub_year = 2004; django query I tried qs = Book.objects.filter( pub_year=2004 ) qs = Book.objects.filter( unit_price__gt__in=qs ) It gives this error I feel like this is actually really, really easy and I am missing some obvious thing, any guidance will be helpful. Thanks. -
Add identifier only if there is a conflict for slug
I have a slug customization, It provides to create slug from title automatically. Here is my code, #models.py from django.db import models from django.urls import reverse from django.template.defaultfilters import slugify class Blog(models.Model) title = models.CharField(max_length=200) slug = models.SlugField(blank=True) def get_absolute_url(self): return reverse('school', kwargs={'slug':self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) #admin.py class BlogAdmin(admin.ModelAdmin): list_display = ('title') prepopulated_fields = {'slug': ('title',)} admin.site.register(Blog,BlogAdmin) #urls.py from django.urls import path from .views import * urlpatterns = [ path('blog/<slug:slug>', entry.as_view(), name='entry'), ] If I make Slug as unique=True, when blog titles are the same(It could be same), slugs should be changed manually. I don't want this. I want to add identifier with numbers but only if there is conflict. The scenario I want is as follows, Lets assume that, Admin creates a blog, blog title is "London travel guide" -> This is the first time created blog with this title. so slug is "london-travel-guide" Second time admin creates a blog with title as "London travel guide" slug should be "london-travel-guide-1" Third time, slug should be "london-travel-guide-2" and so on. How can i implement this, thanks for help. -
URL Pattern with Primary Key not working properly
Need help with the regex in urls. I'm building a different app, not the one shown in the lecture above. To relate to my case with the lecture, School is Clients, and Students is categories. In urls.py file, from url_patterns : url(r'^(?P<pk>[-\w]+)/$', views.DetailClientList.as_view(), name='Detail_Client_List'), This work correctly, with the address being http://127.0.0.1:8000/App1/cli1/, where cli1 is a Clients table primary key (one of the records). But when I put the line below in url patterns (instead of the above) url(r'^<str:pk>/$', views.DetailClientList.as_view(), name='Detail_Client_List') I get the following error (same error for int:pk): Page not found (404) Request Method:GET Request URL:http://127.0.0.1:8000/App1/cli1/ The resulting URL is the same in both cases described above. So where am I going wrong here. I'm guessing its an issue with the url pattern regex (although resulting URL is the same?). Please help. TIA! -
There should be an error here, but does'nt
i'm following the Django's tutorial for first app, and in the Part 5 they say: Different error? If instead you’re getting a NameError here, you may have missed a step in Part 2 where we added imports of datetime and timezone to polls/models.py. Copy the imports from that section, and try running your tests again. But i not missed nothing, i write line by line, and i not received the expected message. I put my code below, if someone with more experience can help me to understand why i not receive the error message, i'll thank you ( the word appreciate and its meaning is very strange uhh). my_project/project/polls/model.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text my_project/project/polls/tests.py import datetime from django.test import TestCase from django.utils import timezone from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self) time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(),False) -
What is forloop.counter in Django?
This is the code in Django official website tutorial: <h1>{{ question.question_text }}</h1> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <br> {% endfor %} <input type="submit" value="Vote"> </form> -
Video doesnot load in django
I am trying to play video in my django built website but it is not playing Here is my setting code STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') ##lINKING THE STATIC FILES THAT IS CSS STATICFILES_DIRS= [ STATIC_DIR ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/movies/' Views.py def Movie_detail(request, pk): post = get_object_or_404(Postmovie, pk=pk) ##EITHER gets specific object from primary key or return 404 stuff_for_frontend = {'post': post} return render(request, 'Movie_Management_System/Movie_details.html',stuff_for_frontend) #render movie details Source i gave in Movie_details.html <br><br> <video width='1000' controls> <!--video player using html--> <source src='{{ MEDIA_URL }}{{ videofile }}' type='video/mp4'> </video> <br><br> Directory structure is like this Directory looks like enter image description here -
Django E.410 errors on runserver
ERRORS: ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. System check identified 1 issue (0 silenced). it is already present in it but why error -
How can I request a POST to the django rest framework except for null json?
I'm making an api with the django rest framework. Now, in my api, where I don't want the content to go in, I'm sending a request: "field": null. But I want to send a request without specifying this field in json, how should I handle it? Here's my code. class PostSerializer (serializers.ModelSerializer) : owner = userProfileSerializer(read_only=True) like_count = serializers.ReadOnlyField() comment_count = serializers.ReadOnlyField() images = ImageSerializer(read_only=True, many=True) liked_people = LikeSerializer(many=True, read_only=True) tag = serializers.ListField(child=serializers.CharField(), allow_null=True) #If I don't want to get a tag, I want to erase the tag field altogether instead of "tag": null. comments = CommentSerializer(many=True, read_only=True) class Meta : model = Post fields = ('id', 'owner', 'title', 'content', 'view_count', 'images', 'like_count', 'comment_count', 'liked_people', 'tag', 'created_at', 'comments') -
django verion:1.11.7, while python manage.py collectstatic i am getting following error
(ecommerce) PS C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\src> python manage.py collectstatic Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\core\management_init_.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\core\management_init_.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 173, in handle if self.is_local_storage() and self.storage.location: File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\utils\functional.py", line 239, in inner return func(self._wrapped, *args) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\core\files\storage.py", line 283, in location return abspathu(self.base_location) File "c:\users\heisenbergsmn\appdata\local\programs\python\python38\lib\ntpath.py", line 527, in abspath return normpath(_getfullpathname(path)) TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not tuple (ecommerce) PS C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\src> -
Django - get model in navbar
I have a class in models: class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) device = models.CharField(max_length=200, null=True, blank=True) Is there a way to access this model in navbar without creating entry in "views.py"? I would like to access similarly to {{ request.user.id }}.