Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What the difference between .save() and objects.create()?
What the fundamental difference between: CustomUser.objects.create(phone_number=phone_number, username=phone_number) and CustomUser(phone_number=phone_number, username=phone_number).save() When I must use first and when second? -
How To Show User Profile To Everyone By Link! in Django
How To Show User Profile To Everyone By Link! in Django I Want To Show User Profile To Everyone for-example if someone type this in browser domain.com/profile/1 Then Our First User Profile Want To Show But it's showing blank It's showing when user login but we need to show to everyone Here is my detail.html {% extends 'base.html' %} {% block body_block %} <h1 class="posttitle">{{user.username}}</h1> {% endblock %} Here is my Views.py def profile_detail(request,pk): model = get_object_or_404(User, pk=pk) return render(request,'profile_detail_view.html') If You Need More Files Like Model,Views,Url Something Let me down in comment i will update my question Any Help Will Be Appreciated Thanks!! -
Django Settings not picking up user
I'm working on my first Django project and struggling to connect it to my MySQL database. My project is struggling to pick up database values from settings. Here is my issue. settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'USER': 'admin', } } I have removed the password, host, and port for now as I'm trying to isolate the issue with user. I run python manage.py diffsettings and the result includes, clearly containing the user: DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'USER': 'admin', 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, 'PASSWORD': '', 'HOST': '', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}}} However, when I run python manage.py migrate, I get the following error: django.db.utils.OperationalError: (1044, "Access denied for user ''@'localhost' to database 'django'") You can see here that the user is missing. It's showing ''@'localhost' instead of 'admin'@'localhost' The strange part is that the database name is being picked up, but the user isn't. Any ideas on what I'm doing wrong? -
Django Channels: How to restrict one session of a game to two connections per session
I am trying to make a real-time two-player game using Django channels. How can I make it so that there can be multiple game sessions and per game session, there can only be two connections? To further elaborate, what I want is when a person starts the game, the system will wait for another player if there isn't already, and once the second person joins, both players can start playing. If a third person appears then they cannot enter this particular game session. Instead, a new game session is made for this third person, which will then wait for a fourth person to make a connection and join their game and so on. Any help would be greatly appreciated, as well as any example code or links to relevant tutorials. Thanks! -
Django Error: int() argument must be a string, a bytes-like object or a number, not 'User'
How To Fix This Error: int() argument must be a string, a bytes-like object or a number, not 'User' I Want to Create User Profile I'm Tired To Fix! I Want To Create User Page When He Register But I get this error again and again Base.Html {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link navaour" href="{% url 'profile' pk=user.pk %}"><i class="fa fa-user"></i>&nbsp; Profile</a> </li> <li class="nav-item"> <a class="nav-link navaour" href="{% url 'logout' %}"><i class="fa fa-power-off"></i>&nbsp; Logout</a> </li> {% else %} <li class="nav-item"> <a class="nav-link navaour" href="{% url 'register' %}"><i class="fa fa-check-square-o"></i>&nbsp; Sign up Free</a> </li> <li class="nav-item"> <a class="nav-link navaour" href="{% url 'login' %}"><i class="fa fa-user"></i>&nbsp; Login</a> </li> {% endif %} Urls.py from . import views from django.urls import path urlpatterns = [ path('', views.index,name='index'), path('accounts/signup/', views.user_reg,name='register'), path('profile/<int:pk>',views.profile_detail,name='profile') ] Views.py def profile_detail(request,pk): pk = User.objects.get(pk=pk) model = get_object_or_404(User, pk=pk) template_name = 'profile_detail_view.html' Here is my Models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class user_register_model(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) def get_absolute_url(self): return reverse("profile",kwargs={'pk':self.pk}) Any Help Appreciated Thanks! -
Django mod wsgi Throws an Apache 404 Error
I have tried to launch my django application to production using mod_wsgi on windows following this tutorial https://www.codementor.io/aswinmurugesh/deploying-a-django-application-in-windows-with-apache-and-mod_wsgi-uhl2xq09e, however when I try to access localhost I receive an Apache 404 error (not a django 404 error). Is it a problem with my httpd.conf file? In my httpd.conf I have added LoadFile "C:/Users/samuel/AppData/Local/Programs/Python/Python37/python37.dll" LoadModule wsgi_module "C:/users/samuel/Envs/avatarWebsite/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "C:/Users/samuel/Envs/avatarwebsite" WSGIScriptAlias / "C:/Users/samuel/PycharmProjects/avatarWebsite/avatarWebsite/wsgi.py" WSGIPythonPath "C:/Users/samuel/PycharmProjects/avatarWebsite" <Directory "C:/Users/samuel/PycharmProjects/avatarWebsite" <Files wsgi.py> Require all granted </Files> </Directory> htppd-vhosts.conf: <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "logs/avatarWebsite.error.log" CustomLog "logs/avatarWebsite.access.log" combined WSGIScriptAlias / "C:\Users\samuel\PycharmProjects\avatarWebsite\avatarWebsite\wsgi_windows.py" <Directory "C:\Users\samuel\PycharmProjects\avatarWebsite\avatarWebsite"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /static "C:/Users/samuel/PycharmProjects/avatarWebsite/static" <Directory "C:/Users/samuel/PycharmProjects/avatarWebsite/static"> Require all granted </Directory> </VirtualHost> wsgi.py: activate_this = 'C:/Users/samuel/Envs/avatarWebsite/Scripts/activate_this.py' # execfile(activate_this, dict(__file__=activate_this)) exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('C:/Users/samuel/Envs/avatarWebsite/Lib/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('C:/Users/samuel/PycharmProjects/avatarWebsite') sys.path.append('C:/Users/samuel/PycharmProjects/avatarWebsite/avatarWebsite') os.environ['DJANGO_SETTINGS_MODULE'] = 'avatarWebsite.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "avatarWebsite.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Django: Username is empty when a new user is created when signing in
I have made custom forms for log in and registration in Django using HTML/CSS and not Django's form.as_p. I have the following code in views.py: def login_user(request): logout(request) if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('/mainpage/') else: login_message = "Your username or password is incorrect." return render(request, 'index.html', {'login_message': login_message}) return render(request, 'index.html') def sign_up(request): if request.POST: username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password_confirm = request.POST['password-confirm'] if(valid_form(username, email, password, password_confirm)): #create the new user user = CustomUser(name=username, email=email, password=password) user.save() user = authenticate(username=username, password=password) login(request, user) return redirect('/mainpage/') else: message = "There was a problem." return render(request, 'index.html', {'message': message}) return render(request, 'index.html') I have the following model for CustomUser in models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=70, null=True) password = models.CharField(max_length=50, null=True) My code is working for the sign up and I can create a new user after inputting the username, email and password. When I check the users in the user list on the Django admin site, for the new user I created (ruby), only their email is … -
Como solucionar ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
Es desde django. en views.py no puedo importar Post desde models.py From .models import Post -
How to save unix epoch datetimeformat like this (2019-11-12T10:26:39.613Z) into models.DateTimeField accurately
How can I save in this unix epoch datetimeformat like this 2019-11-12T10:26:39.613Z into models.DateTimeField accurately I tried with this but as you can see, assigning with datetime.datetime.strptime seems correct, but after I save it, the datetime value changes (which is then inaccurate) >>> b.updated_at = datetime.datetime.strptime("2019-11-12T10:26:39.613Z", '%Y-%m-%dT%H:%M:%S.%fZ') >>> b.updated_at datetime.datetime(2019, 11, 12, 10, 26, 39, 613000) >>> b.save() >>> b.updated_at datetime.datetime(2019, 11, 12, 3, 1, 35, 82434, tzinfo=<UTC>) in model.py updated_at = models.DateTimeField(auto_now=True) I am using Django 1.11 and Postgres 9.4 -
python call type using variable
The following works fine: import someapp.models dump_data(someapp.models.MyModel, using='dumpingdb') But this does not work: import someapp.models modelType = MyModel dump_data(someapp.models.modelType, using='dumpingdb') Any idea how to store the model name in a variable and then call it? -
NameError: name 'Event' is not defined Django Foreign Key
I've very strange behaviour trying to create three models with Foreign Keys. I can create these three empty models in a new project running locally on my computer. The models seem fine. 1. Write out models 2. makemigrations 3. migrate Problem is when I try to do this in my main dev environment which is dockerized. My app crashes and I get an error. market = models.ForeignKey(Event, on_delete=models.CASCADE) NameError: name 'Event' is not defined Steps I've done to fix. I've deleted all migrations and flushed the database. Checked in pgadmin if and tables where still there related to the models. docker pruned the volumes rebuilt the project with docker-compose build. I can't understand why I'm getting this error even though these models are created in a standard django app. I can't cmd into my django container or even start it because this error crashed the container. Here is my models class Event(models.Model): sport_name = models.CharField(max_length=15, null=True) event_id = models.BigIntegerField(primary_key=True) event_name = models.CharField(max_length=200, null=True) start_time = models.DateTimeField(null=True) status = models.CharField(null=True,max_length=13) class Market(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) market_id = models.BigIntegerField(primary_key=True) market_name = models.CharField(null=True,max_length=35) status = models.CharField(null=True,max_length=10) volume = models.FloatField(null=True,max_length=15) class Runner(models.Model): market = models.ForeignKey(Market,null=True, on_delete=models.SET_NULL) runner_id = models.BigIntegerField(primary_key=True) event_id = models.BigIntegerField(null=True) name … -
Django loop through model choices
This is the base code I am using: https://github.com/justdjango/video-membership/tree/master/courses 3 main files: models.py views.py templates/course_list.html But I added some more functionality to models.py to include a skill_level and subject with model choices: https://dpaste.de/xhxX What I want to eventually do is to loop through the subjects and skill_levels so that the loop results could be used in a dropdown menu so users could search/filter for courses of a certain subject or courses of a certain skill level. But for right now I want to get the dropdown form populated with the choices. Example Outcome: https://imgur.com/a/YKhORP9 I would appreciate if someone could provide some code that could accomplish this. -
queryes orm with tables millions data
I need recommendations so that my query is faster it takes too much and apart the fragment, my table already contains millions of data, which is the best option for this type of case when there are millions of data. I already applied the creation of processes, index but still slow to do the query pool = mp.Pool(processes=mp.cpu_count()) results = pool.map(filtar_query,json_f) def filtar_query(args): fecha, argumentos = args[0], args[1] query = Modelo.objects.only('fecha','campo2','campo3').filter(fecha__date=fecha).filter(**argumentos).values('fecha','campo2','campo3') df= pd.DataFrame(query) df = df.groupby(fecha) in the part where it takes too much time is to make the query that advice would give me -
Using Django Rest Framework to show data from related models
I'm trying to learn DRF on my on, for my self practice, wanted to create a member like API with three Models. I'd like to join the contact data whenever I requested UserInfo; however, I googled, stackoverflowed many days without any directions. It'd be great if any gurus can guide me through this. python: 3.7 django: 2.2.6 drf: 3.10.3 models: CID = models.AutoField(primary_key=True) USER_ID = models.CharField(max_length=50, null=False) LOGIN_ID = models.CharField(max_length=50, null=True) USER_TYPE = models.CharField(max_length=10, null=False) UPDATE_TIME = models.DateTimeField(auto_now=True) def __str__(self): names = self.FIRST_NAME + " " + self.LAST_NAME return names class Meta: db_table = "myCustomers" class ContactTypes(models.Model): CID = models.AutoField(primary_key=True) CONTACT_TYPE = models.CharField(max_length=10, null=False) def __str__(self): return self.CONTACT_TYPE class Contact(models.Model): CID = models.AutoField(primary_key=True) USER_ID = models.ForeignKey(UserInfo, on_delete=models.CASCADE) CONTACT_TYPE = models.ForeignKey(ContactTypes, on_delete=models.CASCADE) CONTACT_INFO = models.CharField(max_length=50, null=False) UPDATE_TIME = models.DateTimeField(auto_now=True) serializers: class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = '__all__' class ContactTypeSerializer(serializers.ModelSerializer): class Meta: model = ContactTypes fields = '__all__' class UserInfoSerializer(serializers.ModelSerializer): class Meta: model = UserInfo fields = '__all__' views: class myCustomersViewSet(viewsets.ModelViewSet): queryset = UserInfo.objects.all() serializer_class = UserInfoSerializer class contactsViewSet(viewsets.ModelViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer class contactTypesViewSet(viewsets.ModelViewSet): queryset = ContactTypes.objects.all() serializer_class = ContactTypeSerializer Thanks for spending time with me -
Sanitizing urls.reverse()
Is it necessary to sanitize input to urls.reverse()? Can I pass the view name in the URL as a parameter safely or does this present a risk I'm unaware of? I assume the primary risk is that a user could redirect back to any specific URL–however I'm okay with that, since the presumption is that merely knowing a URL does not change access control to that URL. However, if there are other risks beyond this, that would be useful to know. -
Why am I getting errors when doing Request Factory in Django?
I'm trying to create a python script that runs in the background and periodically runs a view (Celery can't be installed on Azure, django-cron doesn't work). I found out that you can use something called a request factory, which simulates someone visiting your page for testing purposes (my main goal is to pass a request to my function in views.py that has a user ModuleNotFoundError: No module named 'pcbuilder' Here is my external script: from django.contrib.auth.models import AnonymousUser, User from django.test import RequestFactory, TestCase from .views import update factory = RequestFactory() factory = RequestFactory() user = User.objects.get(username='user') request = factory.get('/update') request.user = user response = update(request) As a side question: I had to set my DJANGO_SETTINGS_MODULE environment variable in CMD, is there a way to do it from the .py file itself? -
Django: Integrity error when signing up to create a new user with a custom form
I have made custom forms for log in and registration in Django using HTML/CSS and not Django's form.as_p. I have the following code in views.py: def login_user(request): logout(request) if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('/mainpage/') else: login_message = "Your username or password is incorrect." return render(request, 'index.html', {'login_message': login_message}) return render(request, 'index.html') def sign_up(request): if request.POST: username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password_confirm = request.POST['password-confirm'] if(valid_form(username, email, password, password_confirm)): #create the new user user = CustomUser(name=username, email=email, password=password) user.save() user = authenticate(username=username, password=password) login(request, user) return redirect('/mainpage/') else: message = "There was a problem." return render(request, 'index.html', {'message': message}) return render(request, 'index.html') I have the following model for CustomUser in models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=70, null=True) password = models.CharField(max_length=50, null=True) My code is working for the sign up and I can create a new user after inputting the username, email and password. However, when I try to sign up again and create another user I am getting the following error: Exception Type: IntegrityError Exception Value: UNIQUE constraint … -
"ModuleNotFoundError: No module named 'bootstrap4' " occured when deploying django project to PythonAnywhere
I'm trying to deploy my django project to PythonAnywhere reffering to https://tutorial.djangogirls.org/en/deploy/. When I executed this command, pa_autoconfigure_django.py --python=3.6 https://github.com/my_git_url.git following error happned. (actually some texts are omitted because it's long) Traceback (most recent call last): File "/home/kanchi0914/kanchi0914.pythonanywhere.com/manage.py", line 21, in <module> main() File "/home/kanchi0914/kanchi0914.pythonanywhere.com/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/kanchi0914/.virtualenvs/kanchi0914.pythonanywhere.com/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/kanchi0914/.virtualenvs/kanchi0914.pythonanywhere.com/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/kanchi0914/.virtualenvs/kanchi0914.pythonanywhere.com/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/kanchi0914/.virtualenvs/kanchi0914.pythonanywhere.com/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/kanchi0914/.virtualenvs/kanchi0914.pythonanywhere.com/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/kanchi0914/.virtualenvs/kanchi0914.pythonanywhere.com/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap4' Traceback (most recent call last): File "/home/kanchi0914/.local/bin/pa_autoconfigure_django.py", line 52, in <module> django-bootstrap4andbootstrap4 seems to be correctlly installed. 23:45 ~ $ pip3.6 install --user django-bootstrap4 Looking in links: /usr/share/pip-wheels Requirement already satisfied: django-bootstrap4 in ./.local/lib/python3.6/site-packages (1.0.1) Requirement already satisfied: beautifulsoup4 in /usr/lib/python3.6/site-packages (from django-bootstrap4) (4.6.0) I guessed these sites would be useful, tried some solutions, but situation did not change. https://www.tangowithdjango.com/book17/chapters/deploy.html https://www.pythonanywhere.com/forums/topic/12404/ Off cource I confirmed my project work well in my local env. What should … -
Python fails to run from shell despite being installed and py command running
I am trying to follow the tutorial of setting up an app for Django, but cannot progress past this part; "python manage.py runserver" from https://docs.djangoproject.com/en/2.2/intro/tutorial01/ PS C:\Users\Elias\Documents\WebApp\mysite> ls Directory: C:\Users\Elias\Documents\WebApp\mysite Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2019-11-11 4:32 PM mysite -a---- 2019-11-11 4:32 PM 647 manage.py PS C:\Users\Elias\Documents\WebApp\mysite> py manage.py runserver PS C:\Users\Elias\Documents\WebApp\mysite> python manage.py runserver Program 'python' failed to run: No application is associated with the specified file for this operationAt line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~. At line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed PS C:\Users\Elias\Documents\WebApp\mysite> py -m manage.py runserver PS C:\Users\Elias\Documents\WebApp\mysite> python ./manage.py runserver Program 'python' failed to run: No application is associated with the specified file for this operationAt line:1 char:1 + python ./manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~. At line:1 char:1 + python ./manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed PS C:\Users\Elias\Documents\WebApp\mysite> ./manage.py runserver PS C:\Users\Elias\Documents\WebApp\mysite> python -V Program 'python' failed to run: No application is associated with the specified file for this operationAt line:1 char:1 + python -V + ~~~~~~~~~. At line:1 char:1 + python -V + ~~~~~~~~~ + CategoryInfo : … -
Django could not open images
I have a problem with my project. The Django could not open the images, css and javascript are working. in my Home Page everything is OK, but in Page like about and contact just images nonvisible, "GET /about/images/image_4.jpg HTTP/1.1" 404 2702 Thanks in advance -
Can Elastic Beanstalk use uwsgi.ini instead of wsgi.py in a Python (Django) app?
I can't find any documentation from AWS about using a uwsgi.ini file in the WSGIPath config key section. All references I've found use wsgi.py I have a large codebase that I am migrating from Docker to run on bare metal in a Beanstalk environment. We have a lot of configuration in various ini files / vassals and ideally, I'd like to leave them alone. Is there a way to use a uwsgi.ini file (invoked as uwsgi --init [myfile.ini] when running locally / in Docker)? -
Wagtail: Render child elements from different page
Normally when rendering child elements onto the page I use {% for item in page.get_children %} and render them out like {{ item.specific.name }} However, I want to now access the child elements from a page that is not within its own template. (eg rendering child elements from /about.html onto /home.html) I imagine it's something like {% for item in page.pagename.get_children %} though I'm not sure of the actual page name...Do I have to define it somewhere/ is it defined somewhere? -
How append sum of instances within a django queryset to that queryset?
I have a Django Queryset object that looks like this (it is a derived queryset, not a queryset for a Model): <QuerySet [{'A': 2, 'B':3. 'C':0 }, {'A': 1, 'B':2. 'C':1 }]> How can I append a new instance containing sum of instances within the queryset to that queryset? That is, I need to make a new (or the same) queryset that looks like this: <QuerySet [{'A':2, 'B':3, 'C':0 }, {'A':1, 'B':2, 'C':1 }, {'A':3, 'B':5, 'C':1 }]> -
please i still havent gotten an answer i am trying to deploy django on heroku and still having this error
2019-11-07T12:21:08.238073+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=protected-wave-59724.herokuapp.com request_id=10073936-fef1-4c6f-97b2-421c8a13cda4 fwd="197.210.29.193" dyno= connect= service= status=503 bytes= protocol=https 2019-11-07T12:21:09.167832+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=protected-wave- 59724.herokuapp.com request_id=5be92ac9-6c16-44dc-8438-1ab82e84ab5a fwd="197.210.29.193" dyno= connect= service= status=503 bytes= protocol=https! this is the error image -
Tree Manager for mptt, independent from Admin
I try to make a tree manager for 'django-mptt' without using Admin, but I don't really know how to handle it.