Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can "list_display" show users input on django admin page?
I need to see user's input display on django's admin page, from what i have read, I need to use list_display but there is nothing appearing on admin page. Maybe there is a problem in the views.py but everything looks good. Here is my code: Views.py def process_e(request): if request.method == 'POST': if request.POST.get('website_name') and request.POST.get('product_name') and request.POST.get('phone_number') and request.POST.get('website_details') and request.POST.get('website_content'): post=Enterprise() post.title= request.POST.get('website_name') post.content= request.POST.get('product_name') post.content= request.POST.get('phone_number') post.content= request.POST.get('website_details') post.content= request.POST.get('website_content') post.save() return render(request, 'enterprise.html') else: return render(request,'enterprise.html') Admin.py from django.contrib import admin from service.models import Enterprise class PaymentsAdmin(admin.ModelAdmin): list_display = ('website_name', 'product_name', 'phone_number', 'website_details', 'website_content') admin.site.register(Enterprise, PaymentsAdmin) Models.py from django.db import models class Enterprise(models.Model): website_name = models.CharField(max_length=50) product_name = models.CharField(max_length=200) phone_number = models.CharField(max_length=200) website_details = models.CharField(max_length=200) website_content = models.CharField(max_length=200) Html <div class="form-group"> <label>Website name</label> <input type="text" name="website_name" class="form-control" placeholder="First name"> </div> <div class="form-group"> <label>Product name (if there is)</label> <input type="text" name="product_name" class="form-control" placeholder="First name"> </div> <div class="form-group"> <label>Phone number</label> <input type="text" claa="phone_name" class="form-control" placeholder="First name"> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">What kind of content should your website upload?</label> <textarea class="form-control" name="website_content" rows="3"></textarea> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Website details</label> <textarea class="form-control" name="website_details" rows="3"></textarea> </div> -
Identifying and debugging a getJSON error with Django
I've got an error in my Django app that I can't seem to figure out for the life of me Basically the issue is that my getJSON call is failing in my template and I can't figure out why because I can access the url directly via the browsel and the development server is showing a 200 response as well. Here's my view def test(request): cases = ConfirmedCase.objects.all() cases = read_frame(cases, fieldnames=['provice_state', 'country_region', 'confirmedcases','date']) cases['date'] = pd.to_datetime(cases['date']) globaltrend = globaltrend.groupby('date')[['confirmedcases','1_day_growth']].sum().reset_index() globaltrend['date'] = globaltrend['date'].dt.date #convert back to date globaltrend= globaltrend.to_dict(orient='list') data = {} data['chart_data'] = globaltrend data = json.dumps(data, default=str) return HttpResponse(data, content_type='application/json') Here's the url from tracker import views as tracker urlpatterns = [ path('test/', tracker.test, name="test"), ] If I go to http://127.0.0.1:8000/test/ in the browser, everything works fine and I see { "chart_data": { "date": [ "2020-03-26", "2020-03-27" ], "confirmedcases": [ 66885, 69030, ], "1_day_growth": [ 3.21, 3.18, ], } } Here's my script in my template/html file <script > $(document).ready(function(){ var url = '{% url "test" %}' $.getJSON(url, function(d) { console.log("working"); alert('yay') }).done(function(d) { console.log("done"); }).fail(function(d) { console.log("error"); console.log(url); }).always(function(d) { console.log("completed regardl"); }); }); </script> This keeps throwing an error (and I dont see the alert), even … -
Django Pass Multiple Arguments Into Sitemap URL
I would like to take the tc_accept_specific_version named URL from https://github.com/cyface/django-termsandconditions/blob/master/termsandconditions/urls.py#L67-L71 and pass in the slug (site-terms) and version_number (1.0) into my sitemap.xml file so that /site-terms/1.0/ gets put onto the end of the /terms/accept/ link. How do I do this? Currently, the code below is able to only pass in one argument instead of two: class StaticViewSitemap(sitemaps.Sitemap): priority = 0.9 changefreq = 'always' def items(self, *args): return [ ('tc_view_page', {}), ('tc_accept_page', {}), ('tc_email_page', {}), ('tc_accept_specific_version_page', {'slug':'site-terms'}), ('tc_view_specific_page', {'slug':'site-terms'}), ] def location(self, obj): name, kwargs = obj return reverse(name, kwargs=kwargs) Desired Result: <url> <loc>http://www.example.com/terms/accept/site-terms/1.0/</loc> <changefreq>always</changefreq> <priority>0.9</priority> </url> -
How to perform calculations in Django class-based views?
I used Django class-based views to create a simple web application. In this app, a user submits length and width of a building, the app calculates the area and stores it in the database. After submission the user is redirected to the 'results' page where he can see his inputs and result. I'm not sure how to implement such calculation function in generic views. My Models: from django.db import models class Building(models.Model): length = models.IntegerField(default=1) width = models.IntegerField(default=1) area = models.IntegerField(default=1) def __str__(self): return self.name My Forms: from django import forms from .models import Building class BuildingForm(forms.ModelForm): class Meta: model = Building fields = ('length', 'width', 'area') My Views: from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse, reverse_lazy from .models import Building from .forms import BuildingForm from django.http import HttpResponseRedirect, HttpResponse class BuildingListView(ListView): model = Building context_object_name = 'buildings' class BuildingCreateView(CreateView): model = Building form_class = BuildingForm success_url = reverse_lazy('results') class BuildingUpdateView(UpdateView): model = Building form_class = BuildingForm success_url = reverse_lazy('building_changelist') def calculation(request): length = request.POST.get('length', False) width = request.POST.get('width', False) area = length * width Building.objects.create(length=length, width=width, area=area,) return HttpResponseRedirect(reverse('results')) Can someone share a good example related to my question, or help me to implement this function … -
How to connect the views functions with two templates in django?
In one of my views, I have a function that brings some information of some users. Lets say that in the template (Template A) the users are displayed on a table, and each of them has a button. If you click the button, you will be redirected to another template (Template B). What I want to do is that when you click on the button and sends you to the other page, I want to display the information of that user. How do I do that? -
How to test function that checks and login temporary user - Django
Hello I'm trying to test function that takes temporary user id (if exists) from session and log the user in. def check_if_temp_user_exists_and_log_in(request): temp_user = request.session.get('temporary_user_id', None) if temp_user: u = User.objects.get(pk=temp_user) return login(request, u) Here is my uncomplete unittest. I don't know, what login() returns, so I am not able to finish the test code. import unittest from django.test import RequestFactory from django.contrib.sessions.middleware import SessionMiddleware class AnonymousOrRealTestCase(unittest.TestCase): def test_check_if_temp_user_exists_and_log_in(self): request = RequestFactory().get('/') # adding session middleware = SessionMiddleware() middleware.process_request(request) request.session.save() request.session['temporary_user_id'] = '1' result = check_if_temp_user_exists_and_log_in(request) self.assert ??? Can you help my please? Thanks a lot :) -
Filtering posts by three components logic issue
Code is working fine, but I have one little problem in filtering. def post_list(request): school_slug = request.GET.get('school') category_slug = request.GET.get('category') if VideoPost.objects.filter(school=school_slug).filter(category=category_slug).filter(approve = 1).exists(): posts = VideoPost.objects.all().filter(approve = 1) if school_slug: posts = posts.filter(school=school_slug) if category_slug: posts = posts.filter(category=category_slug) posts = posts.order_by('-date_posted') return render(request, 'stories/browse.html', {'posts': posts}) return render(request, 'stories/no_post.html') 4th code line makes it to show the posts when it has both school and category are set only. How could I use that line to be working with one filter is applied? -
not working running python manage.py rusnerver
when runninge that command python manage.py rusnerver i get this error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? i try to pip install mysqlclient and got that Command "C:\Users\xavi6\PycharmProjects\LES\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\xavi6\\App Data\\Local\\Temp\\pip-install-8q8y5ra6\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\ n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\xavi6\AppData\Local\Temp\pip-record-zvgp3gov\inst all-record.txt --single-version-externally-managed --compile --install-headers C:\Users\xavi6\PycharmProjects\LES\venv\include\site\py thon3.7\mysqlclient" failed with error code 1 in C:\Users\xavi6\AppData\Local\Temp\pip-install-8q8y5ra6\mysqlclient\ Im using pycharm and i think i try everything, pls help me. Thanks for help Andre. -
Formset invalid but 'Save' saves parent model and closes page
I've been using Django for a while - but I'm new to formsets. I have a formset 'payment' on a parent model 'invoice'. If the user enters a payment but forget the payment date (which is required) the page still saves the invoice and then closes. I can see from form_valid that formset.is_valid() is False. I can see the error raised if I print it in console: [{}, {}, {'paymentdate': ['This field is required.']}, {}]. I can even see the validation show up on the page right before is closes. How do I keep the page from closing when there is a validation error? -
How to check username exists or not in wiew.py without forms.py?
How to check username exists or not in wiew.py without forms.py, if USERNAME_FIELD = 'email' in Django settings? in models.py I create accounts model and USERNAME_FIELD = 'email' so now when I trying check username with User.objects.filter(username=username).exists() it returns email address, so how I can check if the username already exists in the database? -
How can I filter posts by user profiles with a certain field value? - Django
I am creating a blog application using Django and I would like to filter the blog posts using user profiles with a certain field value. For example, let's say that there is a field for professions in the profile model of the users, I would like to filter all the posts posted by doctors. Is this possible and if so, how would I achieve this? -
Django ModelChoiceField queryset filter from URL
I'm sure this is either a simple fix or I fundamentally misunderstand something. On this page, the current Store is determined via the url. I want to populate the ListingForm's choices with the Bonds that associated with that Store. Can someone help me achieve this properly? urls.py urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path('stores/<slug:anchor>', views.ListingView.as_view(), name='listing'), ] forms.py from django import forms from store.models import Bond class ListingForm(forms.Form): face_value = forms.ModelChoiceField(queryset=...) # this part is a problem def __init__(self, store, *args, **kwargs): super(ListingForm, self).__init__(*args, **kwargs) self.fields['face_value'].queryset = Bond.objects.filter(store=store) view.py class ListingView(FormView): template_name = 'listing.html' form_class = ListingForm success_url = '/checkout/preview' # todo anchor = None store = None queryset = None def get_form_kwargs(self): kwargs = super(ListingView, self).get_form_kwargs() kwargs['store'] = self.store def get_context_data(self, **kwargs): self.anchor = self.kwargs.get('anchor') self.store = Store.objects.filter(anchor_id=self.anchor).first() self.queryset = Bond.objects.filter(store=self.store) context = super(FormView, self).get_context_data(**kwargs) context['store'] = self.store context['store_bonds'] = self.queryset return context def form_valid(self, form): # save selected bond to session # redirect to success_url face_value = form.cleaned_data['face_value'] bond = Bond.objects.filter(store=self.store, face_value=face_value).first() if bond: self.request.session['bond'] = bond return super().form_valid(form) -
Django connect to securecrt
I am trying to open and send commands from Django to securecrt, my idea is to have use Django to communicate with securecrt and initiate commands and get the output 1-Django to open securecrt and initate ssh session to a specific server 2-Then send some commands to that server 3-Get the output to Django Why I need that way, I don't have access to run commands directly to server from Django, instead I have to login to jumphost server Is there a way to perform such action? -
How Can I get "pk" or "id" in 'get_context_data' from CVB ListView. thanks for your response in advance
class UserList(ListView): model = User def get_context_data(self, **kwargs): user = self.request.user.pk profile = self.get_object() #how to get the list object form here is_subscribed = False if profile.subscribe.filter(id=user).exists(): is_liked = True context = super().get_context_data(**kwargs) context['is_liked'] = is_liked return context am using Django 3.0 and python 3.8 how do I get an object from a ListView and check if its liked or not -
Since backend framwork like Flask have HTML template which can generate html pages, can people just use backend framework to replace frontend?
Since backend framwork like Flask have HTML template which can generate html pages, can people just use backend framework to replace frontend using the HTML template feature provided by backend framework (Jinja2)? When do people need to use a frontend framework like React.js? -
Is it possible to submit a form with same name inputs django
In my app I am not sure how many inputs I need for that form. So I create inputs on the fly using django template for loop. When I submit the form it only takes the last input of the same one's. I have another solution which is to create input name differently using for loop in django forms and it works but I am not sure how do I write these inputs in django template such as. {{ form.samename1 }} {{ form.samename2}} Is there a way I could concatenate strings on django template which create the above result using a for loop.? -
How to set permissions per handler function with APIView?
I am writing an API for a small school-related project using Django and Django-Rest-Framework. I am trying to figure out permissions. I am using APIView for my views, and am looking to set different permissions for each handler method without writing more views. Here is one of the views for the blog module that I have: (This view is used for /posts/) from .serializers import * from django.db.models import Case, When from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import permission_classes from rest_framework import status, permissions # Create your views here. class PostList(APIView): """ API Endpoint to List Posts METHODS: GET, POST """ @permission_classes([permissions.AllowAny,]) def get(self, request, format=None): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @permission_classes([permissions.IsAuthenticated]) def post(self, request, format=None): serializer = PostCreationSerializer(data=request.data) if serializer.is_valid(): obj = serializer.save() data = serializer.data data["id"] = obj.id return Response(data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) The current default is permissions.IsAuthenticated, though changing that would not necessarily help as I would still need to change some permissions individually. So I should be able to make a GET request while not authenticated to /posts/ and get a list of all posts, while I should get a 401 from a POST request to /posts/. … -
Django model problem : (fields.E304) Reverse accessor for a model clashes with reverse accessor for an other/same model
i'm writing a simple model`with a foreignKey field which refer to the author of a specific article but i got this error message when making migrations. I know the the problem will be solved by adding related_nameattribute to the field but i want to understand why is this happening ? thank you for your time SystemCheckError: System check identified some issues: ERRORS: articles.Article.author: (fields.E304) Reverse accessor for 'Article.author' clashes with reverse accessor for 'Article.author'. HINT: Add or change a related_name argument to the definition for 'Article.author' or 'Article.author'. users.Article.author: (fields.E304) Reverse accessor for 'Article.author' clashes with reverse accessor for 'Article.author'. HINT: Add or change a related_name argument to the definition for 'Article.author' or 'Article.author'. my articles.models file from django.db import models from django.conf import settings class Article(models.Model): title = models.CharField( max_length=250) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField() def get_absolute_url(self): return reverse("article_detail", kwargs={"pk": self.pk}) def __str__(self): return self.title -
Make Django Template Font Smaller if Object Long
I'm trying to get make my heading font smaller if there are more than 20 characters. For some reason it doesn't seem to render the smaller font when I have a long heading. <div class="col-12 col-md-9"> <a href="{% url "pmp:project_detail" project.id %}"> {% if project > 20 %} <h1 style="font-size:.7em;">{{ project }}</h1> {% else %} <h1>{{ project }}</h1> {% endif %} </a> </div> -
AttributeError: 'UserVote' object has no attribute 'model' in Django
Trying to add this voter class to a custom user model. I don't think I needed to create a custom model the way I did, but I'm already into it and I'd prefer not to start from scratch. Basically, I'm trying to create a matching system where two users can select yes or no to each other and then be matched. Anyhow, the migrations worked. But, when I go to add it to admin.py, I get " AttributeError: 'UserVote' object has no attribute 'model' " **Models.py ** from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager, User from dating_project import settings class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, description=description, photo=photo, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user class Profile(AbstractBaseUser): email = models.EmailField(verbose_name="email") username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = … -
Django-Filters : override method to allow property's model filtering
This is a model containing some field and a property carbs_g_secured : Models.py class Food(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) ingredients_label = models.TextField() moisture_g = models.DecimalField(max_digits=4, decimal_places=1, blank=True, null=True) def __str__(self): return self.name def carbs_g_secured(self): # If moisture is missing if self.carbs_g : return self.carbs_g,'Carbs provided' else : return None, 'Moisture is missing' I'd like to do some min/max filtering with django-rest-framework on the the carbs_g_secured property. I know I can't do that directly with Django-filters but I try to override the whole thing. I have the following approach : Serializers.py class FoodSerializer(serializers.ModelSerializer): carbs_g_secured = serializers.ReadOnlyField() class Meta: model = Food fields = '__all__' Views.py class FoodFilter(filters.FilterSet): carbs_g_secured_max = django_filters.NumberFilter(method='MyPropertyFilter') class Meta: model = Food fields = {'name': ['exact', 'in', 'startswith'], 'species':['exact'], 'protein_g':['exact','lte','gte'], 'carbs_g_secured_max':['exact']} def MyPropertyFilter(self, queryset, name, value): results = [row for row in queryset if value and row.carbs_g_secured()[0] and row.carbs_g_secured()[0] < value] return results Problem is this is returning a list where it's expecting a query set. web_1 | AssertionError: Expected 'FoodFilter.carbs_g_secured_max' to return a QuerySet, but got a list instead. So it seems I'm a bit stuck. I think it's not good practise to transform this list into query set. What do you guys … -
How to detect when HttpResponse(content_type='text/csv') is returned starts in Django Template?
I have a button in my template which when clicked converts a particular model to csv file and download begins. <a href="{% url 'down' %}" >Download csv File</a> The view: def down(request): allobj=resource.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="resources.csv"' writer = csv.writer(response) writer.writerow(['Name','Email','Resource']) for obj in allobj: writer.writerow([obj.name,obj.email,obj.resource]) return response Problem: I want to show a loading gif as the model is pretty big. I can start the animation when the link is clicked, but I need to know when to stop it. So is there a way to detect in the template when the response is returned or when the download begins? I know its easy to detect when a view has functioned successfully using Ajax, But how would I implement the downloadable link using ajax as it usually has a Json response but here I have a response = HttpResponse(content_type='text/csv') -
How to manage downloadable files in Django
In my Django application users can upload a PDF in the admin section. I would like these PDF files to be able to be downloaded on the public site. This works fine locally but in my production environment I get a 404 not found error for these files. I'm wondering what is the best way to serve these type of files so that they can be downloaded ? I have done some googling and seen some people mentioning that they should be hosted on another server. Is this the best approach or can they be hosted within the Django app for download ? Here are my settings for where these files are located : # Base url to serve media files MEDIA_URL = '/media/' # Path where media is stored MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
How to do RTL with django-easy-pdf
I'm using django-easy-pdf in a project to provide an output report. Works great. I'm just adding Hebrew to the languages available and I cannot get the output in RTL. I've tried a number of approaches to force RTL formatting including hard-coding html, body, p, table, tr, td, span { direction: rtl; } within the tags in base.html. Does django-easy-pdf support RTL and if so, how do I implement it? -
Could not parse the remainder: '==obj.id' from 'sobj.id==obj.id'
i am using nested for loop in django template to print data which i get from the data base {% if objectives %} {% for obj in objectives %} {% for sobj in sobjective %} {% if sobj.id==obj.id %} yes {% endif %} all the open tags are closed but its raising an error as i mentioned above TemplateSyntaxError at /objectives Could not parse the remainder: '==obj.id' from 'sobj.id==obj.id'