Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set daily update limit for django model(db)?
Hi I'm having one Django web app where My model A contains 1000 records and I want to set a daily update limit for example if users are updating that data by uploading a .xls file then it should count how many records updated and once it is more than 500 then the user should get an Error message(Is there Any easy way to implement this at file processing level). Can Anyone help me how to implement this (Is there an SQLite parameter that I can mention in settings.py) below is my upload code. (Here I have tried to store the count value and comparing it with half of the record but again how to reset it after 12/certain time/hrs?) def CTA_upload(request): try: if request.method == 'POST': movie_resource = CTAResource() ##we will get data in movie_resources#### dataset = Dataset() new_movie = request.FILES['file'] if not new_movie.name.endswith('xls'): messages.info(request, 'Sorry Wrong File Format.Please Upload valid format') return render(request, 'apple/uploadinfosys.html') messages.info(request, 'Uploading Data Line by Line...') imported_data = dataset.load(new_movie.read(), format='xls') count = 1 for data in imported_data: value = CTA( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], ) count = count + 1 value.save() # messages.info(request, count) # time.sleep(1) messages.info(request, 'File Uploaded … -
Heroku does not upgrade python version
I am trying to deploy a django project in Heroku but the package 'django-mongoengine' needs a python version >=3.7. I have declare the ``runtime.txt`` file with one of the aviable python versions for Heroku but when I deploy the project, python-3.6.12 is still being installed. ``` Total 4 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Python app detected remote: -----> Installing python-3.6.12 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting Django==3.0.5 remote: Downloading Django-3.0.5-py3-none-any.whl (7.5 MB) remote: Collecting django-mongoengine==0.4.4 remote: Downloading django-mongoengine-0.4.4.tar.gz (186 kB) remote: Installing build dependencies: started remote: Installing build dependencies: finished with status 'done' remote: Getting requirements to build wheel: started remote: Getting requirements to build wheel: finished with status 'done' remote: Preparing wheel metadata: started remote: Preparing wheel metadata: finished with status 'done' remote: ERROR: Package 'django-mongoengine' requires a different Python: 3.6.12 not in '>=3.7' remote: ! Push rejected, failed to compile Python app. ``` The content of my runtime file is: ``` python-3.7.9 ``` And my Procfile file is: web: gunicorn graffitisWeb.wsgi Also the … -
when i tried to add urls in mysite directory nd checking the default server it shows like this?
i don not makesence how do get from it? Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite01.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
DjangoREST - How can I make my view/serializer more efficient on the server?
I'm using a serializer to extract a specific object from my models, followed by using said object field as a parameter in URL's via requests. I'm not getting any errors and everything is working fine, however I think it can be optimized better and be more efficient on the server. serializer.py class BucketListExtraDataSerializer(serializers.ModelSerializer): bucket_return = serializers.SerializerMethodField() bucket_sectors = serializers.SerializerMethodField() class Meta: model = Bucket fields = ('id','stock_list','bucket_return','bucket_sectors') def get_bucket_return(self, obj): print(obj.stock_list) if obj.stock_list: symbols_unicode = (','.join(map(str, obj.stock_list))) print(symbols_unicode) postgrest_urls = f"http://localhost:3000/rpc/bucketreturn?p_stocks=%7B{symbols_unicode}%7D" bucket_return = requests.get(postgrest_urls, headers={'Content-Type': 'application/json'}).json() return bucket_return def get_bucket_sectors(self, obj): if obj.stock_list: symbols_unicode = (','.join(map(str, obj.stock_list))) postgrest_urls = f"http://localhost:3000/rpc/bucketsectors?p_stocks=%7B{symbols_unicode}%7D" bucket_sectors = requests.get(postgrest_urls, headers={'Content-Type': 'application/json'}).json() return bucket_sectors I don't think it's optimal having multiple SerializerMethodField()'s. Which makes me wonder if I should translate all the extra requests def_bucket_return + def_buket_sectors into a view instead. I have doubts that in the future things can get really slow if a user has multiple objects. view.py class BucketListExtraData(generics.ListAPIView): permission_classes = [IsAuthenticated] serializer_class = BucketListExtraDataSerializer queryset = Bucket.objects.all() Disclaimer: my localhost:3000 is not an issue. Focusing on how I set up my serializer and view. Any recommendations on how I can optimize my serializer and view better to retrieve and display data quicker to … -
where i can host django on aws to have acces on cpanel and database
hello everyone am begginer sorry for my eng, i have bucket on amazon aws e3 whitch i contact by dns to subdomain and i made that for upload different resolution images for original and one for timeline for low resolution i want to size how much far it goes to learn properly what i need for and i have python api for back end and i will make next time front end , i am hosting on godaddy and i want to host on amazon but dont get and bunch of settings and by ssh its hard to control files how i can host my site to work on cpanel and lunch rest api to have acces on database can you guys links some source about that? thanks so much -
How to create a model in Django based on the instance of another model, but filtered
I am new to Django, I am searching a way to create a model in Django based on the instance of another model, but filtered. I have a table called Person, which has name and role, in my models.py: class Person(models.Model): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=100) role = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'person' What I want is to be able in my admin.py to call some subclass, which will display only actors (role="actors"): @admin.register(Actor) class Actor(admin.ModelAdmin):... Is it possible? Or do I have to create one more table only with actors? I know that I can use list_filter = ('role',), but this is not what I am searching for, I need actors exclusively. I see solution as something like this: class Actor(models.Model): objects = Person.objects.filter(role='actor') class Meta: verbose_name = 'actor' or class Actor(Person): self.objects.filter(role='actor') class Meta: verbose_name = 'actor' That obviousely does not work. -
How do you render a image in django?
I've been trying to render this image in django template but can't seem to accomplish it. Html: <span><a href="{% url 'logout' %}">Logout</a></span> {% for imagess in userimage %} <img src="{{ UserProfile.avatar }}"> {% endfor %} models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") avatar = models.ImageField(upload_to = "avatars/", null=True, blank=True) views to render the image: def imageprofile(request): userimage = UserProfile.objects.all() context = {'userimage': userimage} return render(request, 'leadfinderapp/dashboard.html', context) Any help I would really appreciate it. Where I'm getting it wrong? -
Plotly Dash - Pattern Matching Callbacks Not Working Properly
here is some sample code that i have been trying to run from plotly dash's 'pattern matching callbacks examples page'. For the life of me, i cannot see what is wrong - the only error i get in the browser is Syntax Error - unexpected end of JSON input. I can see that the problem only occurs when i try to register the last callback with the pattern matching syntax. If it helps, I am using DjangoDash, so i can integrate dash with Django. My code is below: Thanks! import dash import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash import dash_bootstrap_components as dbc from dash.dependencies import Input, Output, State, MATCH, ALL from dash.exceptions import PreventUpdate from django_dash.app import app layout = html.Div([ dbc.Button("Add Filter", id="dynamic-add-filter", n_clicks=0), html.Div(id='dynamic-dropdown-container', children=[]), ]) @app.callback( Output('dynamic-dropdown-container', 'children'), [Input('dynamic-add-filter', 'n_clicks')], [State('dynamic-dropdown-container', 'children')] ) def display_dropdowns(n_clicks, children): new_element = html.Div([ dcc.Dropdown( id={ 'type': 'dynamic-dropdown', 'index': n_clicks }, options=[{'label': i, 'value': i} for i in ['NYC', 'MTL', 'LA', 'TOKYO']] ), html.Div( id={ 'type': 'dynamic-output', 'index': n_clicks } ) ]) children.append(new_element) return children @app.callback( Output({'type': 'dynamic-output', 'index': MATCH}, 'children'), [Input({'type': 'dynamic-dropdown', 'index': MATCH}, 'value')], [State({'type': 'dynamic-dropdown', 'index': MATCH}, 'id')] ) def display_output(value, id): return html.Div('Dropdown … -
'Python manage.py runserver' "ValueError: Unable to configure handler 'mail_admins'".:
I'm working on a Django project. When starting the server I get "ValueError: Unable to configure handler 'mail_admins'". I'm in the correct directory, with virtual environment started. I can't make migrations, same error apears. Everything was working fine was able to start the server on this method in the past with no problem, until today. Thanks in advance! Version: Windows 10 Python 3.8.1 Django==3.1.5 frego@Yisus-Robles MINGW64 ~/Desktop/news $ python manage.py runserver Traceback (most recent call last): File "c:\users\frego\appdata\local\programs\python\python38\lib\logging\config.py", line 563, in configure handler = self.configure_handler(handlers[name]) File "c:\users\frego\appdata\local\programs\python\python38\lib\logging\config.py", line 744, in configure_handler result = factory(**kwargs) File "C:\Users\frego\.virtualenvs\frego-6ij68a4f\lib\site-packages\django\utils\log.py", line 89, in __init__ self.reporter_class = import_string(reporter_class or settings.DEFAULT_EXCEPTION_REPORTER) File "C:\Users\frego\.virtualenvs\frego-6ij68a4f\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "c:\users\frego\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\frego\.virtualenvs\frego-6ij68a4f\lib\site-packages\django\views\__init__.py", line 1, in <module> … -
Use of api key in Django
I´m trying to consume a web services with an api key. I've got the 200 answer but I really don´t know how to show the results. I need some help or guide to do it correctly. import requests headers = {'Content-Type': 'application/x-www-form-urlencoded'} url='http://plataforma.devteame.ml/plugin/chamilo_app/rest.php' response = requests.post(url, params= {'action': 'loginNewMessages','username':'demo','password': 'demo'}, headers=headers) if response.status_code == 200: return response.json() -
How to serve static files with django-rest framework?
I am new to Django development and I want to deploy my project on Azure WebApp service. When I switch to DEBUG = False, I get this error : The resource from “http://127.0.0.1:8000/static/css/index.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). Yet, I followed the steps described in this post : ALLOWED_HOSTS and Django I understood Django does not serve the static files by itself, that's why I installed WhiteNoise and put in the Middleware. (As shown in the post above.) Thus I don't understand why I have this error. Here my settings.py : """ Django settings for WebApp project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'my_hidden_secret_key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', … -
Django : Image files not diplayed in templates
I am trying to create a blog and to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (Failed to load resource: the server responded with a status of 500 (Internal Server Error). Media Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'core/static'), ) Project urls.py: from django.conf.urls import include, url from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin' , admin.site.urls), path("", include("authentication.urls")), path("", include("app.urls")), ]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) App urls.py: from django.urls import path, re_path from django.conf.urls import include, url from app import views from . import views urlpatterns = [ path('', views.index, name='home'), url(r'^blog$', views.blog_view, name ='blog'), url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'), re_path(r'^.*\.*', views.pages, name='pages'), ] Views.py def blog_view(request): query = Post.objects.all().order_by('-date') context = {'post_list' : query} … -
django 1.8.6 django-datatable-view==0.8.2: export buttons not showing
I have an old django app that I am moving into a docker container. It uses: Django==1.8.6 django-datatable-view==0.8.2 django-extensions==1.5.9 django-formtools==1.0 This is my template: {% load static %} {% autoescape off %} <script src="{% static 'js/datatableview.js' %}"></script> <script> datatableview.auto_initialize = false; $(function(){ var table = datatableview.initialize($('.datatable'), { lengthMenu: [ [ 10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ], {% if editable %} fnRowCallback: datatableview.make_xeditable({}), {% endif %} {% if page_length %} bPaginate: true, iDisplayLength: {{ page_length }}, {% else %} bPaginate: false, {% endif %} {% if filter %} bFilter: true, {% else %} bFilter: false, {% endif %} {% if dom %} sDom: '{% if export %}B{% endif %}{{ dom }}', {% else %} sDom: 'lrftip', {% endif %} {% if export %} buttons: [ "copy", "print", "csvHtml5", "excelHtml5", "pdfHtml5" ], {% endif %} }); }); </script> {% endautoescape %} and this is the result: the working version (in another server and not running in a docker component) give this result: as you can see I am missing the export buttons: Copy, Print, CSV, etc Even if I remove the if statement around the buttons' code, the buttons are not showing: {% endif %} {% if … -
Django: form CSRF verification failed
This is my first Django project, however, I have a problem submitting the form. I'm getting 'CSRF verification failed'. It's a very simple form just 2 fields(frontpage) and on submit to display the same page. views.py def newsletter(request): if request.method == 'POST': name = request.POST('name') email = request.POST('email') newsletter = Newsletter(name = name, email = email) newsletter.save() return redirect('/newsletter/') models.py class Newsletter(models.Model): name = models.CharField(max_length = 200) email = models.CharField(max_length=100) publish_date = models.DateTimeField(default = datetime.now, blank = True) def __str__(self): return self.name admin.py class NewsletterAdmin(admin.ModelAdmin): list_display = ('name','publish_date') admin.site.register(Newsletter, NewsletterAdmin) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name = 'home'), path('events/', events, name = 'events'), path('news/', news, name = 'mainnews'), path('about/', about, name = 'about'), path('', newsletter), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) -
How to return DRF Forms data in the POST
So I have a class based view views/users.py where the POST is supposed to send the data from the form to the serializer to validated it and if its alright create the user and return me the data, but for some reason it returns me a 404 bad request. Here's the view: class UserSignUpAPIView(APIView): """ User sign up API view. """ permission_classes = [AllowAny] renderer_classes = [TemplateHTMLRenderer] template_name = 'users/signup.html' def get(self, request): serializer = UserSignUpSerializer return Response({'serializer': serializer,}) def post(self, request, *args, **kwargs): """ Handle HTTP POST request. """ serializer = UserSignUpSerializer(data=request.data) if serializer.is_valid(raise_exception=True): user = serializer.save() data = UserModelSerializer(user).data return Response(data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The get function is working fine, it returns the template but when I submit the form, it returns a 404 BAD Request. My serializer is the following serializers/users.py class UserSignUpSerializer(serializers.Serializer): """ User sign up serializer. Handle sign up data validation and user creation. """ email = serializers.EmailField( validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( min_length=4, max_length=20, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField( min_length=8, max_length=64 ) password_confirmation = serializers.CharField( min_length=8, max_length=64 ) first_name = serializers.CharField( min_length=2, max_length=30 ) last_name = serializers.CharField( min_length=2, max_length=30 ) birth_date = serializers.DateField() def validate(self, data): """ Check that passwords match. Check … -
How to redirect from FormView to a ListView after form validation
In my Django application, I would like to display a form where a user enters a name to search for Persons from an external data source (not model). I am using class-based generic views and have a working application (code attached below) with a minor inconvenience - I would like to see if there is a better way to do this. First, here's how I have done it: I have a Form with 3 fields (first, second and last name) and a clean() where I check if at least one field is populated A FormView which renders this form, and form_valid() method which does nothing at the moment (reasons will become clear shortly) An entry in urls.py to render this view and display the form in a template. The form is being submitted to a ListView with GET, and not the FormView itself (sad!) A ListView where I define get_queryset(self) because data comes from an external source, not a Model; and I use self.request.GET.get('first_name', '') etc. to retrieve query string values, make a connection to the external data source and get a Pandas dataframe which I convert to a list of records and render, paginated, in the template. An entry … -
Django TemplateDoesNotExist at templates
I created new project and can't find where the place where mistake was made. Django versiob - 3.1.5 Python 3.7.4 TemplateDoesNotExist at / index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.5 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: C:\Users\user\PycharmProjects\Django learning\Portfolio\venv\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\user\PycharmProjects\Django learning\Portfolio\venv\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\user\PycharmProjects\Django learning\Portfolio\landingpage', 'C:\Users\user\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\user\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\user\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\user\AppData\Local\Programs\Python\Python37', 'C:\Users\user\PycharmProjects\Django learning\Portfolio\venv', 'C:\Users\user\PycharmProjects\Django ' 'learning\Portfolio\venv\lib\site-packages', 'C:\Users\user\PycharmProjects\Django ' 'learning\Portfolio\venv\lib\site-packages\setuptools-40.8.0-py3.7.egg', 'C:\Users\user\PycharmProjects\Django ' 'learning\Portfolio\venv\lib\site-packages\pip-19.0.3-py3.7.egg'] structure: landingpage: --forms #app: urls views --landingpage: templates: index.html settings.py urls others ... landingpage/settings: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) project_name = "landingpage" BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # apps 'forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'landingpage.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] landingpage/urls: … -
Django Rest Framework Serializer - How to allow optional fields to be ignored when invalid?
I have a use case targeting developers sending extra data to my API. I want my API to have a strict typing system via Django Rest Framework Serializer validation. However, if a user sends partially invalid data, I want to ignore that data if the field is optional rather than return a 400 response. For example, consider a key-value tags field tags = serializers.DictField(child=serializers.CharField(), required=False) Valid data for the tags field might look like {"foo": "bar"}. Invalid data could look like {"foo": "bar", "invalid": {{"some": "object"}} as the value for "invalid" is an object and not a string. DRF is_valid will consider this invalid. validated_data will not be populated. > serializer.is_valid() False > serializer.validated_data {} Because this field is not required and other tags might be valid, I'd want this returned instead > serializer.is_valid() True > serializer.validated_data {'another_field': 'a', 'tags': [{'foo': 'bar']} Is there a way to make optional fields ignore invalid data instead of making the entire serializer invalid while still using a Django Rest Framework serializer and benefiting from the other validation and normalization performed? -
How to upload Multiple file data in Django?
How can i upload multiple photo or video in Django? The code below upload single file instead of multiple files. i also define attr for multiple files in forms.py and it's working for the selection of multiple files. but the form is only save single file in database. please can anybody tell me? how can i do what i want to do? I would be grateful for any help. models.py class Article(models.Model): title = models.CharField(max_length=300) file_data = models.FileField(upload_to='stories', blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) forms.py class ArticleForm(forms.ModelForm): file_data = forms.FileField(required=False, widget=forms.FileInput( attrs={'accept': 'image/*,video/*', 'multiple': True})) class Meta: model = Article fields = [ 'title', 'file_data', ] views.py class NewsCreateView(CreateView): form_class = ArticleForm template_name = 'create.html' success_url = '/' def form_valid(self, form): # check author validation form.instance.author = self.request.user return super().form_valid(form) -
How do I solve form not submiting in django
I have created a form without using the form model, but the form wouldn't submit any data and I dont get any error message. The html file <form action="{% url 'wiki:add_test' %}" method="post"> {% csrf_token %} <div class="input_form"> <label class ="label_title" for="entry_title">Title:</label> <input class="entry_title" type="text" name="entry_title" placeholder="Title"> </div> <br> <div class="input_form"> <div class="input_label"><label for="entry_content">Content:</label></div> <div class="input_field"> <textarea class="entry_content" name="entry_content" id="" cols="5" rows="2"></textarea> </div> </div> <div class="input_form"> <div class="title"></div> <div class="input_button"><input type="button" value="Add Entry"></div> </div> </form> The views.py def test1(request): return render(request, "encyclopedia/display_test.html",{ "lists": new_entry }) def add_test(request): if request.method == "POST": form1 = request.POST print(request.POST['entry_title']) list_item = form1['entry_title'] new_entry.append(list_item) return HttpResponseRedirect(reverse("wiki:test1")) return render(request, "encyclopedia/add.html") The urls.py from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("test1", views.test1, name="test1"), path("add_test", views.add, name="add_test"), ] I need help to know where I went wrong -
How to break the game when it reaches the score 10?
I'm working on Rock, Paper, Scissor game and I want to break the game when the score reaches 10(points) but I'm unable to do it. Can anyone tell me how to do that. I have used while loop for that but I can't get the actual output that I need. And what this stands for? #elif((player_input[1] - computer_input[1]) % 3 == 1): player_score = 0 computer_score = 0 options = [('rock',0), ('paper',1), ('scissors',2)] def player_choice(player_input): global player_score, computer_score computer_input = get_computer_choice() player_choice_label.config(text = 'You Selected : ' + player_input[0]) computer_choice_label.config(text = 'Computer Selected : ' + computer_input[0]) if(player_input == computer_input): winner_label.config(text = "Tie") elif((player_input[1] - computer_input[1]) % 3 == 1): player_score += 1 winner_label.config(text="You Won!!!") player_score_label.config(text = 'Your Score : ' + str(player_score)) else: computer_score += 1 winner_label.config(text="Computer Won!!!") computer_score_label.config(text='Computer Score : ' + str(computer_score)) #Function to Randomly Select Computer Choice def get_computer_choice(): return random.choice(options) -
Django ListView Multiple Pagination in Same Page
I was trying to make multiple pagination in the same page with out using any library. I followed this Multiple Pagination Method and successfully implemented it. However, one issue in this is say if I'm on page 3 on model_one, I click on next for model_two, then model_one resets to page 1, and model_two goes to page 2. Is there any way to retain the page of a table, while navigating through pages of another table? P.S.: If there is any library, please let me know as well. Found two versions of Django-Endless-Pagination, both seems to be abandoned around Django 1.8-2.0, and are more for Python2 than 3. TIA -
Search users function, doesn't work it comes back with error (django)
I am having some issue with the search users function in my django app , it comes back with the error image below: error result . Any ideas what I'm doing wrong ? error: Cannot resolve keyword 'username_icontains' into field. Choices are: date_joined, details, email, first_name, from_user, groups, id, is_active, is_staff, is_superuser, last_login, last_name, likes, logentry, password, post, profile, to_user, user_permissions, username Here is my code : views.py @login_required def search_users(request): query = request.GET.get('q') object_list = User.objects.filter(username_icontains=query) context ={ 'users': object_list } return render(request, 'users/search_users.html', context) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') slug = AutoSlugField(populate_from='user') bio = models.CharField(max_length=255, blank=True) friends = models.ManyToManyField('Profile', blank=True) def __str__(self): return str(self.user.username) def get_absolute_url(self): return "/users/{}".format(self.slug) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] search_users.html {% extends "feed/layout.html" %} {% load static %} {% endblock cssfiles %} {% block searchform %} <form class="form-inline my-2 my-lg-0 ml-5" action="{% url 'search_users' %}" method="get" > <input name="q" type="text" placeholder="Search users.." /> <button class="btn btn-success my-2 my-sm-0 ml-4" type="submit"> Search </button> </form> {% endblock searchform %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-8"> {% if not users %} <br /><br /> <h2><i>No … -
How to get current logged in user out of views(request) in django
I'm working on website whose an app which has class called Members whose a field that is related to the builtin User class from django.contrib.auth.models and it looks like class Members(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) member_image = models.ImageField(upload_to='unknown') member_position = models.CharField(max_length=255) ... So as you can see when I'm adding member_image as a user I have also to select the user which doesn't make sense to me because I want to detect which user is logged in and pass his/her id as default parameter like class Members(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=request.user.id) and after remove the user field in the admin panel like class MembersAdmin(admin.ModelAdmin): fields = ('member_image', 'member_position', ...) so that if the user field doesn't selected it will set the logged in user_id by default but to access request out of the views.py is not possible. so how will I achieve this I also tried the following answers Access session / request information outside of views in Django Accessing request.user outside views.py Django: How can I get the logged user outside of view request?, etc but still not get it -
CSS view changes after addition of bootstrap
I'm a beginner in web development. I am making a simple todo list app. I have designed a webpage which changes after addition of bootstrap. Code without bootstrap <!DOCTYPE html> <html> <head> <title>To Do List </title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'todo/styles.css' %}"> </head> <body> <div class="box" id="heading"> <h1>{{kindOfDay}}!</h1> </div> <div class="box"> {% for i in newListItems %} <div class="item"> <input type="checkbox" \> <p>{{ i }}</p> <a href="{% url 'todo:delete_item' i %}">X</a> </div> {% endfor %} <form class= "item" action="" method="post"> {% csrf_token %} <input type="text" name="newItem" placeholder="Add new item here"> <button type="submit" name="button">+</button> </form> </div> </body> </html> Image of webpage without bootstrap Code with bootstrap <!DOCTYPE html> <html> <head> <title>To Do List </title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'todo/styles.css' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <div class="box" id="heading"> <h1>{{kindOfDay}}!</h1> </div> <div class="box"> {% for i in newListItems %} <div class="item"> <input type="checkbox" \> <p>{{ i }}</p> <a href="{% url 'todo:delete_item' i %}">X</a> </div> {% endfor %} <form class= "item" action="" method="post"> {% csrf_token %} <input type="text" name="newItem" placeholder="Add new item here"> <button type="submit" name="button">+</button> </form> </div> </body> </html> Image of webpage after adding bootstrap Any help will be appreciated