Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django HTML5 data list show option instead of value
I have used this thread Django form with choices but also with freetext option?. my code is below. It is working fine. The problem is after select the id is displayed in the input field. I want to show after select the code and name from the model instead of the id. Please help. fields.py from django import forms from django.utils import formats class ListTextWidgetselect(forms.Select): template_name = 'listtxt.html' def format_value(self, value): # Copied from forms.Input - makes sure value is rendered properly if value == '' or value is None: return '' if self.is_localized: return formats.localize_input(value) return str(value) class ChoiceTxtField(forms.ModelChoiceField): widget=ListTextWidgetselect() listtxt.html file <input list="{{ widget.name }}" {% if widget.value != None %} name="{{ widget.name }}" value="{{ widget.value|stringformat:'s' }}" {% endif %} {%comment%} {% include 'django/forms/widgets/attrs.html' %}>{%endcomment%} {% for name, value in widget.attrs.items %} {% if value is not False %} {{ name }} {% if value is not True %} ="{{ value|stringformat:'s' }}" {% endif %} {% endif %} {% endfor %}> <datalist id="{{ widget.name }}"> {% for group_name, group_choices, group_index in widget.optgroups %}{% if group_name %} <optgroup label="{{ group_name }}">{% endif %}{% for option in group_choices %} {% include option.template_name with widget=option %}{% endfor %}{% if group_name %} … -
Path include() shows 404 in Django
first of I want to apologize if I use the wrong terms or words in my question. I'm completely new to Django and got only a few months of experience with python. I hope you can understand my question anyways. I also want to acknowledge the fact that I'm using some imports that are not needed here and might not be relevant to the latest version of Django, I'm starting to get lost in all the things I've tried from other threads to solve my problem. I'm having some problems with showing a page from apps url. I'm getting redirected to my homepage when trying to reach localhost:8000/articles (because /articles gives 404 error) I'm not sure exactly what code I need to include here, so bear with me. articles/urls.py and articles/views.py from django.conf.urls import url from django.urls import include, path from django.conf.urls import include, url from django.urls import path from .import views urlpatterns = [ path('^$', views.article_list), ] from django.shortcuts import render from django.http import HttpResponse # views def article_list(request): return render(request, "articles/article_list.html") The project's urls.py and project's views.py from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.urls import include, path from django.conf.urls import … -
Reverse for 'user/placeholder/traffic_request' not found. 'user/placeholder/traffic_request' is not a valid view function or pattern name
I am trying to store data. My url is: action="{% url 'trafficapp:traffic_request' %}" Even though traffic_request exists in view.py file, it is unable to locate it. My template directory is setup like this: templates trafficapp >admin otherfiles.html >user placeorder.html otherfiles.html Since it isn't directly in the trafficapp, it is unable to locate. I tried finding solution to resolve it but unable to do it. Kindly help. -
django - how to automatically get author name while post
I want to automatically get the author name without selecting it. I am using class based views in order to create a post. post/models.py class BlogPost(models.Model): title = models.CharField(max_length = 50 , null=False,blank=False) body = models.TextField(max_length = 5000 , null=False,blank=False) date_published = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL,default=1,on_delete=models.CASCADE) #slug = models.SlugField(blank=True,unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post:article-detail', args=(self.id,)) post/views.py class AddPostView(LoginRequiredMixin,CreateView): model = BlogPost template_name = "post/add_post.html" #fields = '__all__' form_class = CreateBlogPostForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) post/article-detail.html <div class="card m-auto""> <h1>{{post.title}}</h1> <small>by:{{post.author}}</small><br/> <hr> <br/> <p>{{post.body}}</p> <br/> </div> -
Django-Admin OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
I am trying to display an image in the admin panel of a django-website. I keep getting this error. The traceback suggests the error is in this line: query.LoginData.screenshot.save(screen_url, File(open(screen_url, 'rb'))) Where query is the model instance. Printing out the screen_url gives me: C:/Users/admin/PycharmProjects/TestingModule/TestingModule/media/LoginTests/praty.png What could be the possible error and workaround? -
"[WinError 10061] No connection could be made because the target machine actively refused it"
I suddenly started getting the above error message and had absolutely no reason why. I speculated that my database was corrupt and deleted it and started again. When that failed I reviewed my firewall sections. I turned them all off and the problem still persisted. -
Django send email - email form
I created a contact form to send me an email when the user fills it out. Everything appears to be working, I get mail to my gmail but I get it from myself, not from filled "email form". For example I fill out my form in my website: Subject: TEST Email: test@gmail.com Message: Hello When I check my gmail account I got my message: from Email: admin@gmail.com - ? to Email: admin@gmail.com date: 17 Sep 2020, 14:05 subject: TEST mailed-by: gmail.com Message: Hello my forms: class EmailForm(forms.Form): subject = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Your subject'})) email = forms.EmailField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Your email'})) message = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Your message'})) my views: def contact(request): form = EmailForm() if request.method =="POST": form = EmailForm(request.POST) if form.is_valid(): subject = request.POST['subject'] message = request.POST['message'] email = request.POST['email'] send_mail( subject, message, email, ['admin@gmail.com'], fail_silently=False, ) context = {'subject':subject} return render(request, 'base/contact.html', context) context = {'form':form} return render(request, 'base/contact.html', context) my settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'admin@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS = True -
Django "AttributeError: Manager isn't accessible" when using custom save with many-to-many field
In models: class Foo(models.Model): text = models.TextField() class Bar(models.Model): def save(self, *args, **kwargs): while not self.id: new_id = ''.join(random.choices(string.digits, k=8)) if not self.objects.filter(pk=new_id).exists(): self.id = new_id super().save(*args, **kwargs) header = models.TextField() foos = models.ManyToManyField(Foo) In the shell: from app.models import Foo, Bar foo1 = Foo(text="This is foo 1.") foo1.save() foo2 = Foo(text="This is foo 2.") foo2.save() bar = Bar(header="This is bar.") bar.save() bar.foos.add(foo1) bar.foos.add(foo2) Gives the error: Traceback (most recent call last): File "<console>", line 1, in <module> File "...proj/app/models.py", line 12, in save if not self.objects.filter(pk=new_id).exists(): File ".../django/db/models/manager.py", line 179, in __get__ raise AttributeError("Manager isn't accessible via %s instances" % cls.__name__) AttributeError: Manager isn't accessible via Bar instances The same commands work in the shell if I remove the custom "save" method from the model. -
API DRF coreapi docs CSRF token
Hello. When I'm on my coreapi docs route and when I try to send POST I get this CSRF. How I can handle this issue? I'm using pydanny/cookiecutter-django -
How to support multiple languages field in same model?
I have a model somthing like this: class MyModel(models.Model): document = models.FileField(upload_to='my_path', max_length=511) # other fields Now we are adding support for another language (say French). For this we need to save document in French language. I might add a field french_document, but what if we add another language in the future, we will again need to save document in that language. So, is there a way to support multiple languages document, without having to create extra field in the model? PS: Is this possible to do so without creating another model to save the documents, and using MyModel only? -
What is def __str__(self) in django(python)
in my model: class OrdersStudent1(models.Model): obj = models.ForeignKey(OrdersStudent, related_name='obj', on_delete=models.CASCADE, null=True) groupid = models.IntegerField(db_column='groupid' ,blank=True, null=True) UserId = models.IntegerField(db_column='UserId', blank=True, null=True) # Field name made lowercase. Name = models.TextField(db_column='Name', blank=True, null=True) # Field name made lowercase. This field type is a guess. Family = models.TextField(db_column='Family', blank=True, null=True) # Field name made lowercase. This field type is a guess. Lat = models.FloatField(db_column='Lat', blank=True, null=True) # Field name made lowercase. This field type is a guess. Long = models.FloatField(db_column='Long', blank=True, null=True) # Field name made lowercase. This field type is a guess. id =models.IntegerField(db_column='id', blank=True, primary_key=True) class Meta: managed = False db_table = 'orders_student' def __str__(self): return self.id I defined a model class for a database table . What is the def __str__(self) function in class models.py ? help me please -
Django 3 CheckConstraints m2m field
I would like to add database constraints to my model, that require at least one of its fields to be not-null. When checking the m2m field, I get a FieldError: Cannot resolve keyword '' into field. Is it possible to create such constraints? Sample code: class A(Model): id = AutoField() url = ManyToManyField(Url, blank=True) description = TextField(null=True, blank=True) class Meta: constraints = [CheckConstraints( check=(Q(description__isnull=False) | Q(url__isnull=False))), name="someName" )] -
AttributeError: 'WSGIRequest' object has no attribute 'Get'
from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Quote from .forms import QuoteForm from pages.models import Page def quote_req(request): submitted = False if request.method == 'POST': form = QuoteForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/quote/?submitted=True') else: form = QuoteForm() if 'submitted' in request.Get: submitted = True return render(request, 'quotes/quote.html', {'form': form, 'page_list': Page.objects.all(), 'submitted':submitted}) Context: This is the views.py code the code looks correct but clicking on the quote link on the html local host gives the aforementioned error -
City' object has no attribute 'region__name' in django-autocomplete-light
I have an searchable dropdown which fetch data directly from the tables(models). and this is City table: and as you see it's trying to join country and region tables as well. and in view I have this: class LocationAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return City.objects.none() qs = City.objects.all().select_related('country', 'region') if self.q: qs = qs.select_related('country', 'region').filter(name__icontains=self.q) return qs def get_result_label(self, item): return format_html('<b>{}</b>-{}-{}', item.name, item.region__name, item.country__name) Based on the definition of select_related: Select all related data when executing the query (except many-to-many relationships) But I get this error( which means region__name is not selected at the end!): 'City' object has no attribute 'region__name' In shell I just tried with values() as follows: qs = City.objects.all().select_related('country', 'region').values('id', 'name', 'country__name', 'region__name') it returns a list of dictionaries however I get the error in view when I replace it: AttributeError: 'dict' object has no attribute 'pk' -
How to configure redirect_uri on azure ad to respond to two different environments?
I have the integration just working perfectly, however a small problem arose, I have two different domains with their own instances, the app.company.com environment and the jobs.compamy.com environment, in the app and jobs code I configured the redirect uri in order to always be answered for your domain, and configured in the app ad the two different urls, however the routing is not done correctly the app always redirects to the first reply url which causes me an error of the type: I log in via app environment but I'm redirected to the jobs environment. This code in Environments, redirect uri is a environment variable: aad_auth = OAuth2Session( company_azure['app_id'], scope='User.Read email openid profile', redirect_uri=settings.AD_REDIRECT_URI ) This Redirect uris on my app: https://jobs.company.com/login_azure_ad/callback https://app.company.com/login_azure_ad/callback -
Why While Update Django base64 imagefile upload error Invalid base64-encode string?
Hey I use base64 function to upload image in django server when i tried to use POST method to add upload image its work fine frontend side but when i tried to update and use PUT method the image it through the error invalid nbas64-encoded string: number of data character can not be 1 more than a multiple of 4 So how to resolve this, Here is my base64 code . class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): if isinstance(data, six.string_types): if 'data:' in data and ';base64,' in data: header, data = data.split(';base64,') ext = format.split('/')[-1] try: # data = data.partition(",")[2] decoded_file = base64.urlsafe_b64decode( data + '=' * (-len(data) % 4)) except TypeError: self.fail('invalid_image') file_name = str(uuid.uuid4())[:12] file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = "%s.%s" % (file_name, file_extension, ) data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) extension = "jpg" if extension == "jpeg" else extension return extension and i use like this field of image. class CarPhotoSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) file = Base64ImageField( max_length=None, use_url=True, required=False, allow_null=True, allow_empty_file=True ) -
Django - can I sotre and run code from database?
I build program, when in one part I have some ranking, and I would like to give users option to customize it. In my code I have a function that gets objects and returnes them packed with points and position in ranking (for now it calculates the arithmetic mean of some object's values). My question is is it possible to give e.g. admin chance to write this function via admin panel and use it, so if he would like to one day use harmonic mean he could without changing source code? -
Group by for DRF Serializer
I have a Document model with publication_date field: class Document(models.Model): ... publication_date = models.DateField(default=datetime.date.today) ... I need to serialize all Documents while ordering and grouping them by year: { "count": 9, "groups": [ { "year": 2020, "documents": [...], }, { "year": 2019, "documents": [...], }, ... ] } I've tried to use ListSerializer with overridden to_representaion, but it didn't work out. Is there a way to do this? -
How can I change kiwi template text when creating a new test case?
I would like to ask if it is possible to set a default email address in [CC to:] textarea when creating a new test case? Like this: Default CC to email address -
Not able to submit the form because of Integrity error in Django
models.py class Comment(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE, related_name='comments') commenter = models.ForeignKey(User, on_delete=models.CASCADE) comment_text = models.TextField() created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.comment_text forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = ('comment_text',) views.py @login_required def trip_detail(request,trip_id): trip = get_object_or_404(Trip, pk=trip_id) if request.method == "GET": return render(request, 'trip/trip_detail.html', {'form':CommentForm(),'trip':trip}) else: try: form = CommentForm(request.POST) newcomment = form.save(commit=False) newcomment.user = request.user newcomment.save() return redirect('wall') except IntegrityError: return render(request, 'trip/trip_detail.html', {'form':CommentForm(), 'error':'Bad data passed in, Try again','trip':trip}) -
How to upgrade SQLite 3.7 to SQLite 3.8 in Linux CentOS ,python version 3.6 and django version is 3
When I am running command python3 mange.py runserver I am getting error improperly configured SQLite 3.8.3 found 3.7 . Django version is 3. I also checked similar problems on stackoverflow but in my case it doesn't work -
how can i get data manytomay relation from 3 tables django
class Product(models.Model): name = models.CharField(max_length=30) class Order(models.Model): order_number = models.CharField(max_length=30) products = models.ManyToManyField( Product, through='OrderProduct', related_name='orders' ) class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) price = models.CharField(max_length=30) quantity = models.IntegerField(null = True) product = models.ForeignKey(Product, on_delete=models.CASCADE) my data is already save in these Models now when i fetch order then i want to see Order product data also how can i see these data ? again 1 order has multi order products i try this abc = Order.object.get(id = 1) now how can i see the related products and its quantity and price? -
Implementing a hierarchical system in django using django treebeard
I am trying to implement a web based organisational church system which has a hierarchy as shown in the diagram. I want to implement the system using django treebeard materialized path . I want each node on the tree to be an instance of a Church where a single church in the tree can manage its content also the Admin and the users can be able to login to the Church they belong to. I also need the parent node to be able to access the some data of the child nodes. Is this possible? If you have any idea or leads, please help. Thanks in advance. here is a diagram of the tree -
Use Django to create tables dynamically
I am a beginner in Django, I wish to know if the following is possible in Django. I will have a folder called 'data' into which say I store 2 csv files 'FileA' and 'FileB'. The contents of these are not defined in any model in my Django app. I wish to read the csv files, get the header information from each and dynamically create Tables/Models using this information and load the csv data into these tables. So, for example, if FileA has 3 columns, ColA,ColB,ColC, then I wish to create a model/table named 'FileA', with 3 fields 'ColA','ColB' and 'ColC' and insert the csv data into these tables. Is this possible with Django, or do I have to create,register,migrate to do this manually each time? Any references would be appreciated. Thanks. -
How to add multi select field to existing form in Django?
Just like in title. This is what I currently have. I've tried django-multiselectfield but I had many issues with my foreignkey and ManyToMany usage in models. Maybe I should just use a JavaScript or something? I'm a newbie to Django and I really don't know which way to take. After all these hours of helpless work and research I'll consider every proposition. Thank you in advance! MODELS class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True,blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8,decimal_places=2) date = models.DateField(default=datetime.date.today,db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' FORMS class ExpenseSearchForm(forms.ModelForm): GROUPING_CHOICES = ('date', 'category asc', 'category desc') grouping = forms.ChoiceField(choices=[('', '')] + list(zip(GROUPING_CHOICES, GROUPING_CHOICES))) SORTING_CHOICES = ('date asc', 'date desc' ) sorting = forms.ChoiceField(choices=[('', '')] + list(zip(SORTING_CHOICES, SORTING_CHOICES))) class Meta: model = Expense fields = ('name','category') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for i in self.fields: self.fields[i].required = False