Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update django database models in MySQL?
How to update database table in MySQL ? For example, in my Django app, I have a database table named 'Category1' , and I want to rename it into "Category" only. After I run python manage.py makemigrations and python manage.py migrate , it doesn't show any errors but I can't see any changes in my MySQL Workbench. How to do this ? -
django urls pattern syntax {0,1}
I'm migrating a django app (python2.7, django 1.11) developed by someone else to a new server and see urlpatterns like the following. The new server has python3.6 and django 2.2.2 and seem the pattern syntaxes are different and I had to drop the {0,1} part. I'm just curious what {0,1} means and searched around but couldn't find any document about it. I saw something like \W{4}, \d{2}, but never saw {0,1}. urlpatterns = patterns( '', url(r'^news/{0,1}$', 'views.news', name='news'), url(r'^toggle/{0,1}$', 'views.masquerade', name='toggle_url'), url(r'^dashboard/{0,1}$', 'views.dashboard', name='dashboard'), url(r'^/{0,1}$', 'views.dashboard', name='dashboard'), ... ) -
Django: Translating URLs: How to separate translatable URL patterns in app/urls.py?
This is how Django recommends going about translating URL patterns: Translating URL patterns. Why are URL patterns described in project/settings.py and not in app/urls.py? The example provided above works but when you have many apps installed on your project project/settings.py starts to get really messy. How can I translate my URLs and keep them separate in their app folder at the same time? Thank you. -
apache2 wont start (Process: 16815, Process: 17391)
I am new to Apache and Hosting in general. Today I wanted to deploy my first Django app on a Linux Server. I followed this Tutorial https://www.youtube.com/watch?v=Sa_kQheCnds. Everything worked fine except the installation of sudo apt-get install libapache2-mod-wsgi-py3.if got an error, tried again and got this being read ... Done Dependency tree is built. Status information is read in .... Done libapache2-mod-wsgi-py3 is already the newest version (4.5.17-1ubuntu1). 0 updated, 0 reinstalled, 0 removed, and 0 not updated so i keept going but now at the end when i enter sudo service apache2 restart i get: Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details. systemctl status apache2.service gives me the following output: Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: failed (Result: exit-code) since Thu 2020-09-17 14:45:14 CEST; 1min 33s ago Process: 16815 ExecStop=/usr/sbin/apachectl stop (code=exited, status=0/SUCCESS) Process: 17391 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE) Main PID: 524 (code=exited, status=0/SUCCESS) The Server came preinstalled with Plask. -
I am not able to install django_heroku in my virtual environment for my django project
I tried updating pip, wheel, and psycopg but I keep receiving the error: ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /Users/serena/Projects/VidLibrary-Backend/env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/zd/04_z6x812bsg7gsgrv5wr4800000gq/T/pip-install-1i40ukbk/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/zd/04_z6x812bsg7gsgrv5wr4800000gq/T/pip-install-1i40ukbk/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/zd/04_z6x812bsg7gsgrv5wr4800000gq/T/pip-record-8emxpni2/install-record.txt --single-version-externally-managed --compile --install-headers /Users/serena/Projects/VidLibrary-Backend/env/include/site/python3.8/psycopg2 Check the logs for full command output. -
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})