Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the meaning of "=" when specifying a superclass in Python?
I have a question about the class definition below. In case it's relevant, the full code can be found here, and the class I stubbed out can be found on line no. 98. class BaseModelAdmin(metaclass=forms.MediaDefiningClass): pass I understand that BaseModelAdmin is extending forms.MediaDefiningClass, but what is the significance of metacalass=? Specifically: What does the assignment operator do in this context? How is the l-value (i.e. metaclass) used? -
javascript , python online game comunication
I have one problem I am not able to find subtle model for the app so basically , I have a page where 2 people are looking for a game and then they have some challenge to do. I am using Django and Vue as stack. So my idea was when someone looking for the game put user username into redis queue and then take first two , but how I do return on the client side data back ,is there any smart way to make communication between two clients? -
Django/Postgres: Parameterized Queriy does not work
i have just started diving into raw queries in django. i am trying to change a schema name in my postgres, but my SQL query does not work here's the code that i run in django shell: >>> from django.db import connection >>> cursor = connection.cursor() >>> query = "ALTER SCHEMA %s RENAME TO %s;" >>> data = ('thor', 'thor1') >>> cursor.execute(query, data) Error: django.db.utils.ProgrammingError: syntax error at or near "'thor'" LINE 1: ALTER SCHEMA 'thor' RENAME TO 'thor1' i believe that those quotes are the root of my problem. any idea how can i make this work ? -
Django Admin Page on New/Chage display objects not values
I am create a simple model and admin in Django. Below is the model class Article(models.Model): title = models.CharField(max_length=30) tags = models.TextField(default="") text = models.TextField(default="") category = models.ForeignKey('cms.Category', default="") status = models.ForeignKey('cms.Status', default="") class Meta: verbose_name_plural = "Articles" And below the admin registration Class ArticleAdmin(admin.ModelAdmin): @staticmethod def get_status(obj): return obj.status.status @staticmethod def get_category(obj): return obj.category.category list_display = ('title', 'get_status', 'get_category') Although I am getting the below, i.e. objects not values. Snapshot from Django Admin I am trying to resolve this and I would like to know where to look for. Thanks a lot -
Django/Json: Can i easily change how django serializes objects?
I have Serialized and dumped my objects like this: data = serializers.serialize("python", MyObject.objects.all()) dic = { 'Studium' : data} return JsonResponse(dic, safe=False) The response I get: {"Studium": [{"model": "djangoApp.studium", "pk": 538, "fields": {"studiumkode": "ABIOK", "studium": "ABIOK (anestesi/barnevern/intensiv/operasjon/kreftsykepleie"}}]} The response I want: {"Studium": {"studiumkode": "ABIOK", "studium": "ABIOK (anestesi/barnevern/intensiv/operasjon/kreftsykepleie"}} -
What is the simplest way to get user input in Django?
I want to get some user input, process it a little and present the same to the user. I need not save the inout to the database. What is the simplest way to do that in Django -
Django - What are the cons of importing a library inside a view?
Currently in my app in certain views I want to get the ip, so I installed an external library. However, I have this doubt: The standard way of working in django is something like: from library import xyz from library2 import yzx def view1(request): #### def view2(request): #### but since I only want to get the ip in certain views, I thought of something like: def view1(request): from library impor xyz ### def view2(request): #### but I know that's not the standard way to do it. What inconveniences can this cause? Should I import the library of the standard way (at the beginning of all the views)? -
What's the main difference between using ./manag.py and python manage.py in a virtual environment
I couldn't execute ./manage.py makemigrations for a Django project. However, I could use python manage.py makemigrations and python3 manage.py makemigrations. I am using pipenv to manage my virtual environment, while doing the above operations, I already activated my virtual environment which installed all packages including Django. manage.py #!/usr/bin/python3 """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings.base') try: from django.core.management import execute_from_command_line # noqa except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Content after type python directly: Python 3.7.5 (default, Nov 20 2019, 09:21:52) [GCC 9.2.1 20191008] on linux Type "help", "copyright", "credits" or "license" for more information. >>> My question is what is the main difference bewteen using ./manage.py makemigrations and python manage.py makemigrations in an activated virtual environment? How to resolve this issue? Thanks for your help. -
Django all over sudden has refused to load static files
Django server was loading the static files successfully but all over sudden it has refused to load the files what might be the problem? i am using Django 2.2.1 and Python 3.6 -
How to handle multiple forms in one function in views in Django
I have to handle two forms in one function: HTML page <form name="selectgenderform" method = "POST"> <select name='gender'> <option>Male</option> <option>Female</option> </select> <input type = 'submit' name ='searchbtn' value= 'search' > </form> <form name="selectionform" method = "POST"> <input type = 'hidden' name = 'valueofnumber' > <input type = 'submit' name = 'searchbtn' value= 'search' > </form> Views.py def formselection(request): if selectgenderform in request.POST: gender = request.POST.get('gender') ... elif selectionform in request.POST: value = request.POST.get('valueofnumber') My query is to handle multiple forms in one function but this will not according to my demand -
Facing issue with custom user authentication and oauth2 in django
I am making an application which has protected API and only an authenticated users should have access to it. To make use of the django's powerful authentication, I decided to extend its User model with some extra fields and customised. I am using the custom user model by extending AbstractUser Model. But Facing below issue while requesting the oauth2 token. Below is my code: class MyUser(AbstractUser): """Extended version of Django User Model""" is_email_verified = models.BooleanField( verbose_name="Email Verified?", default=False, choices=T_N_F_CHOICES, auto_created=True, help_text="This flag indicates if the email address is authentic and validated" ) mobile = PhoneNumberField( verbose_name="Phone Number", blank=True, null=True, unique=True ) is_mobile_verified = models.BooleanField( verbose_name="Mobile Verified?", default=False, choices=T_N_F_CHOICES, auto_created=True, help_text="This flag indicates if the mobile number is authentic and validated" ) profile_pic = models.ImageField( verbose_name="Profile Picture", upload_to=settings.UPLOAD_DIR, height_field=None, width_field=None, max_length=None, blank=True, null=True ) USERNAME_FIELD = "email" REQUIRED_FIELDS = ['mobile'] objects = CustomUserManager() def __str__(self): return self.email class Meta: managed = True db_table = "MyUser" verbose_name = "MyUser" verbose_name_plural = "MyUsers" settings.py ... AUTH_USER_MODEL = 'users.AlphaslateUser' CORS_ORIGIN_ALLOW_ALL = True ... INSTALLED_APPS = [ ... 'oauth2_provider', 'corsheaders', 'countries_plus', 'rest_framework', 'users', ] ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ] } ... AUTHENTICATION_BACKENDS = ( 'oauth2_provider.backends.OAuth2Backend', 'django.contrib.auth.backends.ModelBackend' ) ... MIDDLEWARE = [ ... … -
django makemigrations doesn't recognize new model
I created a new model with manage.py startapp supplier edited some stuff in the views, url and models. Now I execute python manage.py makemigrations but django doesn't recognize my new model "No changes detected" it says -
Django: how to create a ChoiceField/html Select element without a name?
I currently have a Django form that creates an html <Select> element for me:- class RegionSelectionForm(forms.Form): lstAll = [('', '(ALL)')] lstChoices = lstAll + list(region.objects.values_list('code', 'name').order_by('name')) RegionSelection=forms.ChoiceField(choices=lstChoices, widget=forms.Select(attrs={'class': 'form-control searchfields'}), required=False, label="") This gets passed via a view to a template that allows the user to select a constituency from another <select> element. The sole purpose of the RegionSelectionForm is to apply a region filter to the other <Select> using JavaScript and enable the user to more easily find what they want. It never gets used in a submit to specify GET request parameters. Yet it appears in the URL:- https://mydummysite.co.uk/test_map/?!!!!RegionSelection!!!!=&displayfind=Random&find=0&findtype=&maptype=normal I like using Python in the forms file to play with the data, tweak the options etc. It's a lot easier (for me) than using Django template tags in the actual template and iterate through it using a {% for ... %} loop and feels like a better place to put it. And it works fine. But I'm going to end up with quite a busy template with users being able to request various things and I want to generate GET requests that aren't cluttered with unused parameters. I want to lose the name="RegionSelection" attribute of the <select> element … -
Many items in requirements file for Heroku
I finished the Django tutorial yesterday and I wanted to put it on Heroku for fun. My requirements file has many files listed: alembic==0.9.3.dev0 apturl==0.5.2 asgiref==3.2.5 asn1crypto==0.24.0 Babel==2.4.0 blinker==1.4 Brlapi==0.6.6 certifi==2018.1.18 chardet==3.0.4 click==6.7 colorama==0.3.7 command-not-found==0.3 cryptography==2.1.4 cupshelpers==1.0 defer==1.0.6 distro-info===0.18ubuntu0.18.04.1 dj-database-url==0.5.0 Django==3.0.4 Flask==0.12.2 Flask-BabelEx==0.9.3 Flask-Compress==1.4.0 Flask-Gravatar==0.4.2 Flask-Login==0.4.0 Flask-Mail==0.9.1 Flask-Migrate==2.1.1 Flask-Paranoid==0.2.0 Flask-Principal==0.4.0 Flask-Security==1.7.5 Flask-SQLAlchemy==2.1 Flask-WTF==0.14.2 gunicorn==20.0.4 httplib2==0.9.2 idna==2.6 itsdangerous==0.24 Jinja2==2.10 keyring==10.6.0 keyrings.alt==3.0 language-selector==0.1 launchpadlib==1.10.6 lazr.restfulclient==0.13.5 lazr.uri==1.0.3 louis==3.5.0 macaroonbakery==1.1.3 Mako==1.0.7 MarkupSafe==1.0 netifaces==0.10.4 oauth==1.0.1 olefile==0.45.1 paramiko==2.0.0 passlib==1.7.1 pexpect==4.2.1 Pillow==5.1.0 protobuf==3.0.0 psutil==5.4.2 psycopg2==2.8.4 pyasn1==0.4.2 pycairo==1.16.2 pycrypto==2.6.1 pycups==1.9.73 pygobject==3.26.1 pyinotify==0.9.6 pymacaroons==0.13.0 PyNaCl==1.1.2 pyOpenSSL==17.5.0 pyRFC3339==1.0 python-apt==1.6.5+ubuntu0.2 python-dateutil==2.6.1 python-debian==0.1.32 pytz==2019.3 pyxdg==0.25 PyYAML==3.12 reportlab==3.4.0 requests==2.18.4 requests-unixsocket==0.1.5 SecretStorage==2.3.1 simplejson==3.13.2 six==1.11.0 SQLAlchemy==1.1.11 sqlparse==0.3.1 sshtunnel==0.1.4 system-service==0.3 systemd-python==234 ubuntu-drivers-common==0.0.0 ufw==0.36 unattended-upgrades==0.1 urllib3==1.22 usb-creator==0.3.3 wadllib==1.3.2 Werkzeug==0.16.0 WTForms==2.1 xkit==0.0.0 zope.interface==4.3.2 I don't know where these files came from. I didn't install them directly. I installed Django, postgressql, pgAdmin 4, etc. I didn't specifically install all these packages by name and I don't even know if they are required. It even shows Flask as a requirement but I have never used it. Also, when I try to put the code on heroku with git, alembic doesn't install on heroku because it says it can't find the proper version. -
Django - Image not being displayed in the webpage
In my project, I have a DetailView, so a user can view their profile. On here, I want to display their profile picture. However when I open the browser and go to the detail page, no profile picture is displayed. My code is displayed below. models.py: class User(AbstractUser): profilePic = models.ImageField(upload_to='profile_pics/', default='static/default-profile.png') views.py: class DetailProfile(generic.DetailView): model = User # Template that a users profile picture should be displayed in template_name = 'detail_profile.html' detail_profile.html: <img width="200px" src="{{ user.profilePic.url }}" alt=""> Error returned by the browser: GET http://localhost:8000/media/static/default-profile.png 404 (Not Found) urls.py (for the users apps): urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.login, name='login'), path('resetone/', views.resetone, name='resetone'), path('resetwo/', views.resetwo, name='resetwo'), path('viewprofile/<int:pk>', views.DetailProfile.as_view(), name='detail_profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) SETTINGS.PY: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'proj2/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Currently, all the users have the file default-profile.png assigned to their profile pic, however later I am going to implement the ability for users to change their profile pic. default-profile.png is stored in the static folder(Check my settings.py code above), and is also assigned to a user when they first signup. Does anybody know why this file isn't being … -
Django Signals.py. How to combine receiver's and initiate function in a new thread
which is the best way to combine Django receiver's from signals.py and initiate a function in a new thread. Example with post_delete and post_save : from django.db.models.signals import post_delete, post_save from django.dispatch import receiver @receiver(post_delete, sender=Application) def test_delete_function(sender, instance, **kwargs): if isinstance(instance, Application): deletefunc() @receiver(post_save, sender=Application) def test_save_function(sender, instance, **kwargs): if isinstance(instance, Application): savefunc() So, Q1: Is this a good way to express different receiver types - @receiver and then functions after that? Q2: When saving Application from the fronend with POST, test_save_function is initiated in the same thread. How to run test_save_function on a different thread? - I expected this to be handled by Django Framework, but it seems I need additional configuration? Thanks! -
How can i find my root user on Hostgator server?
i am a newbie. im learning python and i recently bought a server from hostgator in order to publish a site i deveoped in django and viewed it on localhost until now. when i bought the server from them i recived an email with username and password. i ssh'd through Putty to connect to the server but i found out i can't use sudo command. when i tried to use it... "sudo: effective uid is not 0, is sudo installed setuid root?" is all i get. i looked everywhere for an answer but i couldn't find Thank's for anyone who can help! -
Output print statement from external python script to Django website
I have a django site which accepts a user input (ip address) and have that user input to run in an external python script which scans the open ports. I already have it output like this from my external python script: ip: 10.10.10.10 portsOpen: [21, 80] I want it to have the output to the django site. My views.py: from django.shortcuts import render, render_to_response from subprocess import run,PIPE import requests import sys from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse # Create your views here. def index(request): return render_to_response('index.html') @csrf_exempt def external(request): inp=request.POST.get('param') out=run([sys.executable, 'D://Desktop//quanta//Quanta//testerfordjango.py',inp], shell=False) print(out) return render(request, 'index.html',{'data1':out.stdout}) The only output i get from the django site after the script has finished running is None I have tried using this but it seems not to work: return HttpResponse(out) -
get_user_model doesn't return a value
as my first project in Django I am creating a todo app, that lets people log in and see their own tasks that they created. For that, I need to save author info in single task data. From what I learned reading the documentation and doing lots of google-searching, the current approach is to use the get_user_model function from django.contrib.auth. The problem is, that whenever I try to use it in my model, it seems to not get the username from the currently logged in user. While printing the form.errors to my console, the output is: <ul class="errorlist"><li>added_by<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Seems like the get_user_model is not returning any value. Can anyone recommend a better approach for me to do that? Or is there something obvious that I missed? Here are the code snippets: models.py from django.db import models from django.contrib.auth import get_user_model class Task(models.Model): title = models.CharField(max_length=35) completed = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.title forms.py from django import forms from .models import * class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' widgets = { 'title': forms.TextInput(attrs={'class': 'new_task_text', 'placeholder': 'Add new task'}), } views.py @login_required def list_homepage(request): tasks = Task.objects.all() … -
How to set path of multiple custom apps in django?
Can anyone please help me with this. MyProject is the name of my project in django with two different apps HappyHomes and HappyHomesAdmin. I want to switch from HappyHomesto HappyHomesAdmin. How to set path in urls file? How many files in total I will need? And also how to set path of moving to different app in views.py file in django. I am here C:/Users/MaitRi/Desktop/PROJECT/MyProject/HappyHomes/templates/reg.html and want to move at C:/Users/MaitRi/Desktop/PROJECT/MyProject/HappyHomesAdmin/templates/home.html -
Django CreateView Object could not be created because the data didn't validate
Good day. I'm trying to create a object based on form input, i tesed out the data, everything is provided but, for some reason the form is not validated. I've also tried overriding form_valid(self,form) but the problem with that method was django never went to it as if it didn't exist. forms.py class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' views.py class CreatePost(CreateView): form_class = CreatePostForm template_name = 'dashboard/add-product.html' # success_url = redirect('user_posts:post_detail') def post(self, request, *args, **kwargs): form = CreatePostForm(request.POST) if self.form_valid(form): post = form.save(commit=False) post.user = request.user post.save() return redirect('user_posts:post_detail', args=post.slug) print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA') code in the template is basic form, not gona import it. data that has been passed via request.POST user 'b8a3b0b3-0eef-48ed-b257-a6f9bfdd5cda' title 'theetitle' main_description 'agdgdfg' slug '' main_image 'Bucee_Lee_smile.jpg' subtitle1 '' sub_description1 '' sub_image1 '' subtitle2 '' sub_description2 '' sub_image2 '' subtitle3 '' sub_description3 '' sub_image3 '' total_likes '' traceback points to this line if self.form_valid(form): -
Django how to forward URL named paramters
I'm new to django so i could be asking a dumb question, but how am i supposed to forward URL A's named parameter to URL B? For example: URL A = https://stackoverflow.com/questions?parameter=1 URL B = https://stackoverflow.com/ask What i actually want is: URL B = https://stackoverflow.com/ask?parameter=1 I need to do this because i need to pass those parameters to the view that is being called at the second url, could someone help me? -
How to get post form data using AJAX?
I'm trying to get the data from a post form using AJAX. I'm failing in some point because I can't access to the form's data. template.html <form method="POST" autocomplete="off" action="/index" id="mail_form_id"> {% csrf_token %} <input type="email" name="mail_input" id="mail_input"> <button type="submit" onclick="send_mailform()" ></button> ... views.py ... if request.is_ajax: print(request.POST['mail_input']) #This is not working script.js // I'm avoiding to refresh using this function var form = document.getElementById("mail_form_id"); function handleForm(event) { event.preventDefault(); } form.addEventListener('submit', handleForm); function send_mailform(){ var http = new XMLHttpRequest(); http.open("POST", "/index", true); http.setRequestHeader('X-CSRFToken', getCookie('csrftoken')); var mail_input = document.getElementById('mail_input').value; http.send(mail_input); } ... I've been searching and there are several solutions for django 1.X or using Jquery. I didnt put the getCookie function in scripts.js but it's working properly. I'm triying to avoid Jquery. Thank you in advance! -
Why will a CSRF POST request to 'localhost:8000' be successful, but '127.0.0.1:8000' will fail?
My frontend (React) and backend (Django) are decoupled, runnning on localhost:3000 and 127.0.0.1:8000 respectively. Consider the following frontend request: async function test() { let token = await getCsrfToken() // fetched from other endpoint let url = 'http://localhost:8000/test' let response = await fetch(url, { method: 'POST', headers: { 'X-CSRFToken': token, }, credentials: 'include', }) let response_text = await response.text() return response_text } test() to the following endpoint: def test(request): return HttpResponse('OK') It works fine. But if I change: let url = 'http://localhost:8000/test' to: let url = 'http://127.0.0.1:8000/test' it will fail with: Forbidden (CSRF cookie not set.): /test Per my understanding, localhost and 127.0.0.1 are supposed to be synonymous. Why isn't it so in this context? What confuses me even more is that the Django's development server explicitly runs on 127.0.0.1:8000. Note: I am using django-cors-headers middleware and the following CORS/CSRF settings: CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ['http://localhost:3000'] CSRF_TRUSTED_ORIGINS = ['localhost:3000'] -
Django multiple repeating dropdowns
I am repeating a Django Form dropdown as follow: html <form class="form-group" method="post"> {% csrf_token %} {{ form.X1}} {{ form.X1}} </form> where, model.py class MyModel(models.Model): X1 = models.ForeignKey(otherModel, on_delete=models.CASCADE) form.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' When I submit the form, I only see one instance of X1 being returned to my view. I don't see the second X1 value... How can I pass the second X1 as well?