Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: 404 when requesting static files in CSS but not in HTML
Static files are quite frustrating. Here is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_PATH, 'content'), ] # content/img/bg-mathead.jpg exists Now in my HTML, calling /static/ this way works: <div class="col-lg-6 order-lg-2" style="background-image: url('static/img/bg-masthead.jpg');"></div> [27/Aug/2020 18:39:24] "GET /static/img/bg-masthead.jpg HTTP/1.1" 200 693185 But the same call does not work in CSS: /* masterhead image bakgound */ header.masthead { position: relative; /*background-color: #343a40;*/ background: url("static/img/bg-masthead.jpg") no-repeat center center; background-size: cover; padding-top: 8rem; padding-bottom: 8rem; } [27/Aug/2020 18:42:23] "GET /static/css/static/img/bg-masthead.jpg HTTP/1.1" 404 1817 The same thing happens with relative paths, STATIC_ROOT, etc.. -
How to show select field with pre-selected data using django forms?
I've a django Form with 2 choices (yes and no), on my "create page" i can render the select field to save the data and it works just fine, when i try to use on the "edit page" the value is not pre-selected with the current value, how can i make the current value selected on the select input field? The form: class Form(forms.ModelForm): choose = forms.BooleanField( required=False, widget=forms.Select( choices=[(1, 'Yes'), (0, 'No')], attrs={'class': 'form-control'} ) ) class Meta: model = MyModel When i call the view to edit: class MyUpdateView( LoginRequiredMixin, SuccessMessageMixin, UpdateView, ): model = MyModel form_class = BenefitForm template_name = "my/template.html" success_url = reverse_lazy('my-url') success_message = 'Updated!' def get_object(self, queryset=None): data = super(MyUpdateView, self).get_object() if not data.user == self.request.user: raise Http404 # data.choose is False return data The HTML input will be always "1" (Yes) even tough the current value is "0" (No) The HTML: {{ form.choose }} -
I need to display paintings based on genre in a HTML template
Im doing a project thats a fine art gallery and have different pages based on each painting genre eg. Impressionism, Surrealism etc i duplicated the all paintings template and want to modify it so it only displays a chosen genre. Here is my all_paintings view def all_products(request): """a view to show all products including search""" products = Painting.objects.all() products = Painting.objects.filter(genre__name='genre') for p in products: print(p) context = { 'products': products, } return render(request, 'products/paintings.html', context) Id like to know if can add a filter like above to an existing class or make an entirely new class? and also what do i add to the HTML template so the specific genre paintings will be shown -
Creating a custom function in model to compare two foreign key max timestamps
In my Django project, I am attempting to create a custom model field that relies on comparing the values of two reverse foreign key timestamps. In this toy example, I operate some car dealerships. Cars are hired out to folks but need to be 'serviced' every time before they are hired out again. I am trying to add a 'currently_serviced' field into my Car model. A car is considered currently serviced if it has had an associated 'ServiceEvent' after the latest 'HireEvent'. I have been following the documentation on custom model fields but this doesn't help me navigate the trickiness of the reverse foreign keys and identifying the latest (before current time as I want to ignore future hires) timestamps. I have tried writing model manager classes and writing the logic into my views with F() comparisons, although would prefer as a DRY approach to declare the 'currently_serviced' attribute on the model itself as it would dynamically update as and when cars are hired and serviced and I would then be able to utilise this field in my views, such as by outputting the '% of serviced cars by dealership'. I am currently getting an attribute error, although I suspect … -
How to display content in grid format in django template when receiving dynamic data in terms of list from database?
In django model I have created a multiselectfield for suppose wishlist where user can select multiple wishes from the available choices. I am storing this data in comma separated format when it comes to displaying this on template things are pretty easy. But, I want this data to be displayed dynamically as one row with two columns and as soon as two columns are filled and there is more data left to be displayed logic should should have the capability to create a new row and display the remaining content on the django-template. For reference: # models.py class Wishlist(models.Model): wishlist = ( ('W1',"Buy a big masion"), ('W2',"Buy worlds fastest car"), ('W3',"Visit Europe"), ('W4',"Travel on bike to mountains") ) your_wishlist = MultiSelectField(choices=wishlist) # views.py def index(request): wishlist = Wishlist.objects.all() context = { "wishlist":wishlist } return render(request,'demolistingapp/index.html',context) # index.html {% load app_filters %} {% block content %} <h1>INDEX LISTING APP</h1> {% if wishlist %} {% for each_wish in wishlist %} {% with each_wish.your_wishlist|split:"," as wish %} {% for mywish in wish %} <p>{{mywish}}</p><br> {% endfor %} {% endwith %} {% endfor %} {% endif %} {% endblock %} I have registered the custom filter split which returns a list. I want the … -
How to check if the a query returns something or does not in django?
I am having this :items=order.orderitem_set.all() in my views.py that gives the items in a order. Currently this is under my cart view. The problem I am facing is that even if a persons cart is empty that is there are no items still the user can go to billing page. So is there any way in my views.py so that I can check whether there are item in items and return alert if not. -
How to fetch user profile from google after login
In my django project i create a function which redirect to user on google and ask for login by google account and user can login but it didn't know to fetch user profile from google and save in my database.So any can tell me what should i have to written in if part. def login(self,request): if (data): pass else: client_id = settings.GP_CLIENT_ID scope = "profile&response_type=code&state=jJzexptNPLLF&flowName=GeneralOAuthFlow" url = "https://accounts.google.com/o/oauth2/auth/identifier?client_id="+client_id+"&redirect_uri=http://localhost:8000/index/&scope="+scope return redirect(url) -
How to get objects which are related one to one to the user model
I'm creating an ecommerce website, currently loading the objects created by the customer to the cart template. My doubt is that how to get the customer which is related to the user by a one to one relationship? the error is Attribute error at /cart/ 'User' has no object 'customer' models.py : class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null=True, blank=True) def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) views: def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] context = {'items': items} return render(request, 'store/cart.html', context) all i want to do is get the customer of the user. Thank you! … -
Django default image does not seem to load
Looked at a bunch of answers and tried to fix them, but my default image for profile.html does not seem to load. What I'm I doing wrong and how can I solve, in case it happens again? Thanks. This is my default image. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' profile.html {% extends "blog/base.html" %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{user.username}}</h2> <p class="text-secondary">{{user.email}}</p> </div> </div> <!-- FORM HERE --> </div> {% endblock content %} Relevant settings.py MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to Enforce Consecutive Numbering in "Through" Model Field
I'm using Python 3.7 with Django 3.1. I have two models: Text and Edition. There are a fixed number of texts, and users will be able to create editions in which they place these texts in whatever order they want. This is accomplished by means of a "through" model, EditionTextThrough, which keeps track of the position of a given text in a given edition: class EditionTextThrough(models.Model): text = models.ForeignKey(Text, on_delete=models.CASCADE) edition = models.ForeignKey(Edition, on_delete=models.CASCADE) position = models.PositiveSmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(372)]) class Meta: ordering = ['edition', 'position'] unique_together = ['edition', 'position'] This works fine. However, I want to enforce consecutive numbering for the "position" attribute, relative to the Edition it is paired with. Django's auto-generated IDs won't do this, because they are simply assigned to each row in the table, and don't start over with each Edition that is contained in it. Django's IDs can't do what I want for another reason as well: I want the "position" numbers to remain consecutive, even when some of them are deleted: position | edition_id | text_id 1 | uuid | 4 2 | uuid | 22 3 | uuid | 128 4 | uuid | 16 5 | uuid | 3 Now, if the … -
How to get clean pagination URL in Django?
https://docs.djangoproject.com/en/3.0/topics/pagination/ I'm referring this URL to add pagination to my app but I'm unable to get a clean URL. URL I get: localhost:8000/?page=2 URL I want: localhost:8000/page/2 urls.py urlpatterns = [ path('page/<int:pageno>', views.methodname, name='methodname') ] views.py def meth0dname(request, pageno=1): '''logic goes here''' By doing this I can access clean URL but pagination is not working. It keeps showing me the same landing page on page 2 and doesn't paginate further. -
How to get jsdoc to work with django template tags?
I have js files with {% %} template tags in them, which causes jsdoc to fail with ERROR: Unable to parse <path>: Unexpected token Is there any way to get django template tags to work with jsdoc or any other javascript doc generator? -
Django-Filter - Removing filter options that will return empty
I feel as if I am missing something pretty obvious here. I'm using Django-Filter to filter a ListView and it's working perfectly apart from the fact the options you get in the dropdown menus also include options that will return an empty search query. I've pre-populated my database with a bunch of data I'm going to need down the line yet isn't currently in use, the "Nations" and "Region" model's specifically. Models.py: class Nation(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=100, unique=False) class Region(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=100, unique=False) nation = models.ForeignKey(Nation, on_delete=models.PROTECT) class Business(models.Model): name = models.CharField(max_length=200) nation = models.ManyToManyField(Nation, blank=True,) region = models.ManyToManyField(Region, blank=True,) Filters.py: from business.models import Business, BusinessCategory from locations.models import Nation, Region import django_filters class BusinessFilter(django_filters.FilterSet): nation = django_filters.ModelChoiceFilter( field_name='nation', lookup_expr='isnull', queryset=Nation.objects.all().order_by('name') ) class Meta: model = Business fields = ['business_category', 'nation', 'region'] View.Py: class BusinessIndexView(ListView): paginate_by = 6 template_name = "business/index.html" context_object_name = 'all_business' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter']= BusinessFilter(self.request.GET, queryset=self.get_queryset()) return context def get_queryset(self): return Business.objects.filter(live=True).order_by('-id') Filter.html: {% load crispy_forms_tags %} <div class="mb-2"> <form method="get"> {{filter.form|crispy}} <button type="submit" class="btn btn-outline-success my-2 my-sm-0">Search</button> <a class="btn btn-outline-warning my-2 my-sm-0" href="{% url 'business:index' %}">Reset</a> </form> </div> Filters.py is where I know it is … -
Django Api not serving media files to reactJS client-side
I am working on a React & Django project, I have built a Django API that stores video and also some text whenever I try to render the video by the client-side it does not render the video. The first problem that I came across is was the API was not giving me the correct full path it gave me this: video: "/media/lectures/mat105-Part2.mp4" So I then tried to resolve that by modifying the path to http://127.0.0.1:8000/api${content.video} Code to my API Models class LectureVideos(models.Model): lecturer = models.CharField(max_length=100, blank=False, null=False) module = models.CharField(max_length=100, blank=False, null=False) video = models.FileField(upload_to='lectures') date = models.CharField(max_length=100, blank=False, null=False) Code to my API VIEWS @api_view(['GET']) def getLectureVideos(request): videos = LectureVideos.objects.all() serializer = LectureVideoSerialzer(videos, many=True) return Response(serializer.data) Code to my client-side where I try to retrieve the data class Video extends Component { constructor(props) { super(props); this.state = { lectureVideos: [], }; this.getVideos = this.getVideos.bind(this); } componentDidMount() { this.getVideos(); } getVideos() { const url = "http://127.0.0.1:8000/api/videos-list/"; axios .get(url) .then((response) => { this.setState({ lectureVideos: response.data, }); }) .then((res) => { console.log("Fetch Successful"); }) .then((res) => { console.log(this.state.lectureVideos); }) .catch((error) => { console.log(error); }); } render() { return ( <div className="Video__container"> <VideoList listvideos={this.state.lectureVideos} /> </div> ); } } export default Video; … -
Creating an Inline Formset - Foreign Key Issue
I have the following 2 models that I want to use in a form set. I'm not sure what I've got wrong models.py class AppTradingPartnerTrp(models.Model): id_trp = models.AutoField(primary_key=True) tpid_trp = models.CharField(max_length=50, blank=True, null=True) name_trp = models.CharField(max_length=50) description_trp = models.CharField(max_length=100, blank=True, null=True) idtrn_trp = models.ForeignKey('AppTransmissionTrn', models.DO_NOTHING, db_column='idtrn_trp', blank=True, null=True) class AppCustomerTpRel(models.Model): id_rel = models.AutoField(primary_key=True) idcst_rel = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_rel') idtrp_rel = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='id_trp') cust_vendor_rel = models.CharField(max_length=50, blank=True, null=True) sender_id_rel = models.CharField(max_length=50, blank=True, null=True) old_vendor_rel = models.CharField(max_length=50, blank=True, null=True) vendor_name_rel = models.CharField(max_length=50, blank=True, null=True) category_rel = models.CharField(max_length=50, blank=True, null=True) And here is where I'm trying to create the formset: forms.py CstVendorNoFormSet = inlineformset_factory(AppCustomerTpRel, AppTradingPartnerTrp, exclude=()) However when I do runserver I'm getting: ValueError: 'AppTradingPartnerTrp' has no ForeignKey to 'AppCustomerTpRel'. -
Switch language on Django app keep languagecode/current_path_app
I have integrated switch button to change language on my django site. I have some apps. I don't want to redirect to home, instead of keep languagecode/current path this is my view.py in home app #function switch language def change_language(request): response = HttpResponseRedirect('/') if request.method == 'POST': language = request.POST.get('language') if language: if language != settings.LANGUAGE_CODE and [lang for lang in settings.LANGUAGES if lang[0] == language]: redirect_path = f'/{language}/' elif language == settings.LANGUAGE_CODE: redirect_path = '/' else: return response from django.utils import translation translation.activate(language) response = HttpResponseRedirect(redirect_path) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language) return response -
Get the last inserted time for more then one modal class in DRF
I am trying to get the response inserted time of more then one modal class and send in the response in DRF. For example, my modal class is: class FeedVehicle(models.Model): sensor = models.ForeignKey( 'SensorDevice', on_delete = models.CASCADE ) feed = models.TextField() created_at = models.DateTimeField(auto_now_add=True) class FeedElsys(models.Model): sensor = models.ForeignKey( 'SensorDevice', on_delete= models.CASCADE ) feed = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) I was writing the view as such but not able to succed class LastFeedAPIView(generics.ListAPIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser, permissions.IsAuthenticated,) serializer_class = serializers.DashboardSerializer def get(self, request, format=None): weather_r712 = models.FeedVehicle.objects.all().order_by('-id')[:1] weather_r712_searlializer = serializers.SignalFeedSerializer(weather_r712, read_only=True) weather_r718 = models.FeedElsys.objects.all().order_by('-id')[:1] weather_r718_serializer = serializers.WeatherR718FeedSerializer(weather_r718, read_only=True) response = {"r712":weather_r712_searlializer.data, "r718":weather_r718_serializer} return Response(response) I want to get the response of both modal last inserted time. I have created the serializer class But not sure how I will connect and get the response. Any Suggestions. -
How to check if data exists or not in Django rest framework
I have a CartModel, CartItem model. I trying to do when I create a cart and when the cart is get created and again I add the same data as I enter in pervious it create another cart. I trying to do that if the cart exists in the CartItem table it has to show the response "Cart already exists". But it is creating another cart. I search a lot and use the code but it will not run. If somebody is capable of giving an answer the please help me. views.py* class CartTestViewSet(viewsets.ModelViewSet): serializer_class = CartItemSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user if user.is_authenticated: if user is not None: if user.is_active and user.is_superuser or user.is_Customer: return CartItem.objects.all() raise PermissionDenied() raise PermissionDenied() raise PermissionDenied() def post(self, request): cart = Cart.objects.filter(user=request.user, cart=request.data, service=request.data, defects=request.data) if cart.exists(): print('cart already exists') else: print('cart is created') serializers.py from rest_framework import serializers from .models import CartItem, CartModel from rest_framework.response import Response class CartItemSerializer(serializers.ModelSerializer): def get_total(self, obj): return obj.get_total get_total = serializers.IntegerField(read_only=True, required=False) # id = serializers.IntegerField(read_only=False) class Meta: model = CartItem fields = "__all__" extra_fields = ['get_total'] read_only = ['get_total'] class CartModelSerializer(serializers.ModelSerializer): class Meta: model = CartModel fields = "__all__" models.py from django.db … -
How can i use asgi completely in django?
I'm new to django. After searching here and their i found asgi enable performance boost over django wsgi based view. So that i want to completely switch to asgi view but i din't found any guides regarding to it so that i can i implement it in views(function and class) and django orm. And also I'm pretty much unsure about how it works. If this question make no any sense, then sorry for that and help me regarding to asgi which is new features in django3. How it is different from django channel. -
Logger in django not printing on console or saving in file when applied inside api
I am trying to implement logging into my application. I have written the logging config in settings.py as LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, # disable logging # Handlers ############################################################# 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'logs/log.log', }, ######################################################################## 'console': { 'class': 'logging.StreamHandler', }, }, # Loggers #################################################################### 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'INFO', 'propagate': True, }, }, } Now I used the logger in my API as: import logging . . . log = logging.getLogger(__name__) class GetDataStores(generics.RetrieveAPIView): def retrieve(self, request, *args, **kwargs): . . log.info('sample log message') . . This is neither printing anything on the console nor writing in the file -
How to deploy a Django app on a private cloud?
I am working on one django app and would like to find a way to deploy it on the cloud for testing purposes. As the app is for my own purposes, and not totally secure, I don`t want it to make it available on the internet. Apart buying a PC server and install it at home, what are the options to deploy the app and keep pushing some modifications to it? Many Thanks, -
vim recover a deleted swap file
I deleted the swap file and lost the modifications. The *.bash file returned to it original version. Is it possible to undo delete of the swap file (i.e., recover or restore the deleted *.bash.swp file)? -
Django urlpatterns issue
I am working from the Python Crash Course from no starch by Eric Matthes. I am having an issue with include(). The error I am receiving in command prompt is: django.core.exceptions.ImproperlyConfigured: passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. Here is my code: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('learning_logs.urls', namespace='learning_logs')), ] -
Is it possible to put a model's admin page in the "Authentication and Authorization" section?
At the moment this model's admin page shows up in the "App" section of the admin site (in admin.py): from app.models import Role class RoleAdmin(admin.ModelAdmin): class Meta: model = Role filter_horizontal = ('group',) admin.site.register(Role, RoleAdmin) Is it possible to add this to the "Authentication and Authorization" section instead? -
Save strings (separated by virgola) directly into a django field
I have a html file as follow: <form method="POST" action="" id="dropdownform" enctype="multipart/form-data"> <fieldset class="form-group"> {% csrf_token %} <div class="content-section"> <div class="card-body"> {{ form.categories }} </div> </div> <div class="content-section"> <p class="text-muted" id="showtags"> // Tags will appear here </p> </div> </fieldset> <div class="form-group mt-7"> <button class="btn btn-primary" type="submit">Submit</button> </div> </form> <script> // here there is a JS code which returns the selected categories as tags into <p> </script> This is my model: class Post(models.Model): categories = models.ForeignKey(Categories, blank=True, null=True, on_delete=models.CASCADE) tags = models.TextField(blank=True, null=True) class Meta: db_table = "posts" def get_tags(self): if self.tags: return self.tags.split(",") else: None There is a dropbbox form that when user changes categories, a function in scripts returns tags and they will be appeared as a long string which separated by virgola. I need to save these values in tags field as separated strings. I don't know exactly how to tell django field should take that field after submitting the form!