Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
While giving the command - python manage.py runserver, it shows the given error
Error while executing python manage.py runserver enter code here Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\hp\appdata\local\programs\python\python37\Lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\users\hp\appdata\local\programs\python\python37\Lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\rest_framework_filters\__init__.py", line 3, in <module> from .filterset import FilterSet File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\rest_framework_filters\filterset.py", line 10, in <module> from django_filters import filterset, rest_framework File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django_filters\__init__.py", line 7, in <module> from .filterset import FilterSet File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django_filters\filterset.py", line 15, in <module> from .filters import ( File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django_filters\filters.py", line 10, in … -
Why are files uploaded from phone processed slower then files uploaded from pc on a webpage by django/nginx?
I have a webpage running on django+gunicorn+nginx, it has a file input and a post button. If i send a file using this webpage from pc, it is processed in a few seconds, but if i send the same file using this webpage from my iphone it takes more then two minutes. Why? How can i make it faster? <h2>Main page</h2> <form method='post' enctype="multipart/form-data"> {% csrf_token %} <input type="file" name='img_file'> <button type='submit'>Send</button> </form> {% if answers%} {% for answer in answers%} {{answer| safe}} {% endfor %} {% endif %} {% if file_extension %} {{ file_extension }} {% endif %} def main(request): user_session = request.session.session_key content = {} if not user_session: request.session.create() user_session = request.session.session_key if request.method == "POST": myfile = request.FILES.get('img_file') print(myfile) fs = FileSystemStorage() file_prefix, file_extension = os.path.splitext(myfile.name) filename = fs.save(user_session + file_extension, myfile) answer_list = image_to_answer(MEDIA_ROOT + '/' + filename)# takes most time to process uploaded_file_url = fs.url(filename) content = {'ufu': uploaded_file_url, 'answers': answer_list, 'file_extension': file_extension} return render(request, 'mainapp/index.html', content) input: posted xxx.jpeg file output: html code (for example: 'answer1'blue'') that will be part of template for returned page (answers in index.html) -
Page not found error while deploying django app on centos7 using nginx and uwsgi
I'm trying to deploy my django app on a centOS7 server using VPS with nginx and uwsgi, following this tutorial https://www.youtube.com/watch?v=c_17jALtLbQ&feature=youtu.be. The server is up and running i.e., the homepage (welcome to nginx) is working but when I navigate to a different page it tells me "page not found". Previously, I also tried using Apache following this https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-centos-7. But it tells me "you don't have permission to access /url/". Following is the code for /etc/nginx/sites-available/sitename: server{ listen 80; server_name localhost; location / { uwsgi_pass unix:///tmp/main.sock; include uwsgi_params; } location /static/ { alias /var/www/supplychain/Supply_Chain_Proj/static/; } } And this is my /etc/uwsgi/apps-available/sitename.ini file: [uwsgi] vhost = true plugins = python socket = /tmp/main.sock master = true enable-threads = true processes = 4 wsgi-file = /var/www/supplychain/Supply_Chain_Proj/supply_chain/wsgi.py virtualenv = /var/www/venv/site chdir = /var/www/supplychain/Supply_Chain_Proj touch-reload = /var/www/supplychain/Supply_Chain_Proj/reload env = DJANGO_ENV=production env = ALLOWED_HOSTS=* -
Carousel is not loading properly
I have made carousel in my home page which lists the products the user wishes to purchase in a card view split by category. Earlier it was working fine and 3 cards per each category were displayed. However, now the carousel doesn't load properly. My HTML code looks like this: <div class="container-fluid ml-5"> {% for product, range, nSlides in allProds %} <h5>{{product.0.category}}</h5> <div class="row"> <div id="myCarousel{{forloop.counter}}" class="col carousel slide mt-3 mr-3 ml-1" data-ride="carousel" data-interval="false"> <ol class="carousel-indicators"> <li data-target="#myCarousel{{forloop.counter}}" data-slide-to="0" class="active"></li> {% for i in range %} <li data-target="#myCarousel{{forloop.parentloop.counter}}" data-slide-to="{{i}}"></li> {% endfor %} </ol> <!-- Slideshow starts here(1.1) --> <div class="container carousel-innner row w-100 mx-auto"> <div class="carousel-item active mr-3"> <!--Slides --> {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3 mr-3"> <div class="card align-items-center mt-3 mr-3" style="width: 18rem;"> <img src="/media/{{i.image}}" class="card-img-top" alt="..."> <div class="card-body text-center"> <h6 class="card-title" id="namepr{{i.id}}">{{i.product_name}}</h6> <h6 class="card-title"><b>Price: ₹ <span id="pricepr{{i.id}}">{{i.price}}</span></b></h6> <h6 class="card-title"><b>Stock:<span id="stockpr{{i.id}}">{{i.stock}}</span></b></h6> <!-- <p class="card-text">{{i.description|slice:"0:70"}}...</p> --> <span id="divpr{{i.id}}" class="divpr"> <button id="pr{{i.id}}" class="btn btn-primary cart">Add to Cart</button> </span> <a href="/shop/products/{{i.id}}"><button id="qv{{i.id}} " href="#" class="btn btn-primary cart">Quick View</button></a> </div> </div> </div> {% if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last %} </div> <div class="carousel-item"> {% endif %} {% endfor %} </div> </div> </div> <!-- Left Right … -
Dynamic updates in real time to a django template
I'm building a django app that will provide real time data. I'm fairly new to Django, and now i'm focusing on how to update my data in real time, without having to reload the whole page. Some clarification: the real time data should be update regularly, not only through a user input. View def home(request): symbol = "BTCUSDT" tst = client.get_ticker(symbol=symbol) test = tst['lastPrice'] context={"test":test} return render(request, "main/home.html", context ) Template <h3> var: {{test}} </h3> I already asked this question, but i'm having some doubts: I've been told to use Ajax, and that's ok, but is Ajax good for this case, where i will have a page loaded with data updated in real time every x seconds? I have also been told to use DRF (Django Rest Framework). I've been digging through it a lot, but what it's not clear to me is how does it work with this particular case. -
Python-Django [SSL: WRONG_VERSION_NUMBER] Error
While I'm trying to connect to my localhost, I get [SSL: WRONG_VERSION_NUMBER] error. I'm using '8080' port by default. Previously, I was getting ProxyError, then I changed my url from 'http' to 'https' and now I get SSLError. I've checked some solutions, which prompts to change the port number. Does it have to do anything with the port number, or something else? views.py: endpoint = 'https://****:8080/MyApp/services/DBConnection/callLoginProcedure' def index(request): post = request.POST if request.POST.get('login_button'): qd = QueryDict(mutable=True) qd.update( inputPhoneNumber=request.POST.get('phone_num'), inputPassword=request.POST.get('password') ) response = requests.post('{}?{}'.format(endpoint, qd.urlencode()), verify=False) result = response.json() messages.info(request, result) return render(request, 'login/index.html') The error is as follows stacktrace: Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['login', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'] Traceback: File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in urlopen 603. chunked=chunked) File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in _make_request 344. self._validate_conn(conn) File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in _validate_conn 843. conn.connect() File "C:\Program Files\Python37\lib\site-packages\urllib3\connection.py" in connect 370. ssl_context=context) File "C:\Program Files\Python37\lib\site-packages\urllib3\util\ssl_.py" in ssl_wrap_socket 368. return context.wrap_socket(sock) File "C:\Program Files\Python37\lib\ssl.py" in wrap_socket 412. session=session File "C:\Program Files\Python37\lib\ssl.py" in _create 853. self.do_handshake() File "C:\Program Files\Python37\lib\ssl.py" in do_handshake 1117. self._sslobj.do_handshake() During handling of the above exception ([SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)), another exception occurred: File "C:\Program Files\Python37\lib\site-packages\requests\adapters.py" in send 449. … -
What is it the max_length in the password of Django User?
My problem is that I don't feel sure because I don't understand how work the password field in Django, that is to say, I think that this field hasn't got any max_length and it can be attacked with a buffer overflow. Is this possible? I am using de default Django User. -
AttributeError:'Student' object has no attribute 'check_password'
I user Custom User Model named Student which inherits Django User Model. I have problem in its logon when I want to use check_password. The error is that Student which is a custom user model has not such attribute. I wanna login students with the registered information by them. and the fields to login is identity_no and student_no. views.py: class StudentLoginSerializer(serializers.ModelSerializer): user = CustomUserSerializerForLogin() class Meta: model = Student fields = [ "user", "student_no", ] def validate(self, data): # validated_data user_data = data.pop('user', None) identity_no = user_data.get('identity_no') print("identity_no", identity_no) student_no = data.get("student_no") user = Student.objects.filter( Q(user__identity_no=identity_no) | Q(student_no=student_no) ).distinct() # user = user.exclude(user__identity_no__isnull=True).exclude(user__identity_no__iexact='') if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("This username or student_no is not existed") if user_obj: if not user_obj.check_password(student_no): # Return a boolean of whether the raw_password was correct. raise ValidationError("Incorrect Credential please try again") return user_obj I print(dir(user_obj)) and the output is: ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', … -
Get value from ChoiceField and returns filtered result
How do I get the value from a ChoiceField dropdown list and returns a list of filtered result back to frontend? Currently I can only show the values in the dropdown list but I failed to return back the selected result views.py def index(request): rest_list = Restaurant.objects.order_by('-restname') query_results = Restaurant.objects.all() region_list = regionChoiceField() if request.method == "POST": selected_region = request.POST.get("region") query_results = query_results.filter(region=selected_region) context = { 'rest_list': rest_list, 'query_results': query_results, 'region_list': region_list, } return render(request, 'index.html', context) index.html <body> <form method="post" name="dropdown">{% csrf_token %} {{ region_list }} </form> <table> {% for rest in query_results %} <tr> <td>{{ rest.restname }}</td> </tr> {% endfor %} </table> </body> models.py class Restaurant(models.Model): restname = models.CharField(max_length=200) # Field name made lowercase. phone = models.IntegerField() address = models.CharField(max_length=200) cuisine = models.CharField(max_length=200) region = models.CharField(max_length=200) last_modify_date = models.DateTimeField() created = models.DateTimeField() def __str__(self): return self.restname -
Django filter list of card types only the latest
I have a Django model of some different card types How can I get only the latest of each type in the filter? cards.filter(card_type__in=[1,2]) -
Django + Docker best practice: use runserver or wsgi.py?
I've been reading a lot of blog posts (like this one) on how to deploy Django in a containerized Docker environment. They all use the runserver command in the docker-compose.yml. Even the Docker documentation does this. This suprises me, since using the Django web server is not recommended for production! What is recommended is pointing the webserver to wsgi.py. However, none of the articles I've found on Django and Docker explain why they use runserver instead of pointing apache or nginx to wsgi.py. Why would all these articles use the built-in Django development webserver to handle requests, instead of a full blown webserver like apache or nginx? Isn't the point of using containers in development, to keep that environment as close to production as possible? Then why build a not-production-ready environment? -
Forcing sql_mode to "STRICT_TRANS_TABLES" still got warning Django
I'm using Django 2.1.3 ,pymysql 0.9.2, mysql 5.7, python3.5 sql_mode in mysql: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION db setting in django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', ..., 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8mb4' }, } And I always get warning like this: /venv3.5/lib/python3.5/site-packages/pymysql/cursors.py:170: Warning: (3135, "'NO_ZERO_DATE', 'NO_ZERO_IN_DATE' and 'ERROR_FOR_DIVISION_BY_ZERO' sql modes should be used with strict mode. They will be merged with strict mode in a future release.") result = self._query(query) /venv3.5/lib/python3.5/site-packages/pymysql/cursors.py:170: Warning: (3090, "Changing sql mode 'NO_AUTO_CREATE_USER' is deprecated. It will be removed in a future release.") result = self._query(query) Why I got the warning like above? Any commentary is very welcome. great thanks. -
How can I get return value from a web-service with django/python
I am posting some parameters to a web-service as follows: requests.post("http://**.***.**.**:****/MyLogin/services/DBConnection/callLoginProcedure?inputPhoneNumber=" + phone + "&inputPassword=" + password) The "callLoginProcedure" returns an integer value but I couldn't manage to get that value. How can I get this return value? views.py: def index(request): post = request.POST.copy() if post.get('login_button'): phone = post.get('phone_num') password = post.get('password') requests.post("http://68.183.75.84:8080/Calculator/services/DBConnection/callLoginProcedure? inputPhoneNumber=" + phone + "&inputPassword=" + password) r = request.GET.get("return", "-1") # if r == 1: # messages.info(request, 'successful!') # else: # messages.info(request, 'unsuccessful!') messages.info(request, r) return render(request, 'login/index.html') urls.py: urlpatterns = [ url(r'^$', views.index, name = 'index'), path(r'^$', views.index, name = 'script'), ] -
Django AttributeError NoneType has no attribute strip
I'm a Django beginner and I don't know why I'm getting this AttributeError at /id_finder/forms/ 'NoneType' object has no attribute 'strip' everytime I try to submit the form. Can someone take a look at my code below, maybe I'm not doing something correctly. forms.py class UserForm(forms.Form): first_name = forms.CharField(max_length = 15,required = True) last_name = forms.CharField(max_length = 15,required = True) email = forms.EmailField(max_length = 50,required = True) phone_number = forms.CharField(max_length = 14,required = True) password = forms.CharField(max_length = 30,widget = forms.PasswordInput(),required = True) region = forms.ModelChoiceField(queryset=Region.objects.all(),empty_label = None,required = True) district = forms.ModelChoiceField(queryset=District.objects.all(),empty_label = None,required = True) models.py class User(models.Model): FirstName = models.CharField(max_length = 15) LastName = models.CharField(max_length = 15) PhoneNumber = models.CharField(max_length = 14) Email = models.EmailField(max_length = 50) Password = models.CharField(max_length = 30) Date = models.DateTimeField(auto_now_add = True) Region = models.OneToOneField('Region', on_delete = models.PROTECT) District = models.OneToOneField('District', on_delete = models.PROTECT) def __str__(self): return "{0} {1}".format(self.FirstName,self.LastName) class Region(models.Model): RegionName = models.CharField(max_length = 20) def __str__(self): return self.RegionName class District(models.Model): DistrictName = models.CharField(max_length = 30) Region = models.ForeignKey(Region, on_delete = models.PROTECT) def __str__(self): return self.DistrictName views.py def form(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): obj = User() # create a new model object #process form data obj.first_name … -
Problem with {% url 'something:somthing' %}
I want to make the url go as {% url 'namespace:name' %} but it don't work! I did everything according to the documentation, but all my attempts were in vain. My CartDetail.html .......... </tr> </tbody> </table> <p class="text-right"> <button href="{% url 'shop:ProductList'%}" class="btn btn-info">Продолжить Шопинг</button> <button href="#" class="btn btn-danger">Оформить заказ</button> </p> </div> {% endblock %} My shop/urls.py from django.contrib import admin from django.urls import path,re_path from . import views urlpatterns = [ re_path(r'^(?P<category_slug>[-\w]+)/$', views.ProductList, name='ProductListByCategory'), re_path(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.ProductDetail, name='ProductDetail'), re_path(r'^$', views.ProductList, name='ProductList'), ] And my main url.py from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^cart/', include(('cart.urls', 'cart'), namespace='cart')), path('', include(('shop.urls', 'shop'), namespace='shop')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) What should I to do -
Mocking DynamoDB object
I am trying to mock a AWS DynamoDB. But, it is giving "Resource not found error" even after creating a table and sending the same mocked Boto3 resource object. test_views.py from django.test import Client, TestCase, override_settings from moto import mock_dynamodb2 import boto3 import mock @mock_dynamodb2 def mock_ddb(*args): dynamodb = boto3.resource('dynamodb') return dynamodb @mock_dynamodb2 def mock_ddb_create_table(*args): dynamodb= mock_ddb() table = dynamodb.create_table( TableName='test_table', KeySchema=[ { 'AttributeName': 'id', 'KeyType': 'HASH' } ], AttributeDefinitions=[ { 'AttributeName': 'id', 'AttributeType': 'S' }, ], ProvisionedThroughput={ 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5 } ) class TestMappings(TestCase): def setUp(self): self.client = Client() @mock.patch('app.views.create_ddb_object',side_effect=mock_ddb) @mock_dynamodb2 def test_reject_supplier(self, mock_ddb_obj): table = mock_ddb_create_table() table.put_item( Item={ 'id':'1', 'name':'test' } ) response = self.client.post('/app/view_1/',{'id': '1',}) self.assertEqual(response.status_code, 400) Views.py ddb = create_ddb_object() def views_1(request): id = request.POST.get('id') table = ddb.Table('test_table') response = table.scan( FilterExpression=Key("id").eq(id) ) print(response["Items"]) Error : : An error occurred (ResourceNotFoundException) when calling the Scan operation: Requested resource not found -
Is there any way to make the wagtail body field readonly?
I have a question. I'm developing blog app with wagtail. main point about blog page: Writer can write "title", "introduction" and "body". Firstly, writer can submit title. After finishing "title task", writer can edit and submit body. When writer do title task, writer can not edit body field. Furthermore, when writer do body task, writer can not edit title field. I want to Change permission dynamicaly for titleField and bodyField(RichTextField) but I could not figure out how to its. I thought editting hook about "@hooks.register("after_edit_page")" in wagtail_hooks.py can reach resolving. I tried to use PagePermissionHelper, PermissionHelper. thank you -
how I get selected value from options using ModelChoiceField(queryset=...) in django
class Model_Neural_form(forms.ModelForm): allMod = forms.ModelChoiceField(queryset=Model_Neural.objects.all()) class Meta: model = Model_Neural fields = ["nom_mod", "modl"] def __init__(self, *args, **kwargs): super(Model_Neural_form, self).__init__(*args, **kwargs) self.fields['allMod'].label = '' -
Mod_wsgi doesn't load page on Apache server
I'm trying to build a Django app in python to practice, and after a bit I wanted to deploy it to my local Wamp server. I managed to install mod_wsgi module but I'm finding a few problems in the final configuration, mainly because most of guides and tutorials are for Ubuntu, while I'm using Windows. The Apache httpd.conf file contains: LoadFile "c:/program files (x86)/microsoft visual studio/shared/python37_64/python37.dll" LoadModule wsgi_module "c:/program files (x86)/microsoft visual studio/shared/python37_64/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/program files (x86)/microsoft visual studio/shared/python37_64" WSGIScriptAlias / "C:/wamp64/www/provaDjangoApp2/provaDjangoApp2/wsgi.py" WSGIPythonPath "C:/wamp64/www/provaDjangoApp2/provaDjangoApp2;C:/wamp64/www/provaDjangoApp2" <Directory "C:/wamp64/www/provaDjangoApp2/provaDjangoApp2"> <Files wsgi.py> Require all granted </Files> </Directory> The Apache httpd-vhosts contains: <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On WSGIScriptAlias / "C:/wamp64/www/provaDjangoApp2/provaDjangoApp2/wsgi.py" <Directory "C:/wamp64/www/provaDjangoApp2/provaDjangoApp2"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/wamp64/www/provaDjangoApp2/static" <Directory "C:/wamp64/www/provaDjangoApp2/static"> Require all granted </Directory> </VirtualHost> And this is wsgi.py file in my Django app: import os import sys import site # Add the app's directory to the PYTHONPATH sys.path.append('C:/wamp64/www/provaDjangoApp2') sys.path.append('C:/wamp64/www/provaDjangoApp2/provaDjangoApp2') os.environ['DJANGO_SETTINGS_MODULE'] = 'provaDjangoApp2.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "provaDjangoApp2.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I effectively don't know if these configurations are ok, but when I open my localhost it's shown "500 Internal Server Error" error. -
Allowing other characters than numbers in a form for a BigIntegerField
I'm trying to allow users to enter other characters than numbers in a form that has a BigIntegerField. The numbers can be very large, such as 149648594350 / 149.648.594.350 and to avoid mistakes in the input I want to allow "separators" in the input. My idea was to change the input to a TextInput and then create a Form that cleans the input and strips everything but numbers in the cleaned data. This is the code I have: class Score(models.Model): score = models.BigIntegerField(null=False, blank=False) game = models.ForeignKey(Game, null=False, blank=False, on_delete=models.PROTECT) player = models.ForeignKey(Player, null=False, blank=False, on_delete=models.PROTECT) class ScoreForm(ModelForm): def clean_score(self): print("CLEANING SCORE") class Meta: model = Score fields = '__all__' class ScoreCreateView(CreateView): template_name = "register_score.html" success_url = reverse_lazy('registered_score') model = Score form_class = ScoreForm def get_form(self, form_class=None): form = super().get_form(form_class) form.fields["score"].widget = TextInput() return form However, there seems to be some early validation of the input that ends up giving me a "Enter a whole number."-error and clean_score isn't running. Any ideas how to get around this, or to do it a completely different way? Thanks for any help. -
DRF - a better way to write double nested serializers
I am building a todo app that can have comments posted on to the todo. For that to work, I have made a writable double nested serializer. It works, but the update method I have written is difficult to understand, and so I am trying to make it more readable. Is there a better(or standard way) to write an update method for a double nested serializer? I have read the docs for nested serializers in the official documents. https://www.django-rest-framework.org/api-guide/serializers/ models.py class CustomUser(AbstractUser): def __str__(self): return self.email class Todo(models.Model): publisher = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="todos", ) title = models.CharField(max_length=50) pub_date = models.DateTimeField('date published') description = models.CharField(max_length=800) is_done = models.BooleanField(default=False) def __str__(self): return self.title class Comment(models.Model): subject = models.ForeignKey( Todo, on_delete=models.CASCADE, related_name="comments", ) publisher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=50, default=None) pub_date = models.DateTimeField('date published') description = models.CharField(max_length=800) def __str__(self): return self.description serializers.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ( 'url', 'title', 'pub_date', 'description', ) read_only_fields = ( 'url', 'pub_date', ) class TodoSerializer(serializers.ModelSerializer): comments = CommentSerializer(required=False, many=True) class Meta: model = Todo fields = ( 'url', 'title', 'pub_date', 'description', 'is_done', 'comments' ) read_only_fields = ( 'url', 'pub_date', ) class UserSerializer(serializers.ModelSerializer): todos = TodoSerializer(required=False, many=True) class Meta: model = CustomUser … -
Django field model for HTML parser?
The contents of my models.py looks like this: from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length=256) pub_date = models.DateTimeField() image = models.ImageField(upload_to='media/') body = models.TextField() def __str__(self): return self.title def pub_date_pretty(self): return self.pub_date.strftime('%A %d %B %Y @ %-I:%M:%S %p') def summary(self): return self.body[:350] Lines 5 through 8 initiate the model class variables for my blog dashboard. My dashboard looks like this. There is a title, pub date, image and body. The Udemy instructor suggests consulting the official Django doc for field types/options. I’m not sure I really understand most of it. There is just so much information there. My question for all of you: Which field option or field type initiates an HTML parser for body text? I mean, when I go to to create a new blog post, how do I create rich text with HTML formatting buttons like bold, underline and italics? It’s not really the buttons I care about. I just want my HTML tags to parse. Take note of the HTML tags I’ve circled in red here. How do I get the h5, hr and em to parse? Is there a field option/type for this? I don’t see it in … -
Access primary key of a model which is in foreign relationship to another model
Suppose this code We want to create a student using create view in a particular school, how to access the primary key(id) of the school?How to define the get_absolute_url(self): when we dont know how to link this student model to School model? class School(models.Model): name = models.CharField(max_length = 264) principal = models.CharField(max_length = 264) location = models.CharField(max_length = 264) class Student(models.Model): name = models.CharField(max_length=264) age = models.PositiveIntegerField() school = models.ForeignKey(School, on_delete=models.CASCADE, related_name = 'students') How to define the get_absolute_url(self): when we dont know how to link this student model to School model? -
how to login a Custom User Model in django rest API framework
I defined a Custom User Model in models.py whose name is Student. This model inherits Django User. I can sign up student correctly, but when I want to login , I get error. I want to login with identity no and student no which exists in database when a student signs up. models.py: class CustomUser(AbstractUser): USER_TYPE_CHOICES = ((1, 'student'), (2, 'professor'),) username = models.CharField(max_length=50, unique=True) user_type=models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, null=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=100) identity_no = models.PositiveIntegerField(default=0) email = models.EmailField(max_length=300) class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) entry_year = models.PositiveIntegerField() student_no = models.PositiveIntegerField() serilizers.py: class CustomUserForLogin(serializers.ModelSerializer): class Meta: model = CustomUser fields = ( 'identity_no', ) class StudentLoginView(serializers.ModelSerializer): user = CustomUserForLogin() class Meta: model = Student fields = [ "user", "student_no", ] def validate(self, data): # validated_data identity_no = data.get('identity_no') print("identity_no", identity_no) student_no = data.get("student_no") print("student_no", student_no) # to search username or email is a user Model user = Student.objects.filter( Q(identity_no=identity_no) | Q(student_no=student_no) ).distinct() print("user", user) if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("This username or student_no is not existed") if user_obj: if not user_obj.check_password(student_no): # Return a boolean of whether the raw_password was correct. raise ValidationError("Incorrect Credential please try again") return user_obj views.py: class StudentloginView(APIView): permission_classes = … -
Combining django queryset objects having similar values
It's an eCom site that I am working on. I need to filter results based on email, as in obtain all those orders placed by this email account. On executing the query OrderItem.objects.filter(order__email='john@john.com').select_related('order') I get queryset object for each product. So if an order had multiple products then each product is a set on it's own. What I need is all items combined in the one set for an order ID so that I can iterate through them in the template. OrderItem.objects.filter(order__email='john@john.com').select_related('order').values('order_id').annotate(ct=Count('pk')) - This query gets all those IDs and shows how many sets are there per ID. Likewise I just need the results but with other fields like created_date, order_id, transaction_id, product. I have explored the django documentation but don't seem to find an appropriate solution. Another option is to manually loop through each item in the queryset and segregate based on the order_id having multiple items but then again that doesn't seem efficient. So any thoughts on how to proceed would be great. Models are below: class Order(models.Model): payment_date = models.DateTimeField(blank=True, null=True) created_date = models.DateTimeField(auto_now_add=True) transaction_id = models.CharField(max_length=256, blank=True, null=True) email = models.EmailField(max_length=128, blank=True, null=True) def __str__(self): return "Order #{},Date:{}".format(self.id,self.created_date) class OrderItem(models.Model): product = models.ForeignKey(PRODUCT_VARIANT_MODEL, on_delete=models.DO_NOTHING) quantity = …