Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make None callable?
class ObjectCreateMixin: model_form = None template = None def get(self, request): form = self.model_form() return render(request, self.template, context={'form': form}) self.model_form is not callable How to make None callable? -
Django sitemap for multilanguage website posts filter
I try to seperate my post on lang. in sitemap. but But for example, if there are 3 languages (en,fr,de), each post three added in sitemap. example my_sample_post_english in db language option "en" my_sample_post_french in db language option "fr" my sitemap create like this; <url> <loc>http://127.0.0.1:8000/en/post/vote/my_sample_post_english</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> <url> <loc>http://127.0.0.1:8000/fr/post/vote/my_sample_post_english</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> <url> <loc>http://127.0.0.1:8000/de/post/vote/my_sample_post_english</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> how can i filter post for languages? i want like this; <url> <loc>http://127.0.0.1:8000/en/post/vote/my_sample_post_english</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> <url> <loc>http://127.0.0.1:8000/fr/post/vote/my_sample_post_french</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> <url> <loc>http://127.0.0.1:8000/de/post/vote/my_sample_post_deutsch</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> url.py urlpatterns += i18n_patterns( ... path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ... ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) sitemaps.py class BlogSitemap(Sitemap): priority = 0.5 # this generates urls per language i18n = True def items(self): posts= Post.objects.filter(private=False) for b in posts: if b.language == 'en': b.language = str('en/') + b.language if b.language == 'fr': b.language = str('fr/') + b.language if b.language == 'de': b.language = str('de/') + b.language return posts def lastmod(self, obj): return obj.created_date model.py class Post(models.Model): title = models.CharField(max_length=350,verbose_name="PostTitle") slug = models.SlugField(unique=True, max_length=353, null=True) language = models.CharField(max_length=30, choices=settings.LANGUAGES, default="en") private = models.BooleanField(blank=True, default=False, verbose_name="Private Post") def get_absolute_url(self): return reverse('post:addVote', args=[str(self.slug)]) -
Django to call the correct function
been searching a lot for fixing my issue.. New to django and might be missing a very simple logic here and looking for some help.. I have created a form in html page called thispage.html as below: <form action="{% url 'getvaluefromform' %}" method="POST">{% csrf_token %} <input type="text" name='mytitle' placeholder="enter title"> <input type="submit" value="save"> </form> then I updated views.py with the below code: from django.shortcuts import render def index(request): return render(request,'thispage.html') def getvaluefromform(request): mytitle = request.POST.get('mytitle') print(mytitle) return render(request,'thispage.html') finally my urls.py has this part: from dhango.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), path('getvaluefromform',views.getvaluefromform,name='getvaluefromform') ] Problem: when I use this I am able to get the input vallue however the url is changing to '/getvaluefromform' and when I remove 'getvaluefromform' from the url section and just keep it '' then the code view index gets picked up. Is there a way I can call the second function when button is clicked without moving to the new path. Please advise. P.S - I am deliberately not using a model form because I want to build a raw sql query based on user input and then run the query to get the results/ create a new table on the … -
create multible recored related to parent automaticaly django python
i want to do the following: 1- create one table contain all transactions of my project ==> table name "batch" ==> done 2- when i create new transaction in any model of my project it will create batch then create transaction and refere batch num in the transaction. ==> done ** the following is my problem: 3- i want after save re direct to the same page of creation instead of using url detail from get_absolute_url 4- also i want to complete in the same batch "in php usualy i redirect page to creationURL/Batch_Num then split Batch_number from url in view" here is my view code class Invoice(LoginRequiredMixin, CreateView): template_name = 'Create.html' form_class = InvoiceForm def form_valid(self, form): # Note: Create Batch number for new transaction batch_num, created = H010001.objects.get_or_create( table_name = "Invoice", created_by = self.request.user, updated_by = self.request.user, number_of_documents_created = 0, ) # Note: Create new transaction & assign batch numb form.instance.created_by = self.request.user form.instance.updated_by = self.request.user form.instance.batch_number = batch_num # Note: Increase Creation Document number of batch batch_num.number_of_documents_created += 1 batch_num.save() return super().form_valid(form) and here is my get_absolute_url code in model: def get_absolute_url(self): return reverse("detail", kwargs={ 'pk': self.pk }) -
Django Rest Framework : prefetch_related doesnot work as expected with serializer
I have two models class Book(models.Model): name = models.CharField(max_length=50) author = models.ForeignKey(Author) class Author(models.Model): name = models.CharField(max_length=50) then a prefetch_related queryset is created as follows Author.objects.all().prefetch_related("book_set") Then a serializer is created for the Author and book_set is added to serializer field like this class AuthorSerial(serializers.ModelSerializer): class Meta: model = Author fields = ('name' ,'book_set') But this only return list of book ids as nested serializer and not the rest of data with it such as name like below. { name:'john', book_set:[1,2,3] } Is there any way to solve this to get the data as name:'john', book_set:[{id:1,name:'Book 1'},{id:2,name:'Book 2'},{id:3,name:'Book 3'}] } Also what to do if I have to further filter these prefetch -
Unable to log in to django admin
I know this question has been asked before, but either I don't understand how to apply the solutions provided or they don't work. I think my case may be much simpler. I am a beginner with Django and I'm following first the djangogirls tutorial. I installed Django in a virtual environment that I created with conda. The first time I tried it, I was perfectly able to create a superuser and log in to the account successfully. However, that time I created the project in C:\Users\User\ and it was not very organized since there were a whole lot of files and folders there along with the project. Now, I created a second virtual environment and a new project, which is in F:, another partition of the same drive. I did everything I had done the first time, but when I tried to log in to the admin page, I get a message saying the credentials are incorrect. Actually, I created other two superusers (successfully), but always get the same message. I also created a third virtual environment and project (in the same partition where the OS is not), this time with pip, to follow exactly the same process in the … -
Pass the POST data through the views DRF
My problem is how to pass POST data through the class based views(DRF ApiView). I’m doing a multi step form, and views should have an access to the form data on all steps. The only limitation, I can’t use self.request.session. So summarizing all the information, how can I make my views more restful, that, for example, first step view give all the data to the second step view? If you need code examples, I’ll give it to you. -
The footer of the page is overlapping with the images django
I am trying to do a simple website were the images act like links to another template where you can watch a video, but the footer gets in the way, instead of staying at the bottom of the page it goes up and putting itself behind the pictures.and I am not sure why, I have been looking around but I could not find an clear answer. I am also still learning at the moment, in here you could find teh same questions but with some pictures so you can see what I mean. https://es.stackoverflow.com/questions/362790/the-footer-of-the-page-is-overlapping-with-the-images-django in order to keep the footer in place. I have to add a line of text which if the amount of pictures if odd it kind of stay in the site the html is {% extends "TresAcordesApp/base.html" %} {% load static %} {% block content %} <h1 style="text-align: center;"><p style="color: rgba(0, 95, 0, 0.8);">Temporada Cero</p></h1> <div style="width: 33%; float: left"> <h4 style="margin-left: 2.5cm; color: rgba(0, 95, 0, 0.8); ">Videojuegos</h4> <a href="{% url 'Videojuegos' %}"> <img title="Videojuegos" src="{% static 'TresAcordesApp/img/Videojuegos.jpg' %}" height="250px" width="250px" style="margin-left: 2.5cm;" alt=""> </a> </div> <div style="width: 33%; float: left"> <h6 style="margin-left: 2.5cm; color: rgba(0, 95, 0, 0.8); ">El Día Que Fleko Se Convirtio … -
Django - How do I annotate the count of multiple foreign key fields (within 1 model) to same model
I am trying to annotate the count of two foreign key fields, incorporation_country and acquired_country (both linked to Country model). The fields are within the same model (CustomerInformation). Below is my models.py for reference class Country(models.Model): country_id = models.AutoField(primary_key=True) country = models.CharField(max_length=500) class CustomerInformation(models.Model): customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) incorporation_country = models.ForeignKey('Country', related_name='customers_incorporation', on_delete=models.CASCADE, null=True, blank=True) acquired_country = models.ForeignKey('Country', related_name='customers_acquired', on_delete=models.CASCADE, null=True, blank=True) What I would want to accomplish is to get CustomerInformation.objects.all() and from there, annotate to get the count of each country for incorporation_country and acquired_country. For example, I would want the output to be something like : [{ 'country': 'Singapore', 'incorporated_count': 5, 'acquired_count': 3 }, { 'country': 'Taiwan', 'incorporated_count': 4, 'acquired_count': 7 }] All help is appreciated, thanks all! -
Django Ajax views.py cannot get the Object ID and returns 404 instead
Hi I am trying to ajaxify my comment function of my blog app in Django. Right now the code works fine except one part: I am not able to transmit the Object ID I want to access to my views.py file. When I hardcode the Object ID everything works fine. views.py file: (When I replace pk=request.POST.get('post_id') with the actual obj ID everything works!) @login_required def comment_create(request): post = get_object_or_404(Post, pk=request.POST.get('post_id')) user = get_object_or_404(User, username=request.user) comment_form = CommentForm() if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.author = user new_comment.save() else: comment_form = CommentForm() if request.is_ajax(): html = render_to_string('feed/comment_section.html', {'post': post}, request=request) return JsonResponse({'form': html}) The comment form in my html: <div> <form class="comment-form" action="{% url 'comment-create' %}" method="POST"> <div class="row"> {{ comment_form.as_p }} {% csrf_token %} <button type="submit" name="post_id" value="{{ post.id }}" class="btn btn-info">Submit</button> </div> </form> </div> My jQuery event handler: $(document).on('submit', '.comment-form', function(event){ event.preventDefault(); console.log($(this).serialize()); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'json', success: function(response) { $('#comment-section').html(response['form']); console.log($('#comment-section').html(response['form'])); }, error: function(rs, e){ console.log($(rs.responseText)); }, }); }); I tried various things but I do not know how I can make sure the post_id gets handed over to my comment_create() function.. -
Django POST IntegrityError at /add_trade/
I am currently getting into Django Forms which seems to be super cool basically. I tried to set up a quiet simple form to post some data to my database. Later on I will have a form that contains around 20 input fields of different types. Right now my approach raises the following error: IntegrityError at /add_trade/ ERROR: NULL-Value in column »balance« causes Not-Null-Constraint Although I did define all Model fields to blank=True HTML <form action="/add_trade/" method="POST"> {% csrf_token %} <div id="headline"> <div id="input_instrument_wrapper" class="headline_wrapper"> <input type="text" name="instrument" id="instrument_input" placeholder="Insert instrument"> </div> </div> </form> Models.py from django.db import models # Create your models here. class add_trade(models.Model): instrument = models.CharField(max_length=100, blank=False) sector = models.CharField(max_length=100, blank=True) [...] [...] margin_blocked = models.FloatField(max_length=20, blank=True) exposure = models.FloatField(max_length=20, blank=True) class Meta: db_table = 'planned_trades' Forms.py from django import forms from .models import add_trade class TradeForm(forms.ModelForm): class Meta: model = add_trade fields = ('instrument',) Views.py from django.shortcuts import render from .models import add_trade from .forms import TradeForm def add_trade(request): if request.method == 'POST': form = TradeForm(request.POST) # A form bound to the POST data if form.is_valid(): form.save() # saves a new 'add_trade' object to the DB Why is that? I didn't include the balance input field … -
Is it possible to generate 2 different login authenticators django
I am fairly new to django and I am trying to develop a web based game. I want the game to have 2 seperate log ins, one for a user log in and one for a character 'selection', obviously I can't go to the character selection without requiring the login_required decorator, but at the same time I want to make the rest of my website based upon the "character" and therefore I essentially need another login(character)_required, I was wondering if there is simpler way to do this rather than trying to rewrite djangos login functionality. I would appreciate it if I could be pointed in the right direction! -
Return variable from models.py to views.py other files
I made a form you have to fill out when uploading a file. Im using the email from the form to create a folder named after the email and i upload the file inside. In my models.py def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.email, filename) class User(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) pdf = models.FileField(upload_to=user_directory_path) def __str__(self): return self.title Im using user_directory_path to create the user_folder. I now want to do some processing on that data but i need that exact path. I have a separate file that does all the processing user_processing.py or a function inside views.py for example. In that file im importing models.py with from mysite.core.models import user_directory_path Im getting an error. ImportError: cannot import name 'print_filename' from 'mysite.core.Project_x' How do i import a function/ pass a variable from the models.py function into another file? -
Django - create profile for all existing users
i'm using Django 3 , this is my userprofile model from django.db import models from django.contrib.auth.models import User from datetime import datetime from django.db.models.signals import post_save from django.utils.text import slugify from django.db.models import signals # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=1000,blank=True) created_at = models.DateTimeField(default=datetime.now()) slug = models.SlugField(blank=True) img = models.ImageField(upload_to='userimg/',default='userimg/avatar.png') def __str__(self): return "%s" % self.user def save(self, *args, **kwargs): self.slug = slugify(self.user) super(Profile, self).save(*args, **kwargs) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.get(user=instance) post_save.connect(create_user_profile, sender=User) def delete_user(sender, instance=None, **kwargs): try: instance.user except User.DoesNotExist: pass else: instance.user.delete() signals.post_delete.connect(delete_user, sender=Profile) the problem is that the function create_user_profile create profiles only for the new users but doesn't create for the old users , so how can i fix that ? -
Filer Image Compression
How will I compress the images which are getting uploaded through Django-filer in Django cms? I already have the code for image compression but don't where to put in Django cms as I am new to it. -
Django auocomplete lgith shows duplicated forms
I'm using the package Django Autocomplete Light and the strange this it shows 2 of the same form Here is my code : Autocomplete View class ShiftAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Shift.objects.filter(employee__isnull=True) if self.q: qs = qs.filter(branch__name__icontains=self.q) return qs urls.py and here is how I created a URL for it : path('shift_autocomplete/', branches_views.ShiftAutoComplete.as_view(), name='shift_autocomplete'), forms.py here is where I used the autocomplete field in the form class ShiftAssignToEmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['salary', 'shift'] widgets = { 'shift': autocomplete.ModelSelect2(url='shift_autocomplete') } views.py class ShiftAssignToEmployee(SuccessMessageMixin, UpdateView): model = Employee form_class = ShiftAssignToEmployeeForm template_name = 'back_office/assign_shift_to_employee.html' success_message = _('Shift has been assigned successfully .') And finally the HTML : <form method="post" class="col s12"> {% csrf_token %} <div class="row"> <div class="input-field col s12"> {{ form.shift }} </div> </div> <div class="row"> <div class="input-field col s12"> <i class="material-icons prefix">chrome_reader_mode</i> {{ form.salary }} <label for="id_salary">{% trans 'Salary' %}</label> </div> <button type="submit" class="btn"> <i class="material-icons">send</i> {% trans 'Submit' %}</button> </div> </form> <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> {{ form.media }} so far so good, but the strange thing that in HTML there are 2 forms for the branch, once that looks like a normal SELECT widget with no options at all, and another one that … -
Login required in django
I am developing ecommerce website in django . I have view ( addToCart) I want sure before add to cart if user logged in or not so that i use @login_required('login') before view but when click login it show error (can't access to page ). Note that: normal login is working -
Django - delaying the form submission to prefill some data using javascript
I'm trying to fill in the latitude and longitude of my form with the geocode function which converts an address to latitude and longitude coordinates. I want my form submission to be delayed whilst the geocode function prefills the latitude and longitude fields. I know my geocode works because 'return false' fills the latitude and longitude fields in properly. Here is my delay code below: $('#form').submit(function() { geocode(); console.log('function ran.'); return true; }); Through experimentation by using 'return false', my console.log(Function ran.) prints before the console.log in my geocode function. I've tried using async functions but it still isnt' prefilling the fields quickly enough before form submission. $('#form').submit(async function() { await geocode(); //geocode isn't running fast enough; console.log('function ran.'); return true; }); async function geocode() { console.log("geocode"); } How do I correctly delay the return true function to execute after my geocode function has finished? -
How to pass a permission via Django Rest API?
I would like to create a custom permission that return true / flase depending on whether the user is the author of a story or not and pass this information via the restAPI. So when the author is requesting a story where he is not author the permission returns "false" and i can access these information IsStoryOwner: "False"via my API. Something like this should be the result: "user": { "id": 35, "username": "HII", "user_permissions": [ IsStoryOwner: "False", ] } However i struggle to implement that. I wrote the following permission: class IsStoryOwner(permissions.BasePermission): """ Check if authenticated user is story author """ def has_object_permission(self,request,obj,**kwargs): if request.user.id == story.author: return True return False Than i integrated the permission in my UserAPI class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, IsStoryOwner ] serializer_class = UserSerializer def get_object(self): return self.request.user However the permission is not appearing in my API and the "user_permissions": [] remains empty. -
Firebase Mutilple Item Upload not working
I need help to upload mutiple images in firebase for files in local_image: cloud_img = "images/example" + str(random.randint(1, 18596)) storage.child(cloud_img).put(files, user['idToken']) imgurl = storage.child(cloud_img).get_url(user['idToken']) def Convert(string): li = list(string.split(",")) return li urllist = imgurl # print(Convert(urllist)) x = Convert(urllist) data = { "name": name, "email": email, "phone": phone, "password": password, "image": x } print(x) results = db.child("users").push(data, user['idToken']) I am using python to push data but images url is saving only single url in databse please help me to figure it out -
ElasticSearch Autocomplete cleaning suggestions Django
I'm trying to make an autocomplete search for an application. I use django-elasticsearch-dsl with elasticsearch 7.x Instead of searching through documents title, I prefer to use a bunch of searched term saved like Google (I presume) models.py class SearchedTerm(models.Model): text = models.CharField(max_length=120, unique=True) def save(self, *args, **kwargs): """ Force lowercase for text """ if self.text: self.text = self.text.lower() models.Model.save(self, *args, **kwargs) document.py # Analyzer for searched term indexing my_completion_analyzer = analyzer('my_analyzer', tokenizer=tokenizer('trigram', 'edge_ngram', min_gram=3, max_gram=20, token_chars=['letter', 'digit']), char_filter=['html_strip'], # remove html entities filter=["lowercase", "snowball"] ) @registry.register_document class SearchedTermDocument(Document): completion = fields.CompletionField( attr='text', analyzer=my_completion_analyzer, fields={'raw': fields.KeywordField()} ) class Index: # Name of the Elasticsearch index name = 'searched_term' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = SearchedTerm # The model associated with this Document # fields to index # fields = ['text'] # None as using completion with special analyzer Get some Autocomplete suggestions: from apps.search.documents SearchedTermDocument es = SearchedTermDocument.search().suggest( 'autoc', 'sail boa', completion={ 'field': 'completion', 'skip_duplicates': True }}).execute().to_dict() [suggest['text'] for suggest in es['suggest']['autoc'][0]['options']] I get: [u' sail boat ', u'18 sail boat', u'ie sail boat', u'sail boat', u'sail boat'] Excpected result: [u'sail boat', u'18 sail boat', u'ie sail … -
Django - can't loop through custom templatetag
I've created custom categories_tag templatetag as follows: from django import template register = template.Library() from ..models import Category @register.simple_tag(takes_context=True) def categories_tag(context): categories = Category.objects.all() return categories And now want to loop through this tag like: <h3>CATEGORIES</h3> {% for i in categories_tag %} <a href="">i</a> {% endfor %} But in browser doesn't seem anything. What can be wrong with my code ? -
Wagtail: Getting 404 when using django-allauth and Wagtail?
I'm trying to setup login, logout functionality following this tutorial. In there the instructor shows where to put the url(r'', include('allauth.urls')) however he puts it above this line,url(r'', include('wagtail_urls')) that I don't see in my urls file for my project app. Notice that his url path is empty '', but then he goes to localhost/login and get a loginpage, that acording to him is provided by Wagtail. I don't get that, but a redirct to a 404 error page. What should I do? My Wagtail site works perfect, I can create pages, snippets, etc. /mysite/urls.py: from django.conf import settings from django.conf.urls import include, url from django.urls import path from django.contrib import admin from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls from search import views as search_views urlpatterns = [ url(r'^django-admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = urlpatterns + [ # For anything not caught by a more specific rule above, hand over to # Wagtail's page serving mechanism. This … -
How do I get the text and img of the "div contenteditable" and save it on the server?
How do I get the text and img of the "div contenteditable" and save it on the server, and then paste its information from the server to another div with i use django? HTML: div class="text_area_input" contenteditable id="text_area"> </div> JS is put img to "div contenteditable" JS: -
How to push data from several HTML input fields to Django database
I have an application that uses around 20 input fields (type text and number, some select) to make some calculations on the client-site. I would then like to push this entire data on click of a submit button to my Django database into a single table/model. How to accomplish this? Do I have to transpose each input field into a html form and then grab all of the html input fields data within a single view? Additionally do I need Django forms at all if I don't need to render the forms from the backend instead just having them in my html template pre-defined? Is it smart to fire an AJAX call to trigger the view or is it more convenient to directly post the data to the backend? (So I would need to create a custom submit button?) My html looks like the following right now: <div class="formsBox" id="formsBoxConsideredRisk"> <div class="formLabel"> <p class="formLabel">Risk & Underlying</p> </div> <div class="formMain"> <div class="riskContainer"> <input type="number" class="formInputRisk" id="formInputriskInPercent"> <p id="riskPercentText" class="riskText">Risk in %</p> </div> <div class="riskContainer"> <input type="number" class="formInputRisk" id="formInputriskInFiat"> <p id="riskFiatText" class="riskText">Risk in $</p> </div> <div class="riskContainer"> <select name="Underlyings" id="underlyings"> <option value="Shares">Shares</option> <option value="Gold">Gold</option> <option value="Silver">Silver</option> <option value="Oil">Oil</option> <option value="Indices">Indices</option> <option value="Other">Other</option> …