Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin list filter?
Actually, my models has foreign key to User table. And I want to make admin list show only what I made. # models.py class Store(models.Model): name = models.CharField(max_length=20) address = models.CharField(max_length=50) city = models.CharField(max_length=20) state = models.CharField(max_length=2) phone = models.CharField(max_length=25) user_id = models.ForeignKey(User, on_delete=models.DO_NOTHING) # admin.py class StoreAdmin(admin.ModelAdmin): list_display = ('name', 'address', 'city', 'state') list_filter = ['name'] search_fields = ['name'] But this shows all of list. -
UTF-8 is not saving txt file correctly - Python
My django application reads a file, and saves some report in other txt file. Everything works fine except my language letters. I mean, encoding="utf-8" can not read some letters. Here are my codes and example of report file: views.py: def result(request): #region variables # Gets the last uploaded document last_uploaded = OriginalDocument.objects.latest('id') # Opens the las uploaded document original = open(str(last_uploaded.document), 'r') # Reads the last uploaded document after opening it original_words = original.read().lower().split() # Shows up number of WORDS in document words_count = len(original_words) # Opens the original document, reads it, and returns number of characters open_original = open(str(last_uploaded.document), "r") read_original = open_original.read() characters_count = len(read_original) # Makes report about result report_fives = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-5.txt", 'w', encoding="utf-8") report_twenties = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-20.txt", 'w', encoding="utf-8") # Path to the documents with which original doc is comparing path = 'static/other_documents/doc*.txt' files = glob.glob(path) #endregion rows, found_count, fives_count, rounded_percentage_five, percentage_for_chart_five, fives_for_report, founded_docs_for_report = search_by_five(last_uploaded, 5, original_words, report_fives, files) context = { ... } return render(request, 'result.html', context) report file: ['universitetindé™', 'té™hsili', 'alä±ram.', 'mé™n'] was found in static/other_documents\doc1.txt. ... -
cannot send large text using POST request in Django
I am making an app in reaact native and backend is in django. I am sending POST request from the app to the api, when the text is small it is working fine but when I try to send long text like about 3 paragraphs, only 1.5 paragraph comes in request the other half is not coming. Please help me on this. -
django gunicorn workers vs theads vs other possibilities
My app in django with gunicorn and I am kinda new to gunicorn. My app is heavy on IO, not so much on memory and CPU, essentially a thread has to save a or serve a big file (from few MB to few GB) from storage. Currently because of this the workers run out while there is no load on CPU or memory or even the HDD. By default has a config file for gunicorn that looks like this: import os daemon = True workers = 5 # default localhost:8000 bind = "127.0.0.1:8000" # Pid pids_dir = '/opt/pids' pidfile = os.path.join(pids_dir, 'app.pid') # for file upload, we need a longer timeout value (default is only 30s, too short) timeout = 7200 limit_request_line = 8190 I am not sure about how to configure the workers and threads etc for my work load. let me provide more details: We run "a few VMs" of 2 CPUs/8GB RAM. python is 2.7 we are on the way to upgrade to 3.7, but for now is 2.7 I already tried adding threads with different values (1 to 6), but it does not seem to work. Can someone please help explain what I can do? -
Getting id of an item instead of value, django forms
I have created a form and I wanted to create a field that is for display only, after adding that line, the form started returning id instead of the value. class AmendLoan(ModelForm): borrower = forms.CharField(disabled=True) class Meta: model = BikeInstance fields = ( 'borrower', 'due_back', 'status' ) Any ideas, how to display value of borrower, instead of id? -
Django: adding excluded fields after ModelForm submission
I have a ModelForm where I excluded the selected_season field. The model looks like this (showing relevant part): class Registration(models.Model): student_name = models.CharField(max_length=50) selected_season = models.ForeignKey(Season, on_delete=models.CASCADE) ... before saving the form I have tried adding that field in: if form.is_valid(): form.save(commit=False) form.selected_season = '21' form.save() But it shows null value in column "selected_season_id" violates not-null constraint I added the 21 because there are 2 objects in my Season table, '21' and '22'. How do I fix this? -
Django: Change the HTML button when user joins a event with ManyToMany field
I am designing a event management system using django. I have a problem in changing the button of html page. The problem is: 1.If user is not authenticated then the button should have the value "Login to join" 2. After login, if the user clicks the "join" button(which is earlier "login to join") then the same button changes to "Joined". 3. If the The number of joiners is exceeds to the given limit then the same button should replace with "Full" or "Not Available". {% if user.is_authenticated %} <a href="{{ event.increase_join }}"><button>Join Now</button></a> {% else %} <a href="{% url 'login' %}">Login to Join match</a> {% endif %} I tried the above one but it is not capable to handle my problem the views.py is given below: @login_required def event_joined(request,id): event = get_object_or_404(Event,id=id,available=True) current_joiner = User.objects.get(username=request.user) event.joiners.add(current_joiner) event.joined+=1 event.available_slot-=1 event.save() return render(request,'events/event/detail.html',{'event': event}) -
Error while running '$ python manage.py collectstatic --noinput'.even with static configuration from heroku docs
After trying to upload my django-project to heroku i get the following error, even though I tried to configure setting.py in accordance with heroku documentation. Tried to fix it myself for couple of days but I clearly got no idea about what is wrong. -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_3daca1eccd4631486a8597ada28d44da/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! … -
How to identify which anchor tag submitted form in django?
I have created test.html. I have two anchor tag as shown below.I want to submit form and print name of anchor tag. <div class="collapse navbar-collapse" id="navbarNavDropdown" > <ul class="navbar-nav" > <li class="nav-item" name="lang" > <a class="nav-link" id ='id' value="home" onclick="design.submit();">Home</a> </li> <li class="nav-item"> <a class="nav-link" id ='id1' value="latest_news" onclick="design.submit();">latest news </a> </li> </ul> </div> In view.py i have test func associated with test.html. def test(request): login_data = request.POST.dict() print("succeed") print(login_data) return render(request,'test.html') My aim is when one click the link it will submit form,I will identify which link is clicked and call further code according to it. But, I do not know how to do it.Please Help. -
Saving image of <image> tag in django
I want to save image of tag of html to database using Django. <form method="post" name="data" enctype="multipart/form-data"><br>{% csrf_token %} <image id="theimage" name="theimage"></image> <input class="btn btn-outline-secondary btn-md " type="submit" name="submit" id="submit" value="Upload"> </form> -
in django how to display all videos in static folder in a single page
I want to built a page which will display all the videos in static folder and able to play them (not just listing the video file name). -
Possible permission issue with upstart script/uwsgi
I'm trying to configure an Apache/uwsgi/Django app on a Centos 7. I've been able to set apache to proxy requests to uwsgi. I also set an ini file to link uwsgi with my Django app. The point is that I'm missing something with the systemd service to start the uwsgi server. I suspect is some permissions issue. if I manually run the server with uwsgi --ini /home/foo/env/app/uwsgi.ini then everything works like a charm but when I start the server with systemctl start uwsgi that corresponds to a configured service, the server starts with no errors but certain views on my app just fail. Watching logs I see many errors like these ones During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/foo/env/lib/python3.6/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute Traceback (most recent call last): File "/home/foo/env/lib/python3.6/site-packages/django/template/base.py", line 882, in _resolve_lookup current = current[bit] File "/home/foo/env/lib/python3.6/site-packages/django/template/context.py", line 87, in __getitem__ raise KeyError(key) KeyError: 'form' During handling of the above exception, another exception occurred: File "/usr/lib64/python3.6/traceback.py", line 105, in print_exception print(line, file=file, end="") UnicodeEncodeError: 'ascii' codec can't encode character '\xf8' in position 18057: ordinal not in range(128) This same views work perfectly when starting … -
How can i copy the current row of a model to other in Django?
After I create a blog I have two submit buttons one to post an article in my profile which only I can see and other to post it in homepage as well as in my profile where all users can see but I can't figure out how to make second submit button work properly #Model MyLane in mylane/models.py class MyLane(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=25) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('my-lane') # Model Home in home/models.py class Home(models.Model): title = models.ForeignKey(MyLane, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title #Createview in mylane/views.py class MyLaneCreateView(LoginRequiredMixin, CreateView): model = MyLane fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): if 'homepost' in self.request.POST: mylane = MyLane.objects.get("??") home = Home(title=mylane.title, content=mylane.content, author=self.request.user) home.save() url = reverse('home') else: url = reverse('my-lane') return url -
no such table: form1_user
I have tried all previous solutions such as syncdb, migrate, makemigrations etc. I am still not getting the program to work. My models.py class Role(models.Model): ROLE_CHOICES = ( (1,'ADMIN'), (2,'HR'), (3,'MGR'), (4,'EMP'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES,primary_key=True) def ___str___ (self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) class Admins(models.Model): user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) class HRs(models.Model): user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) Then here is my views.py class AdminSignUpView(CreateView): model = User form_class = AdminSignUpForm template_name = 'form1/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'ADMIN' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/form1/forms/') class HRSignUpView(CreateView): model = User form_class = HRSignUpForm template_name = 'form1/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'HR' return super().get_context_data(**kwargs) def form_valid(self,form): user = form.save() login(self.request, user) return redirect('/form1/forms') Here is my forms.py class AdminSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fname = forms.CharField(max_length=256) lname = forms.CharField(max_length=256) @transaction.atomic def save(self): user = super().save(commit=False) user.roles = 1 user.save() admin1 = Admins.objects.create(user=user) admin1.first_name.add(*self.cleaned_data.get('fname')) admin1.last_name.add(*self.cleaned_data.get('lname')) return user class HRSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User @transaction.atomic() def save(self, commit=True): user = super().save(commit=False) user.roles = 2 user.save() hr1 = HRs.objects.create(user=user) hr1.first_name.add(*self.cleaned_data.get('fname')) hr1.last_name.add(*self.cleaned_data.get('lname')) return user Finally, here is my error - OperationalError at /accounts/signup/hr/ no such … -
Unable to import Django Project onto additional computers
For the final project in my software class, my group has decided to use Django to build a web app. I created a Django project with a working Virtual Environment and have it sitting in GitHub for my teammates to be able to access and collaborate. So far, I have been able to run the website and create new apps with ease. That being said, when my teammates first pull from VCS into Pycharm Professional and configure the interpreter, they are met with this error: Cannot set up a python SDK at Python 3.8 (DeliverMe) (/Users/taylorschissel/PycharmProjects/DeliverMe/venv/bin/python) The SDK seems invalid. I have read through many posts but cannot seem to find anyone with a similar issue, so I am at a loss for causes/solutions. Here is the link to the repo: https://github.com/isaacfc4/DeliverMe -
Difficulty adding widget to django project
Firstly I apologize for the very basic question but I am currently learning to develop and have read a lot of documentation and searched a lot but still cannot get this working. I'm building a website using Django framework am trying to add the django-bootstrap-datepicker-plus widget. I am having a lot of difficulty figuring out exactly where the different parts of code should go. I have included snippets from my model.py and forms.py files below. The forms work as they are now, but I encounter lots of problems when I try to add the datePicker widget. class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) GENDERS = ( ('M', 'Male'), ('F', 'Female'), ) first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') gender = models.CharField(max_length=1, choices=GENDERS) class PersonalInformationForm(forms.ModelForm): class Meta: model = PersonalInformation fields = ['first_name', 'surname', 'gender'] Thank you very much and I apologize for the very basic question but I have spent hours trying to figure it out and am just going around in circles. -
Does enabling HTTP/2 in Daphne preclude Daphne's server pushed events feature from working?
The HTTP/2 Support section of the Daphne GitHub page (https://github.com/django/daphne#http2-support) says: Daphne only supports "normal" requests over HTTP/2 at this time; there is not yet support for extended features like Server Push. I plan on using Daphne for its server push feature. Does the above statement imply I should not even try to enable HTTP/2 because it would prevent the server push feature from working at all? -
Apache configuration for serving Django app is not working
I have installed my Django Project on the server, and it is running locally with no problem. I can make migrations and runserver works with no error. I am following this tutorial in order to use Apache to serve the project on Ubuntu, but I am having problems. The first one is where you start Django's development server and allow remote connections (./manage.py runserver 0.0.0.0:8000). When I connect from a remote browser, I get this error: Esta página no funciona 189.172.218.174 envió una respuesta no válida. ERR_INVALID_HTTP_RESPONSE I have also made al configurations to serve the app with Apache, but when a try to connect to the server from a browser, I just get a blank page. No error or anything. This is my 000-default.conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last … -
Reverse for 'hire_a_crew' not found. 'hire_a_crew' is not a valid view function or pattern name
I keep on getting a NoReverseMatch at / error when i run my project here is the app level url.py from django.urls import path from . import views from justproduceit_project import settings from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name = 'create' urlpatterns = [ path('equipment_categories/', views.EquipmentCategoriesListView.as_view(), name='equipment_categories'), path('rent_equipment/', views.EquipmentListView.as_view(), name='equipment_home_page'), path('equipment/<slug>/', views.EquipmentDetailView.as_view(), name='equipment_detail'), path('add_to_cart/<slug>/', views.add_to_cart, name='add_to_cart'), path('remove_from_cart/<slug>/', views.remove_from_cart, name='remove_from_cart'), path('checkout/', views.checkout, name='checkout'), path('hire_a_crew/', views.CrewListView.as_view(), name='hire_a_crew'), path('start_a_project/', views.ProjectListView.as_view(), name='start_a_project'), ] here is the settings level urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('pages.urls')), path('learn/', include('learn.urls')), path('create/', include('create.urls', namespace='create')), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] here is the template that is throwing the error <div class="dropdown-menu col-lg-12 text-center" aria-labelledby="dropdownMenuLink"> <h6 class="dropdown-header"><b>Hire a</b></h6> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'hire_a_crew' %}">Crew</a> <a class="dropdown-item" href="#">Director</a> <a class="dropdown-item" href="#">Producer</a> <a class="dropdown-item" href="#">Writer</a> <a class="dropdown-item" href="#">Cinematographer</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'equipment_home_page' %}" role="button">Rent equipment</a> <a class="dropdown-item" href="{% url 'start_a_project' %}" role="button">Start a project</a> </div> -
Multiple arguments from DjangoTemplateLanguage to re_path()
Suppose there's an urlpattern as such : re_path('^(app){3}/$', views.apple, name='apple'), My understanding is that if I want to use a hyperlink of this in templates, I should do as such: <a href="{% url 'apple' 'app' 'app' 'app' %}">apple</a> But what if I wanted to make this pattern? re_path('^(app){100}/$', views.apple, name='apple'), Is there a better way than spamming arguments? -
In forms.ModelForm, Select dropdown not displaying values in queryset() correctly
[models.py] from django.contrib.auth.models import User class Post(models.Model): title = models.CharField() author = models.ForeignKey(User, on_delete= models.CASCADE) [forms.py] from django.contrib.auth.models import User class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','author'] widgets = { 'author': Select(attrs={'style': 'width: 400px;'}), } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['author'].queryset = User.objects.values_list('first_name') and this is what Select dropdown for Author shows: how do i make it shown this instead: ----- Admin John (PLEASE IGNORE: i'm just adding nonsense here otherwise stackoverflow complains "it looks like your post is mostly code. please add some more details" and won't let me submit. I don't know what else to say so i'm just adding garbage here...) -
How to use Django session variable in models.py
I wanna use the Django session variable on models.py file. How can I do it? -
django-registration invalid activation key error but user account gets activated
When I click on activation link http://127.0.0.1:8000/core/auth/activate/aoisdoaisdoaisdoiaj/ I am taken to a activation_failed page which says - The activation key you provided is invalid. But my account in the database gets activated too. If account is being activated that means activation was successful. Then why would django-registration redirect to failed page. Thanks -
Django models update calculated field according another field
I use Django and I want update many records of my model by using a calculation like in SQL like that : UPDATE table SET amount = pre_tax * 1.2 WHERE amount IS NULL; I want do that with Django ORM. I didn't find any ways to do that. This answer Django - Update model field based on another field don't use bulk update, I need a syntax that allows updating several records. -
Django Multiple form, change second forms content based on 1st form
I need to create a form where, user input from 1st form will change the form 2 content / options. For example consider in 1st form User inputs Number of building Number of floor per building Let's assume the user entered 3 building with 6,7 and 8 floors. In the next form the user has to inputs Sq Ft area per floor per building So Second form needs to have 6 rows/input for building 1, 7 rows/input entry for building 2 and 8 input entry for building 3. Thanks in advance, I am learning Django and apologize if asking a silly question.