Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
One model with 2 categories in Django. How do I display another category from the same model in html?
I've created a class Product in models.py where I have 2 categories. I successfully displayed in my html page the category connectors but not the software which I left commented to see the data properly in html. How can I display the software category in html properly as I did with connectors? Thanks in advance for any tips! class Products(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=250) short_description = models.CharField(max_length=100) longDesc = models.TextField() category = models.CharField(max_length=50) version = models.DecimalField(max_digits=2, decimal_places=1) picture = FilerImageField(null=True, blank=True, related_name="products_image") def __str__(self): return self.title class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' The views.py contains the following code: def products(request): objconnectors = Products.objects.all().filter(category__iexact='connectors') contextconn = {'connectors': objconnectors} # objsoftware = Products.objects.filter(category__iexact='software') # contextsoft = {'software': objsoftware} return render(request, 'website/products.html', contextconn, contextsoft) The html file contains a loop to display all the data from the Products model, category Connectors. {% for products in connectors %} <div class="products animated delay1" data-effect="fadeInUp"> <div class="connectorWrap"> <div class="productsTitle"> <img src="{{ products.picture.url }}"> </div> <div class="textBox"> <h3>{{ products.title }}</h3> <p class="connDesc">{{ products.short_description }}</p> <p class="versionNumber">{{ products.version }}</p> </div> </div> </div> {% endfor %} -
Removing extra Icons in django forms
I'm adding various search and filter options through forms in my django application. Although everything's working fine, I'm getting an extra double arrow heads in all of the fields: I want to remove these arrowheads from some if not all of the fields. This is what the html looks like ... <form class="form-inline" method ="GET" action ="{% url 'filter' %}"> <div class="col-md-4 col-lg-4 mb-3"> <label for="q">Keyword Search</label> <input class="custom-select shadow-sm" style="padding-left: 28px; width: 20em;" name ="q" value ="{{ request.GET.q}}" placeholder="Search books by title or author..."> </div> <div class="col-md-2 mb-3" style="max-width: 250px;"> <label for="genre">Book Genre</label> <select class="custom-select shadow-sm w-100" id="genre" name ="genre" > <option value="">All</option> {% for g in genres %} <option >{{g}}</option> {% endfor %} </select> </div> ... This possibly is due to the custom-select class. Let me know how to update the form/class. -
Posts not showing author who wrote it in Django
Basically, I'm writing an app in which people can make blog and image posts. So far, I've completed users to be able to write text posts. However, when I try to create a post, it returns "By: None" when it should be returning "By: shrey". In this case, Bob is the author. Here's an image: Here's an image for the post creation view: Theoretically, when I enter a post it should say who it was written by. Here's the template for the create post: {% extends "social/base.html" %} {% load crispy_forms_tags %} {% block content4 %} <h1>Make Your Post</h1> <p>Write a post / Share an image</p> <br> <div class="container"> <form method="post"> {% csrf_token %} {{form|crispy}} <button type="submit" name="button">Make Post</button> </form> </div> {% endblock content4 %} Here's the function for the create post view: class PostCreateView(CreateView): model = Posts fields = ['post_title', 'post_text_content'] def form_valid(self, form): form.instance.author = self.request.user print(self.request.user) return super().form_valid(form) Thank you in advance. EDIT: Home Page Template (template which displays the posts): {% extends "social/base.html" %} {% block content %} <h1>Your Feed</h1> <p>This is your feed. Here, you'll see posts from people you follow.</p> {% if user.is_authenticated %} <p>You are logged in as {{user.username}}. This is your feed.</p> … -
Highlight Django Search result
This is my Model class Acsd(models.Model): sequence = models.IntegerField(primary_key=True) country = models.CharField(max_length=60, blank=True) description = models.CharField(max_length=2000, blank=True) class Meta: verbose_name = 'acsd' verbose_name_plural = 'acsd' This is my view class SearchResultsView(ListView): model = Acsd template_name = "search.html" context_object_name = 'search' paginate_by = 25 def get_queryset(self): query = self.request.GET.get('q') object_list = Acsd.objects.filter( Q(description__icontains=query) ) return object_list def get_context_data(self, **kwargs): context = super(SearchResultsView, self).get_context_data(**kwargs) context['result_string'] = self.request.GET.get('q') return context and this is my template <div class="row"> {% for acsd in search %} <div class="col-md-2 " style="margin-top: 10px;"> <b>{{acsd.description}}</b> </div> </div> I want to highlight the line containing the search string/phrase. And also want to show the previous and later line of that string/phrase containing line. If I need to change my search mechanism, please suggest that too. Something like google does. If we search "The Superhero", the results will make search string bold in the content. -
Heroku set default site
I have created a new Heroku site and I am developing it on my Linux box, using Django. The standard "getting started" site Heroku created for me is called "gettingstarted". How can I change that / configure Heroku to forget about it? I was reading through the Django tutorial, which explains how to create a new site (django-admin startproject my_site). I did this successfully for a demo project. Then I tried to do it under the Heroku directory, because I wanted a better name for my site than "gettingstarted". I noticed that every time I start the Heroku server under my project, it says ...using settings 'gettingstarted.settings'. I found that this is configured in manage.py and I change it. This is the directory layout I have /some/path/heroku_random_name/gettingstarted/settings.py /some/path/heroku_random_name/my_site/settings.py /some/path/heroku_random_name/my_app This is what I have in /some/path/heroku_random_name/manage.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_site.settings') so I would expect that the site that matters is my_site. I got it to the point where I can run the site successfully on my local machine, and I can tell that it using the settings from my_site. But when I deploy the project to Heroku, it does not recognize my_app until I register it in gettingstarted/settings.py. In other words, when … -
Django Multi Column Primary and Foreign Key usage example needed
I am trying to have a implementation in Django models where Table A will have 5 columns, say like table1 : (column1, column2, column3, column4, column5) where i want column1, column2 to act as composite primary key instead of Id column of django table 2: (column6, column7, column8, column9, column10, column 11) where column6, column7 are foreign keys which refer to primary keys of column1, column2 in table 1 and which also act as composite primary keys in table 2. How can i achieve this in Django, so that as a admin user i can add data to table 1 and also add data to table 2, where first two columns of table 2 i.e column6, 7 is autopopulated with column1, 2 data when i want to add data to table 2. Is this possible in DJango, if yes pls provide concrete working example? -Ajay -
React axios post error: "Request failed with status code 404"
I am creating a front-end app in react with the back-end in django and using djangorestframework. Here I am working on plain form submission by calling an API endpoint. I am using axios to make the post request. I have put the axios method withing handleSubmit() method: handleSubmit(event){ event.preventDefault(); const data = { first_name: this.state.first_name, last_name: this.state.last_name }; axios.post('http://127.0.0.1:8000/profile/create/', data) .then(res => console.log(res)) .catch(err => console.log(err)); }; On the back-end i am using the generics.CreateAPIView view: class CreateProfile(generics.CreateAPIView): serializer_class = ProfileSerializer The url: path('profile/create/', CreateProfile.as_view()), When I am submitting the form this error is showing in the console: Error: "Request failed with status code 400". What am i doing wrong? -
django data base filter by method
I have a Django model with a method determines if I need to use it or not. I want to filter the table by the value returned from this method. something like this: filter(object.method()) Is it possible to do something like this? -
Why does Django caching cause CSRF violation and faulty template rendering?
I am using Django with Memcached in production and as far as I can tell, the caching system seems to work fine, however, it causes certain errors in my application: Whenever a form is submitted, I get a CSRF error, because for some unknown reason the CSRF token gets cached. My templates are also not rendering correctly, for example, when a user is logged in I have a conditional in my template that checks if the user is authenticated, but when viewing the page, the template doesn't get updated and is still showing the cached version. If anyone knows what is going on here and how I can fix this, please let me know. -
Django CustomUserModel email field case sensitive
Email field in the Django(3.0) Custom User Model is case sensitive, I tried various ways to make it case-insensitive but no success so far. Code forms.py class UserCreationForm(UserCreationForm): class Meta: model = User fields = ('first_name','last_name','username','email','password1','password2') class UserChangeForm(UserChangeForm): class Meta: model = User fields = ('first_name','last_name','username','email',) class UserUpdateForm(forms.ModelForm): ''' model form are the form that work with specific user model ''' class Meta: model = User fields = ('first_name','last_name','username','email',) class ProfileUpdateForm(forms.ModelForm): ''' model form are the form that work with specific user model ''' class Meta: model = Profile fields = ['image'] manager.py class UserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password=None): if not email: raise ValueError('Must have Email') if not username: raise ValueError('Must have username') if not first_name: raise ValueError('Must have first_name') if not last_name: raise ValueError('Must have last name') user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, password=None): user = self.create_user( email=email, username=username, first_name=first_name, last_name=last_name, password=password, ) user.is_active = True user.is_staff = True user.is_admin = True user.is_superuser = True user.save(using=self._db) return user Things already tried One of the very obvious things to try is to make email lowercase in manager.py before any authentication and so I did like … -
Delete rows set to be deleted in a formset
I know this question has been asked before (e.g. Django modelformset_factory delete modelforms marked for deletion) but I've tried all the possible solutions, including doing what the official documentation says (https://docs.djangoproject.com/en/3.0/topics/forms/formsets/), and I still cannot delete the forms from my formset. I have a form which correctly sends POST data with everything I need (including the DELETE instruction). [print(form_links_event.cleaned_data) for form in form_links_event.deleted_forms] [{'description': 'asdasd', 'link': 'http://www.test.com', 'id': <linksEvent: linksEvent object (25)>, 'DELETE': True} Nevertheless, I need to process the formset before saving all the instances (I need to attach the id of a related model), so I need to call save(commit=False): instances_links_event = form_links_event.save(commit=False) for link in instances_links_event: link.event = instance_event link.save() form_event.save() form_links_event.save() Doing so, though, strips the .deleted_forms list. In fact: [print(instances_links_event.cleaned_data) for form in instances_links_event.deleted_forms] AttributeError: 'list' object has no attribute 'deleted_forms' Therefore I'm stuck in a loop: I cannot save my form directly because I need to attach more data to it first, and in its raw state it has the 'deleted_forms' list. Once I save it with commit=False and process with the processing, though, the 'deleted_forms' is not there any more so that I cannot delete those rows set for deletion. Ideally, I'd like … -
How to assign custom color in google column chart based on value (Django)
I have values : m=72 n=34 z=59 I got the following google column chart : <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load("current", {packages:['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ["Apple", {{m}}, "green"], ["Orange", {{n}}, "red"], ["Grape", {{z}}, "orange"],); var view = new google.visualization.DataView(data); view.setColumns([0, 1, { calc: "stringify", sourceColumn: 1, type: "string", role: "annotation" }, 2]); var options = {title: "Fruits",width: 1000, height: 400, bar: {groupWidth: "95%"},}; var chart = new google.visualization.ColumnChart(document.getElementById ("columnchart_values"));chart.draw(view, options);} </script> <div id="columnchart_values" style="width: 900px; height: 300px;"></div> i want to color values m,n or z in the following way: if value (m,n or z) more than 70 color green if value (m,n or z) more than 50 but less than 70 color orange if value (m,n or z) less than 50 color red I am not good with js just learned to copy pasted and modify ready code however in this case I do not how to customise colors of columns based on conditions. Any help is appreciated. -
Displaying a bookmark button in html using django-siteflags
So I'm going through this documentation and trying to use siteflags to bookmark an article. In the end I want to be able to click an icon to bookmark then have it switch to a solid color once it's bookmarked and I'm confused on how to post to the bookmark_set function. I've tried passing the function to the action of the form with no avail. I hope I'm asking the right way. If anyone can help I will appreciate it. urls.py: path('article/<int:article_id>/', views.article_detail, name='article-detail'), views.py: from django.shortcuts import render def index(request): return render(request, 'index.html') from django.shortcuts import get_object_or_404 from .models import Article def article_detail(request, article_id): article = get_object_or_404(Article, pk=article_id) user = request.user # Let's suppose we have here only logged in users. is_bookmarked = article.bookmark_check(user) all_flags = article.get_flags(user) post = request.POST if post.get('bookmark_set'): # Now a user reports this article as a fake. article.bookmark_add(user, note=post.get('bookmark_message')) elif post.get('bookmark_remove'): # Or he removes a fake flag. article.bookmark_remove(user) context = { 'article': article, 'is_bookmarked': is_bookmarked, 'all_flags': all_flags, } return render(request, 'article-detail.html', context) html: {{ article.title }} {{ article.content }} {% if article.is_bookmarked %} Yes! {% else %} No! {% endif %} <form class="form-inline my-2 my-lg-0" action="{{ bookmark_set }}" method="POST"> {% csrf_token %} <input … -
How to access value in class' atribute in models.py Django
I would like to change username and question using my function in views.py. I have this code in models.py: class Choice(models.Model): username = models.ForeignKey(Users, null=True, on_delete=models.CASCADE) question = models.ForeignKey(Questions, null=True, on_delete=models.CASCADE) answer = models.CharField(null=True,max_length=50) and I would like to change username inside the choice using this line: if username == str(Users.objects.latest('name')): Choice.objects.username = Users.objects.latest('name') Propably there is some variation of Choice.objects.something that might retrieve value in 'username' and let me change it but I don't know about it. -
How to organize recursive m2m relation in Django?
I am developing a mentorship platform. The stack is Django and Postgres. I have a question about the hierarchy of DB for mentorship platform. There are 2 user types: Mentor and Menti. User can't be a mentor and a menti at the same time. I think to set DB hierarchy as following: 1) Create User table to store main info for authentication functionality, like email and password. 2) Create Profile table and link it to User table with one to one relation, where I will store other information 3) Add a "role" column in Profile table with 2 options: mentor and menti. Add MentorInfo and MentiInfo tables and link them with one to one relations to Profile table. mentiInfo column in Profile table will be null for mentors, and mentorInfo column in Profile table will be null for mentees. 4) Relation between mentors and mentees will be organized with recursive many to many relation in Profile table Is everything right? What can I improve in my approach? Thank you in advance -
URL patterns and how to use them for external link django
Inexperienced with Django, but I have been playing with the Reddit API and it is easy and fun to use. I think I don't understanding something fundamental about template tags and urls in Django. All I really want to do is to have an href link to 'http://redd.it/' with the reddit id for the post after the slash. My model is: class Reddit_Model(models.Model): reddit_title = models.CharField(max_length=500,default='') reddit_score = models.CharField(max_length=20,default='') reddit_id = models.CharField(max_length=20,default='') reddit_url=models.URLField(blank=True,max_length=500) And in the template if I use: <a href="{{ entry.reddit_url }}">{{ entry.reddit_url }}</a> I connect to the external URL as expected. However that URL can be the external URL that someone put in their post, so if I want to go back to the persons post (for example a post that has a reddit_id of ge2oap) and I type into the browser http://redd.it/ge20ap it will go to the post as desired. However when I try to construct a template tag I run into problems. if I use <a href="{{http://redd.it/{{entry.reddit_id}}}">http://redd.it/{{ entry.reddit_id }}</a> and got http://127.0.0.1:8000/mainapp/'http://redd.it'%20ge2oap which I think makes sense, so I tried various URL template tag patterns <a href="{% url 'http://redd.it/' entry.reddit_id %}">http://redd.it/{{ entry.reddit_id }}</a> none of which work. I suppose I could create another field in … -
How to store data jn the template, taken from the user django framework
I am buliding an website which create cv's. I have 5 cv templates. Now want data from user in a form like Name.. Address... Phone number.. And show that data in the template which is selected by the user.. So how can i do that ... -
Authenticate with only username
I creating quiz app, in which user login with only username and the proceed for a quiz but django authenticate not working views.py class UserFormView(View): form_class = UserForm template_name = 'app/registration_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # cleaned data username = form.cleaned_data['username'] user.save() # autheticate user = authenticate(username=username) if user is not None: if user.is_active: login(request, user) return redirect('app:quiz_list') else: return HttpResponse('active nahi hai') else: return HttpResponse('pehchan me nahi hai') return render(request, self.template_name, {'form': form}) -
I am quite confused which framework to learn for python. AS per the demand and job opportunity [closed]
I am just confused so I want the suggestion. I just want to create restful api . So in Django, there is Django rest framework and also there is flask to only create rest API ........ can anyone suggest which one to learn for rest API as per the demand and job offer I am quite confused about it -
nginx allows https inside server but not outside
I've a Django web app running using Waitress as a server. The server's firewall is set to allow HTTPS inbound traffic. However, with the settings described below I cannot access the HTTPS site outside of the server itself. Yesterday I had no issue accessing the HTTP site just fine. This issue only occurred once I included the HTTPS settings. Am I missing something? The project's settings.py include ## SSL SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True and the my project conf file includes # Redirect all non-encrypted to encrypted server { listen 80 default_server; server_name mysite.net; # substitute your machine's IP address or FQDN return 301 https://$server_name$request_uri; } server { server_name mysite.net; listen 443 ssl; # <- ssl_certificate C:/nginx-1.17.10/ssl/mysite_net.crt; ssl_certificate_key C:/nginx-1.17.10/ssl/mysite_net.key; access_log C:/nginx-1.17.10/logs/access.log; error_log C:/nginx-1.17.10/logs/error.log; location /static { alias C:/Users/batch_job/project/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { proxy_pass mysite.net:8001; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; # <- proxy_set_header Host $http_host; proxy_redirect off; } } -
Django Views.py - POST Request On 2nd Page Returns To New Instance Of Previous Page
This is probably just me from staring at the code all day and making numerous changes, but I'm presently running into an issue when pressing the 'Deploy' button on my 'confirmation' page: it seems to create a new instance of the first page form. Instead, I simply want it to print to the console and do nothing else (for the time being). My Views.py file looks like this: from django.shortcuts import render from .projectform import ProjectForm from .projectconfirm import ProjectConfirm def projectcreation(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): request.session['projectname'] = form.cleaned_data['client'] + "-" + form.cleaned_data['stage'] + "-" + form.cleaned_data['purpose'] request.session['computeapi'] = form.cleaned_data['computeapi'] request.session['deploymentmanapi'] = form.cleaned_data['deploymentmanapi'] request.session['storagecompapi'] = form.cleaned_data['storagecompapi'] request.session['monitorapi'] = form.cleaned_data['monitorapi'] request.session['loggingapi'] = form.cleaned_data['loggingapi'] confirmform = ProjectConfirm(request=request) return render(request,'projectconfirm.html', {'form': confirmform}) else: form = ProjectForm() return render(request, 'projectform.html', {'form': form}) def projectconfirm(request): if request.method == 'POST': form = ProjectConfirm(request.POST) if form.is_valid(): projectname = form.cleaned_data['name'] print("Now beginning deployment of project " + projectname) else: form = ProjectConfirm(request=request) return render(request, 'projectconfirm.html', {'form': form}) When adding the following to the projectcreation function, it prints to the console without an issue: print("This is a test.") So, I'm not sure why this works for the first function but not for the second. … -
How can i save images in sub directory in media?
in first step i have primary key in user field,then in second step in complete info in site image save,i want to uplaod image in this path: /photos/user_id/file.png class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) personal_image = models.ImageField(upload_to='',blank=True) gender = models.IntegerField(default=0) birth_date = models.CharField(max_length=12) i want to upload image in sub directory that name is user_id -
getting the IntegrityError Message in Django view
I Have a complex model with 6 constrains and i want to get a message to the user which constrain failed when the post-request fails. class testView(APIView): @staticmethod def post(request): serializer = testSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) try: testModel.objects.create( # all the data ) return testView.get(request) except IntegrityError: return Response(status=status.HTTP_403_FORBIDDEN) The exception is called but I cant find the specific constrain that faild in the IntegrityErrorclass. Is there any way to return the specific Constrain to the User? (iam using django 3.0.2 with Postgresql) -
Malformed json on the front end: e = SyntaxError: Unexpected end of JSON input
I verified the returned from Django server json in jsonlinter (https://jsonlint.com/) and it is correct. Backend log output does not have any errors, but on the front end I am getting either very long waiting time or an error: e = SyntaxError: Unexpected end of JSON input When I looked into the requests' json in the network tab (Chrome) I see the following at the end: "projectGuid": "R0021_test", "project_guid": "R0021_test", "sampleGuids": [], "sex": "M" }, "I0000238_s0049336_cidr": { "affected": "A", "caseReviewDiscussion": null, "caseReviewStatus": "I", "caseReviewStatusLastModifiedBy": null, ------> "caseRevieError occured while trying to proxy to: localhost:3400/api/project/save_table/f5105 As you can see the last line of the json got messed up and thats', I guess, the reason for the error. Probably its due to the fact that json is pretty big: 92Kb, not sure... What could be the possible issue here, and where should I try looking for? -
Django ORM Optimisation - annotating by count as well as the last entry for the annotate filter
I currently have the following property on a Post model: @property def compliments(self): compliments_by_kind = list( self.compliment_set.values( 'kind' ).annotate( amount=Count('kind') ).values( 'kind', 'amount' ) ) for compliment_by_kind in compliments_by_kind: compliment_by_kind['last_giver'] = self.compliment_set.filter( kind=compliment_by_kind['kind'] ).order_by( 'created' ).last().giver.name return compliments_by_kind This returns the following listing data structure: [ { 'kind': 'unique', 'amount': 3, 'last_giver': 'Person 1' }, { 'kind': 'fresh', 'amount': 2, 'last_giver': 'Person 2' }, { 'kind': 'concept', 'amount': 3, 'last_giver': 'Person 3' }, { 'kind': 'lines', 'amount': 1, 'last_giver': 'Person 4' } ] There's nothing wrong with the data, per se. There's just nothing right with ther performance of performing Queries within the loop. However, the looping method - is not efficient - for each kind (which there are 6 in total, there are 6 further queries on top of the one to get the Count annotation. So, this really hampers performance on the serialization stage. Would anyone know how to perform the annotation for the latest Compliment "giver.name" according to the ordering by "created" attribute according the the "kind" ... i.e., the last person to give a compliment of "kind" unique etc etc Here is the Compliment model: class Compliment(TimeStampedModel): giver = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name="giver", ) receiver …