Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Collation Error When creating Django Database Models
I have followed the various tutorials from philly and others to setup django with django-mssql-backend but have had no luck. I think the connection is working but when it is trying to parse the tables I get a collation error that it cannot get past. The specs of what I'm running are as follows: django-mssql-backend: 2.8.1 django: 3.2 pyodbc: 4.0.30 'server':{ 'ENGINE': 'sql_server.pyodbc', 'NAME': 'database', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'hostname of server', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'unicode_results': True, }, } When I attempt to run the migration class creator or: python manage.py inspectdb --database=devops_02 I get the following error in the output: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models … -
StaticLiveServerTestCase Server Error 500
Main urls.py file: urlpatterns = [ path( 'admin/', admin.site.urls ), path( '', include( 'employee.urls' ) ), path( '', include( 'epos.urls' ) ), path( '', include( 'supplier.urls' ) ), ] epos.urls: urlpatterns = [ path( '', home_view, name='home' ), home_view: @login_required def home_view(request): # Get all categories categories = Category.objects.all() # Get the first category which will be selected by default selected_category = categories.first() # Get the order_items for the selected category (first category) products = Product.objects.filter( category=selected_category.id ) user = request.user tax = Tax.objects.latest('id') context = { 'categories': categories, 'user': user, 'title': "EPOS", 'products': products, 'selected_category': selected_category, 'tax': tax } return render(request, 'epos/epos.html', context) Test case: class LoginTests(StaticLiveServerTestCase): fixtures = ['fixtures/employee/employee_data.json'] def setUp(self): self.browser = webdriver.Chrome() self.browser.get(self.live_server_url) self.browser.maximize_window() def tearDown(self): self.browser.quit() def test_login_when_clocked_in(self): import ipdb;ipdb.set_trace() login_button = self.browser.find_element_by_xpath( '//button[normalize-space()="Login"]' ) clock_in_out_button = self.browser.find_element_by_xpath( '//button[normalize-space()="Clock In/Out"]' ) pin_input = self.browser.find_element_by_id( 'pin' ) pin_code = 'some pin' employee_name = 'some name' pin_input.send_keys(pin_code) clock_in_out_button.click() time.sleep(10) login_button.click() When the test logs in I am redirected to the main webpage which is localhost:46497/ but instead of the page I am getting Server Error 500. This error occurs only when testing. In addition, if I add another path e.g. localhost:46497/analytics it opens the webpage as expected. … -
Django forms: new fields whenever field value is changed?
In my forms.py I have a simple form defined, with an integer and a choice field: SAMPLE_STRINGS = [('','Select...'),'aa','ab','bb','c0'] class MyCustomForm(forms.Form): chosen_string = forms.ChoiceField(choices=SAMPLE_STRINGS, label='Please select a string', required=True) chosen_number = forms.IntegerField(label='Please select an integer', widget=forms.NumberInput(attrs={'placeholder': 0})) Currently both fields appear on the form. My goal however is to show just the ChoiceField by default, but when the user selects an option different from the default "Select..." option, append the IntegerField to the form as well. I am aware of the .changed_data property and the .has_changed() method, but both of these seem to only activate upon a "submit" button press which is not what I intend. Ideally, I would like the IntegerField to immediately when the user changes the ChoiceField from the default "Select..." to anything else, e.g. "aa". How could I achieve this - if it is even possible? My views.py now only has the following: def form_interactivity(response): form = MyCustomForm(response.POST or None) # ? # print(form.changed_data, form.has_changed()) return render(response, "main/form_interactivity.html", {"form": form}) -
Django-Heroku-PostGres: KeyError: 'psql' during Git push Heroku main
I'm trying to deploy my Django app in Heroku. I'm also using PostGreSQL and Github. I've been using a bunch of random tutorials to set this up and try to debug the results, so I apologize if there are "inconsistencies". When I run git push heroku main, I get the error remote: KeyError: 'psql' Error while running '$ python manage.py collectstatic --noinput: Here's the traceback. remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/tmp/build_e87847fa/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_e87847fa/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 363, in execute remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 790, in exec_module remote: File "<frozen … -
TemplateDoesNotExist at /post/new/ When i host the django project on heroku
I created an app with django on my local machine and it works perfectly with all the templates and html files going to the correct locations but when i tried to host it on heroku, it loads the home page but when i try to create a new blog it says templates does not exist. This is the error I keep getting: Request Method: GET Request URL: https://ifecrudapp.herokuapp.com/post/new/ Django Version: 3.2 Exception Type: TemplateDoesNotExist Exception Value: blog/post_form.html Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/template/loader.py, line 47, in select_template Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.4 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /app/templates/blog/post_form.html (Source does not exist) django.template.loaders.filesystem.Loader: /app/blog/templates/blog/blog/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/blog/templates/blog/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/users/templates/blog/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/crispy_forms/templates/blog/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/templates/blog/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/templates/blog/post_form.html (Source does not exist) -
How can I call manage.py within another python script?
I have a shell script that calls ./manage.py a few times, and would like to create the same functionality within a python 3.9.2 script. I have tried subprocess.run and os.system but get hung up for various reasons. Currently the shell script looks like ./manage.py dump_object water_testing.watertest '*' > ./water_testing/fixtures/dump_stevens.json ./manage.py dump_object tp.eqsvc '*' >> ./water_testing/fixtures/dump_stevens.json ... Any suggestions? -
Display django debug toolbar in production
I installed django-cahalot with redis backend on my django application. It is working fine on my local machine. Problem is this I am unable to see any improvement on my production server. I need to display django-debug-toolbar on my production server to analyze the bottlenecks. Thanks -
Display office files or pdf files using ViewerJS in a Django template
I'm trying to use ViewerJS in a Django 3.1 application in order to display office documents or pdf's within a Django template. The url I created is http://localhost:8000/static/js/ViewerJS/index.html/#..media/files/Materials.pdf This generates this: That is, it lifts the index.html file but no more than that. When I look at the developer console -> networks I see that many items of viewer js are not found, I understand that this is why the presentation fails. ViewerJS is located in static/js/ViewerJS In the template I have tried these two ways: <a href="/static/js/ViewerJS/media/archivos/Materiales.pdf" class="btn">Preview</a> <iframe src = "/static/js/ViewerJS/index.html/#../media/archivos/Materiales.pdf" width='700' height='550' allowfullscreen webkitallowfullscreen></iframe> If you know of another solution by which I can do what I need and it is not ViewerJs, it is welcome. But neither works. -
Django overriding display names for foreign key field in modelform
Suppose below models: from django.db import models class Status: name = models.CharField(max_length=50) order = models.PositiveIntegerField() def __str__(self): return self.name class Article: headline = models.CharField(max_length=100) status = models.ForeignKey(Status, on_delete=models.CASCADE, null=True) I want to create admin form for Article model, but don't want to use results of __str__ method of Status model as display name in status choices form field. It can be achieved by overriding label_from_instance method ModelChoiceField as below: from django import forms from blog.models import Status, Article class StatusModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, status): label = f"{status.order}: {status.name}" return label class ArticleForm(forms.ModelForm): status = StatusModelChoiceField(queryset = Status.objects.all()) class Meta: model = Article fields = ('headline', 'status') Problem with this method is that, it doesn't take into account Article model's status field definition. For example, although status field is nullable in Article model, it is required in ArticleForm. I should tell explicitly that it is not required (status = StatusModelChoiceField(queryset = Status.objects.all(), required=False)). If status field would have limit_choices_to, it also won't be considered in my form dynamically. So, I just want different display names than default __str__. How can I achieve this goal in more DRY manner? -
pixi.js не загружает картинку (pixi.js does no add image)
Всем привет, использую django и никак не выходит загрузить картинку в PiXi.loader, в settings прописан путь на статические файлы в html например выводит картинку, а вот в pixi уже нет, в инете не нашёл, вот аналог Pixi.js can't load images because Django "can't find them" Hello everyone, I use django and I can't load the image in PiXi.loader, the path to static files in html is written in settings, for example, it outputs the image, but in pixi it no longer exists, i try make this Pixi.js can't load images because Django "can't find them" my code: https://i.stack.imgur.com/uVYYB.png -
How to sort django form fields automaticly
I have django ModelForm like this class MyForm(forms.ModelForm): def make_this_fields_first(my_firlds): #what I can do here? class Meta: model= MyModel fields = '__all__' In view I want to make like this: my_form_obj = MyForm() my_form_obj.make_this_fields_first(['field6','field3']) -
Chat server: Websocket Server vs Django Channels vs SignalR
I'm looking to utilize a chat service for my app. Does anyone know which chat service can host the most amount of users with the current technology? -
python manage.py runserver No module named projectname.settings error message
I have a problem that occurred once I moved my Django project to a new Mac. Once I fired up the virtual environment, I have a problem with running my server. Stacktrace, code, and images attached. Any help is appreciated. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fiveminread', ] settings.py manage.py -
Deploying Django on VPS using Apache2 on ubuntu 20.04
I had tried to set up the Django application on VPS. At first, I have installed all dependencies on Linux, then copied the Django project via ssh. I created virtualenv inside Django project. At first, I decided to review the project by running ./manage.py runserver 0.0.0.0:8000 . Everything works fine. I have configured the firewall settings: To Action From -- ------ ---- 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere Apache ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) Apache (v6) ALLOW Anywhere (v6) So I move to the next step – Apache2. I run apache2 with 000-default.conf to check that Apache is working properly and is listening to the IP address. To check my server IP I hit: hostname -I Let’s say my Server address is Ex. 77.55.111.246 and servername.domain.com By hitting IP address my browser return: Apache2 Ubuntu Default Page. All’s well that is end well… I made a copy 000-default.conf with the name django_project.conf Enable the domain configuration file sudo a2ensite django_project.conf I also diabled old configuration sudo a2dissite 000-default.conf django_project.conf <VirtualHost *:80> ServerAdmin jacobitedge@77.55.111.246 ServerName 77.55.111.246 DocumentRoot /home/jacobitedge/bike/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/jacobitedge/bike/static <Directory /home/jacobitedge/bike/static> Require all granted </Directory> <Directory /home/jacobitedge/bike/bike> … -
Social Network Login Failure on Django, Callback url mismatched
I have problem for attaching social login. I have tried google login on local, it was fine. But when I try for deploy, Non-public domain is not supported. I`m not sure *.link is non-public domain, but it did not work for some reason. So I am trying to do github login, but I have following errors.. There is callback URL mismatch, but I don't know which URL should I use. Im using on Github this URL : https://taeheejo.link/user/githubin/github/login/callback/ urls.py ... path('admin/', admin.site.urls), path('user/', include('authy.urls')), path('sub/', include('tier.urls')), ... authy/urls.py ... path('login/', authViews.LoginView.as_view(template_name='registration/login.html'), name='login'), path('githubin/', include('allauth.urls')), ... And Here is an Error.. I have added on admin pannel sitename and application too.. Can someone please tell me which part am I missing? -
AttributeError: 'QuerySet' object has no attribute 'category'
I am using DRF to get and create data from and to the API. I was struggling with a model Question and a attribute category which is a model too. So in order to create and read data I had to implement this question's answer method. Whenever I use the default API route I can create and read the data, but I am getting the following error whenever I write a different scenario: AttributeError: Got AttributeError when attempting to get a value for field category on serializer QuestionSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'category'. This is my custom code, where something is wrong...: class UserQuestions(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request, *args, **kwargs): questions = Question.objects.filter(created_by=request.user.id).all() data = QuestionSerializer(questions).data return Response({ 'questions': data }) Just in case, this is my answer's implementation: class RelatedFieldAlternative(serializers.PrimaryKeyRelatedField): def __init__(self, **kwargs): self.serializer = kwargs.pop('serializer', None) if self.serializer is not None and not issubclass(self.serializer, serializers.Serializer): raise TypeError('"serializer" no es una clase serializer válida') super().__init__(**kwargs) def use_pk_only_optimization(self): return False if self.serializer else True def to_representation(self, instance): if self.serializer: return self.serializer(instance, context=self.context).data return super().to_representation(instance) class … -
Django multiple user acess specific content
I'm trying to make a page has diffrent content what I'm trying to do is to make specific users to acess specific objects in this page when I do for example: Something.objects.filter(user=request.user) only one user is have acess to this content can't add another user from django admin Any advice Thanks -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 107654: invalid start byte Django database change to MySQL
I recently attempted to switch databases on my Django project from the default SQLite to MySQL. After setting up MySQL accordingly, I used the following command: python manage.py dumpdata > datadump.json # to export existing data into a json file After I set up the MySQL db in settings.py and doing all the migrations, trying to load the json file to the db with the command: python manage.py loaddata datadump.json # should return sth like "Installed 59 object(s) from 1 fixture(s)" I get the following error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 107654: invalid start byte Now I tried setting the default charset of the mysql DB to utf8 but nothing happened. When I click on the datadump.json file in Pycharm, I also get the following warning, I do not know whether it is relevant or not: File was loaded with the wrong encoding: UTF-8 Any help would be appreciated -
Getting a phone number by logging in via telegram
I use the django-telegram-login library to log in to the site via telegram. How can I get a phone number after logging in? In the GET parameters, there is a user id. Maybe you can somehow find out the number through the id -
Adding placeholder to ChoiceField in Django?
In my forms.py I have a simple form class defined as: SAMPLE_STRINGS = ['aa','ab','bb','c0'] class IndicatorForm(forms.Form): chosen_number = forms.IntegerField(label='Please select a value') chosen_string = forms.ChoiceField(choices=SAMPLE_STRINGS, label='Please select a string', required=True) I want to add a placeholder for both fields. For the first one, it was easy: chosen_number = forms.IntegerField(label='Please select a value', widget=forms.NumberInput(attrs={'placeholder': 0})) But for the ChoiceField, I didn't have any luck. I tried using widget=forms.TextInput(attrs=...) but that removes the choices and transforms the field into a simple text field. widget=forms.ChoiceInput and widget=forms.ChoiceField do not work either. How can I add a placeholder saying "Select..." to my ChoiceField? -
How to separate a category in a django template
I get this error: ValueError at /product/ The QuerySet value for an exact lookup must be limited to one result using slicing. this is my models : class Categorie (models.Model): title = models.CharField(max_length=50) category_slug = models.SlugField(blank=True) def __str__(self): return self.category_slug class Products(models.Model): category = models.ForeignKey(Categorie,on_delete=models.CASCADE,null=True, related_name="product") product_slug = models.SlugField(blank=True) product_title = models.CharField(max_length=50 , null=True) product_name = models.CharField(max_length=100 , null=True ) product_describe = models.CharField(max_length=200 , null=True) product_picture = models.ImageField(upload_to='img_pro' , null=True) product_created_at = models.DateField(auto_now_add=True) product_updated_at = models.DateField(auto_now=True) def __str__(self): return self.product_slug this is my view: def index(requset): category = Categorie.objects.all() product = Products.objects.filter(category_slug=category) context = { 'category':category, 'product ':product , } return render( requset , 'product/index.html' , context) this is my template: {% for cat in category %} <div class="fix single_content"> <h2>{{cat.title}}</h2> <div class="fix"> {% for pro in product %} <ul> <li> <div class="entry_name"><a href=""><img src="{{pro.product_picture.url}}" alt=""><span> {{pro.product_title}}</span></a><h6>{{pro.product_name}}</h6></div> </li> </ul> {% endfor %} </div> {% endfor %} Can anyone help me with that please? -
Django post not working (Your file couldn’t be accessed) ERROR
I did not change anything in my form where I was able to upload files normally, before I got this error just today : (just in POST not GET method) Your file couldn’t be accessed It may have been moved, edited, or deleted. ERR_FILE_NOT_FOUND in the browser but nothing in the console (even the request is not captured !!!). I used nginx as web server. Any explanation and/or solution please ? -
Website visitor/ view counter app in django
I have created website with Django consisting 3+ app. Now I wanted add hit counter/ visitor counter to complete website (all apps) not individual to any app. I have tried some of app: django-hitcount, django-pageviews & django-visits but they not fulfilling my requirement. They are using IP address so it will not count multiple visits from same machine. Most of the counter are for Post in blogs. I wanted a counter for whole website. not bound to IP address or any post/app. Any solution is welcomed. Thank you in advance. -
AttributeError: 'FloatField' object has no attribute 'model' error when using F function on a OneToOneField model field
My model definitions looks like this and there is a OneToOne relationship class Rocket(BaristaBase): name = models.CharField( max_length=256, blank=True, null=False, unique=True, ) my_volume = models.IntegerField( default=0, null=False, blank=True, ) class RocketMetrics(EspBase): rocket = models.OneToOneField( "Rocket", on_delete=models.CASCADE, blank=True, null=True, related_name="metrics" ) helpful_count = models.IntegerField( default=0, null=False, blank=True, ) The following is from the view_api.py and self.queryset is based of Rocket.objects.all() self.queryset = self.queryset.annotate(percent_unhelpful=Case( When(total_actions=0, then=0.0), default=F('metrics__helpful_count') * 100.0 / F('total_actions'), output_field=FloatField())) The above usage of the FloatField() to transform the output throws the following error. 2021-04-27T01:20:14 tenant1 ERROR [6b30d5178f0a4f718d34c16553575ad1] common logging_util.py:116 - 'FloatField' object has no attribute 'model' Traceback (most recent call last): File "/Users/myuser1/projects/tahoe/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/myuser1/projects/tahoe/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/myuser1/projects/tahoe/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view return self.dispatch(request, *args, **kwargs) File "/Users/myuser1/projects/tahoe/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch response = self.handle_exception(exc) File "/Users/myuser1/projects/tahoe/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception self.raise_uncaught_exception(exc) File "/Users/myuser1/projects/tahoe/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch response = handler(request, *args, **kwargs) File "/Users/myuser1/projects/tahoe/django/deltaco/barcharter/faqs/views_api.py", line 1604, in rocket_lookup return rocket_lookup(self, request, filtered_queryset) File "/Users/myuser1/projects/tahoe/django/deltaco/barcharter/rocket_lookup/functions.py", line 90, in rocket_lookup return obj.get_paginated_response(get_serialized_rockets(obj, request=request)) File "/Users/myuser1/projects/tahoe/django/deltaco/barcharter/rocket_lookup/functions.py", line 501, in get_serialized_rockets page = obj.paginate_queryset(obj.queryset) File "/Users/myuser1/projects/tahoe/lib/python3.6/site-packages/rest_framework/generics.py", line 173, in paginate_queryset return self.paginator.paginate_queryset(queryset, self.request, view=self) File "/Users/myuser1/projects/tahoe/lib/python3.6/site-packages/rest_framework/pagination.py", line … -
Django session cookie forgotten on every browser reopen - mobile Safari (iphone,ipad)
I wonder if anybody encountered with this problem. I am storing some data about visitor in django session. It works as expected but only mobile safari (iphone and ipad) have strange behaviour. When I visit my site from iphone or ipad(Safari ver. 14.3) session cookie is normally set. But when I close the browser then reopen, new session cookie is generated. This behaviour can be seen only on mobile safari version. I was not able to reproduce it on macOS desktop safari. To solve this problem I had to change setup for session cookie in django settings.py: SESSION_COOKIE_SAMESITE = ‘None’ According to django doc. cookie is normally set as ‘lax’ and this introduce security risk in my app. SESSION_COOKIE_SAMESITE Default: 'Lax' The value of the SameSite flag on the session cookie. This flag prevents the cookie from being sent in cross-site requests thus preventing CSRF attacks and making some methods of stealing session cookie impossible. Possible values for the setting are: 'Strict': prevents the cookie from being sent by the browser to the target site in all cross-site browsing context, even when following a regular link. For example, for a GitHub-like website this would mean that if a logged-in user …