Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why does my link to logout not work in my Django app?
So I'm trying to do a logout link in my Django app. I've set a view that logs out the user and then redirects him to a template paginaPrincinal.html that has two buttons for login and register. The problem is that for some reason the link href that I'm creating in my index.html doesn't appear. my views.py def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return redirect('index') else: form = AuthenticationForm() return render(request, 'registration/login.html', {'form': form}) def logout_view(request): logout(request) return redirect('paginaPrincipal') my urls.py path('principal/', views.intro, name='pagina_principal'), path('registro/', views.registro_usuario, name='registro_usuario'), path('login/', views.login_view, name="login"), path('logout/', views.logout_view, name="logout"), path('',views.index, name ='index'), index.html {% block contenido %} <div> <ul> {% if user.is_authenticated %} <li>Hola, {{user.username}}</li> <li><a href="{% url 'logout' %}"></a></li> {% endif %} </ul> </div> {% endblock %} The error that appears if I inspect the code and try to go to the Href is this: NoReverseMatch at /myapp2/logout/ Reverse for 'paginaPrincipal' not found. 'paginaPrincipal' is not a valid view function or pattern name. -
Verify if exists records in database with Django
My english is bad. Hello everyone, i trying verify if exists records in Database. If exists then not insert. If not exists insert. The problem is that's inserted when exists in DB. Can't insert if exists but is inserted. :( How to fix it? My code is: class Follow(models.Model): followed = models.CharField(max_length=100) following = models.CharField(max_length=100) def __str__(self): return self.followed def verify(self, request, gender): select_me = User.select_me(self, request) select_random = User.select_random(self, request, gender) try: verify = Follow.objects.filter( followed=select_me.twid, following=select_random.twid).exists() if verify: return False else: return True except: return False def follow(self, request, gender): select_me = User.select_me(self, request) select_random = User.select_random(self, request, gender) timer = utils.strtotime('+' + str(configs.FOLLOW_TIME_PREMIUM) + ' minutes') if select_me.premium > 0 else utils.strtotime('+' + str(configs.FOLLOW_TIME_FREE) + ' minutes') if self.verify(request, gender): register = Follow(followed=select_me.twid, following=select_random.twid) register.save() select_me.follow_count += 1 select_me.follow_time = timer select_me.follow_total += 1 select_me.save() return True else: return False -
Django- Cleaning data for a many-to-many field within ModelForm
I'm building an API that will require the cleaning of input data into a modelform m2m field before creating the model instance. The data will come in as a string of names, I will need to clean the data and add link the m2m relationship manually. What is the proper way to link these relationships within the manytomany field during the clean Def. Do I simply append each into the field itself? Below is my working "clean" def: def clean_sourcingbroker(self): broker = self.cleaned_data['broker'] cleanlist = [] names = [] for name in broker.replace(', ', ',').split(' '): name = name.split(',') last_name = name[0] first_name = name[1] names.append((last_name, first_name)) for name in names: brokerobj = Broker.objects.get(lastname=name[0], firstname=name[1]) cleanlist.append(brokerobj) return cleanlist -
Django admin dashboard CSS is missing
I just deployed my application to DigitalOcean. Everything works very well, excep admin panel's styling although I've used nginx. Here are my codes: settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static_root") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] nginx configuration: server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static_root/ { root /home/my_username/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/my_username/myproject/myproject.sock; } } -
Should I have methods that don't return a queryset on a models.QuerySet children?
Right now at work I have a situation like this where I'm trying to find the cleanest way out of it: FooQuerySet(models.QuerySet): def active_items(self, items): new_items = self._do_something_with_items(items) return self.filter(active__in=items) def _do_something_with_items(items): """ some kind of calculation """ The question is, should the method _do_something_with_items leave inside the QuerySet children given that it does not return a queryset but rather does some data transformation, or is it ok to leave it there as it's next to the place that calls it? -
How can I make a log to the db table of errors, all Django operations that have been failed
I am pretty new in Django , and I try to make a log table which contain all the bad operations like : UPDATE,DELETE,CREATE and the reason it has been failed , for example : unique field is already exist. I tried to do it with Signals, pre_post but when an error occur,it even doesn't get into my create() function on my serializer . any ideas ? Thank you! -
Method return TypeError for 2 positional argument instead of 1 that was given
My model manager for Django defines a function that gets or creates new billing profile for either existing user or a guest user depending if the user is authenticated or not. The function takes in only one parameter, but in using it in the view, I'm presented with TypeError that says: TypeError at /cart/checkout new_or_get() takes 1 positional argument but 2 were given For better understanding here is the source source code: Urls.py from django.urls import path from . import views app_name = 'cart' urlpatterns = [ path('checkout', views.checkout_home, name='checkout') ] Model This is before the views because this were I define the function new_or_get() in the class BillingProfileManager() from django.db import models from django.conf import settings from django.db.models.signals import post_save from accounts.models import Guest User = settings.AUTH_USER_MODEL class BillingProfileManager(models.Manager): def new_or_get(request): user = request.user guest_email_id = request.session.get('guest_email_id') obj = None created = False # Logged in user checkout. Remembers payment if user.is_authenticated: obj,created = self.model.get_or_create(user=user, email=user.email) # Guest user checkout. autoreloads payment elif guest_email_id is not None: guest_obj = Guest guest_email_obj = guest_obj.objects.get(id=guest_email_id) obj,created = self.model.get_or_create(email=guest_email_obj.email) created = True else: pass return obj, created class BillingProfile(models.Model): user = models.OneToOneField(User, unique=True, null=True, blank=True, on_delete=models.DO_NOTHING) email = models.EmailField() active = models.BooleanField(default=True) … -
Django File object and S3
So I have added s3 support to one of my Django projects. (storages and boto3) I have a model that has a file field with zip-archive with images in it. At some point I need to access this zip-archive and parse it to create instances of another model with those images from archive. It looks something like this: I access archive data with zipfile Get image from it Put this image to django File object Add this file object to model field Save model I works perfectly fine without s3, however with it I get UnsupportedOperation: seek error. My guess is that boto3/storages does not support uploading files to s3 from memory files. Is it the case? If so, how to fix id/ avoid this in this kind of situation? -
How to store postgresql database in django - project folder?
Where is postgreSQL database saved in a django folder (that which has manage.py)? If not, I presume it must be stored in postgres folder of root directory. Then, how to transfer this file to those systems having no postgres installed, so that when they "run server", they can see seamlessly all the data/app? Can we ask DJANGO to create the databse file in its project folder itself and does this help in such transfers ? Thanks. -
After deploying Django app on AWS elastic beanstalk it shows default page but in local system it works fine
I am deploying Django application to AWS beanstalk , this application works fin in local environemnet but after deploying its shows default page of Django. I tried manually putting urls but it is not working too. -
Django: Problems setting up django-allauth URLs
I'm trying to customize a few things of allauth and ran into the following problem. I got my own account app, which is supposed to handle all the customization I do to allauth amongst other account related stuff. Which means I want to include the allauth urls into the urls.py located in my account app, not in the project level urls.py. However when I try it with the code below I run into the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'account_login' not found. 'account_login' is not a valid view function or pattern name. project/urls.py urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns( ... path('account/', include('apps.account.urls')), # This does not work # path('account/', include('allauth.urls')), # This works ... ) apps/account/urls.py urlpatterns = [ ... path('', include('allauth.urls')), #This is where I want to include the allauth urls ... ) Going one step further: Can I customize the allauth urls in some way? When I try something like the following I get the same error as above: apps/account/urls.py from allauth.account import views as allauth_view urlpatterns = [ ... path("signup/", allauth_view.signup, name="account_signup"), ... ) -
TypeError: on_delete must be callable
Suddenly I am getting an error saying TypeError: on_delete must be callable. I don't know how to solve this error as I don't see field=models.ForeignKey(default=1, on_delete='CASCADE', to='main.Category'), mentioned anywhere in my code. File "/home/arch/myproject/main/migrations/0014_auto_20191025_1154.py", line 6, in <module> class Migration(migrations.Migration): File "/home/arch/myproject/main/migrations/0014_auto_20191025_1154.py", line 47, in Migration field=models.ForeignKey(default=1, on_delete='CASCADE', to='main.Category'), File "/home/arch/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 801, in __init__ raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable. -
Django says ImproperlyConfigured: The included URLconf does not appear to have any patterns in it
I'm new to Django and I'm facing a problem with a repo I downloaded. It sends the error File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\urls\resolvers.py", line 596, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'quiniela.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. My quiniela.urls looks like this: from django.contrib import admin from django.urls import path from quinewhats.views import Home from django.contrib.auth.views import LogoutView from django.urls import include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', Home.as_view()), path("logout/", LogoutView.as_view(), name="logout"), path('liga/',include('liga.urls',namespace='liga')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And my liga.urls like this: from django.urls import path from .views import EquiposTableView,EquiposCreateView,EquiposUpdateView,EquiposDeleteView, LigaTableView, LigaCreateView, LigaUpdateView, LigaDeleteView, TorneosTableView,TorneosCreateView,TorneosDeleteView,TorneosUpdateView app_name='liga' urlpatterns = [ path('equipos/table/', EquiposTableView.as_view(), name='tabla_equipos'), path('equipos/create/',EquiposCreateView.as_view(), name='crear_equipos'), path('equipos/update/<int:pk>/',EquiposUpdateView.as_view(), name='actualizar_equipos'), path('equipos/delete/<int:pk>/',EquiposDeleteView.as_view(), name='eliminar_equipos'), path('liga/table/', LigaTableView.as_view(), name='tabla_liga'), path('liga/create/', LigaCreateView.as_view(), name='crear_liga'), path('liga/update/<int:pk>/', LigaUpdateView.as_view(), name='actualizar_liga'), path('liga/delete/<int:pk>/', LigaDeleteView.as_view(), name='eliminar_liga'), ] I don't know what a circular import is, but I read it could be that my urls.py was somewhat imported to a views.py, but I checked and it doesn't seem to be the case. Is there any other thing I'm overseeing, or some other information that could be useful? … -
registering multiple models in Django Admin and excluding common field
I am registering my (numerous) models using looping through apps.get_models() much like in the below answer: Register every table/class from an app in the Django admin page My goal: as most of the models contain a common field that I would like to exclude from Django Admin I wonder if there is any way to do it without resorting to registering each model separately with exclude = FieldToBeExcluded -
('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: contains
I have models like: class Gtex1(models.Model): id = models.TextField(primary_key=True) sample = models.TextField(blank=True, null=True) gtex_s4q7_0003_sm_3nm8m = models.FloatField(db_column='GTEX-S4Q7-0003-SM-3NM8M', blank=True, null=True) gtex_qv31_1626_sm_2s1qc = models.FloatField(db_column='GTEX-QV31-1626-SM-2S1QC', blank=True, null=True) gtex_13ovi_1026_sm_5l3em = models.FloatField(db_column='GTEX-13OVI-1026-SM-5L3EM', blank=True, null=True) class Tcga1(models.Model): id = models.ForeignKey(Gtex1, models.DO_NOTHING, db_column='id', primary_key=True) sample = models.TextField(blank=True, null=True) tcga_we_aaa0_06 = models.FloatField(db_column='TCGA-WE-AAA0-06', blank=True, null=True) tcga_86_8668_01 = models.FloatField(db_column='TCGA-86-8668-01', blank=True, null=True) tcga_d8_a146_01 = models.FloatField(db_column='TCGA-D8-A146-01', blank=True, null=True) I have almost 30 models like Tcga1 having the same primary key (id) which is a foreign key from the Gtex1 model. I am trying to do this: search_models=[models.Gtex1,models.Tcga1,models.Tcga2,models.Tcga3] search_results = [] search_query='tcga_61_2111_01' for m in search_models: fields=[x for x in m._meta.get_fields()] search_queries=[Q(**{x.name + "__contains" : search_query}) for x in fields] q_object = Q() for query in search_queries: q_object = q_object | query results = m.objects.filter(q_object) search_results.append(results) print(search_results) which is basically going through all models column names and finding search query and filter through it. However, I am getting ERROR like: raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: contains If anyone can help me understand how to resolve this or any insights will be helpful and appreciated. Thank you so much. -
Not able to login to the django admin
Hello I am creating a web app locally (postgres), and is trying to login to the django admin. However whenever I login using the correct credentials the server stops running. The last log says [10/Dec/2019 16:37:11] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 The url .../admin/ shows me the expected login form and if I fill in the form incorrectly I get relevant error messages. If I fill in the form correctly with the details of a superuser (created via manage.py createsuperuser) then the page does not redirect and the server suddenly stops. settings.py INSTALLED_APPS = [ 'pages.apps.PagesConfig', 'listings.apps.ListingsConfig', 'realtors.apps.RealtorsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] urls.py urlpatterns = [ path('', include('pages.urls')), path('listings/', include('listings.urls')), path('admin/', admin.site.urls), ] I have done the fix from Djando admin wont log in, no errors but had no success. Any help is appreciated! -
Django ManyToMany object saving to different database
I have a Django app that uses multiple databases - one for each client. When saving new objects, I use the .save(using=db) to specify which database the object should be saved to. Models class Document(models.Model): name = models.CharField(max_length=500, unique=True) class Dataset(models.Model): name = models.CharField(max_length=500, unique=True) documents = models.ManyToManyField(Document, related_name="doc_datasets") Saving dataset = Dataset(name = "myDataset") dataset.save(using = db) # Success! The object is saved in the correct database. document = Document(name = "myDocument") document.save(using = db) # Success! The object is saved in the correct database. I am running into issues when trying to add a many-to-many relationship: dataset.documents.add(document) # This attempts to save to a default database (non-client specific) How do I specify the database when adding a related object? -
Python - Splitting a string of names separated by spaces and commas
I have an API feeding into my program into a django many to many model field. The names of the individuals within my database are structured with a separated first name and last name. However, the API is sending a bulk list of names structured as as a string list as so: "Jones, Bob Smith, Jason Donald, Mic" (Last name-comma-space-first name-space-new last name- etc.) How would I separate this string in a way that would allow me to filter and add a particular user to the many-to-many field? Thanks!! -
How to upgrade my django 2.2 project to 3.0 and support asgi?
Recently Django releases a 3.0 version with an inbuild asgi version. I have created a Django project using django 2.2 but I want to support inbuild asgi without using channels. What are the possible ways to migrate from django 2.2 to 3.0 so that the project can support inbuild asgi? -
Django error ['“foo” is not a valid UUID.']
I recently resetted my database and now Django raises the error ['“2” is not a valid UUID.'] when visiting any site. The UUID is set as pk in my model and database and I am logged in properly with a superuser account. I don't know where Django gets the 2 from and what causes the error? Model: from django.contrib.auth.models import AbstractUser from django.db import models import uuid class CustomUser(AbstractUser): DID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def __str__(self): return self.username View: from django.urls import reverse_lazy from django.views.generic.edit import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' Error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/users/login/ Django Version: 3.0 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'Wiki_app', 'Dashboard', 'users'] Installed 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'] Traceback (most recent call last): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2309, in to_python return uuid.UUID(**{input_form: value}) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\uuid.py", line 169, in __init__ raise ValueError('badly formed hexadecimal UUID string') During handling of the above exception (badly formed hexadecimal UUID string), another exception occurred: File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, … -
Django TemplateSyntaxError at / 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls
I get the error when i run the code. python3 manage.py runserver TemplateSyntaxError at / 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log propeller static tz Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0 Exception Type: TemplateSyntaxError Exception Value: 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log propeller static tz Exception Location: /home/sggs/neerajbyte/Env-10-DeC/lib/python3.7/site-packages/django/template/defaulttags.py in find_library, line 1025 Python Executable: /home/sggs/neerajbyte/Env-10-DeC/bin/python3 -
Django Settings.py - SECRET_KEY - KeyError
Currently have a Django project running on Python 3.6.9 , hosted on Digital ocean using Gunicorn and Nginx. I am attempting to switch my SECRET_KEY and other passwords to environment variables opposed to having them as a string in settings.py. When doing so I run into the following error and Gunicorn shuts down. Dec 10 15:22:20: File "/home/user/projectdir/project/project/settings.py", line 23, in <module> Dec 10 15:22:20 droplet_name gunicorn: SECRET_KEY_PULL = os.environ['SECRET_KEY'] Dec 10 15:22:20 droplet_name gunicorn: File "/home/user/projectdir/myenv/lib/python3.6/os.py", line 669, in __getitem__ Dec 10 15:22:20 droplet_name gunicorn: raise KeyError(key) from None Dec 10 15:22:20 droplet_name gunicorn: KeyError: 'SECRET_KEY' Dec 10 15:22:20 droplet_name gunicorn: [2019-12-10 15:22:20 +0000] [20022] [INFO] Worker exiting (pid: 20022) I have exported the SECRET_KEY correctly prior by doing '''export SECRET_KEY="my_key"''' This is what my settings.py looks like as well: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = False ALLOWED_HOSTS = ["my_ip"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] 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 = 'project_name.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'project_name.wsgi.application' DATABASES = { 'default': { … -
Simple way to implement Razorpay with Django
I want to know the simple and straight forward way to implement Razorpay's standard checkout method in my Django app. Consider a very basic scenario where the user just enters an amount in the form and the clicks on checkout and the Razorpay takes forward. -
Render date with url instead of calendar
I have a notebook where people can leave a note, they can set the note for later and find a note a request date. It is render as a calendar, I would like to have a link, for example, for the last 3 days and the next 3 days. I don’t where to begin. My views.py start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') set_start_date = None set_end_date = None if start_date and end_date: try: datetime.strptime(start_date, "%Y-%m-%d") datetime.strptime(end_date, "%Y-%m-%d") set_start_date = start_date set_end_date = end_date except: messages.error(request, _(f"The form is invalid")) return redirect('workspace-detail', token=token) My models.py class Notebook(models.Model): workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE, related_name='notes') author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='author') message = models.CharField(max_length=3000, null=True, blank=True, verbose_name="Publier une note") date = models.DateTimeField(auto_now_add=False, null=False) -
Problem about sending email from Django, gmail blocks sign in from server
I am running website on scaleway server, 2 days ago i found "bug" which took 2 day to found out what was the problem, i am using email sending through django send_email, after 2 day of reviewing code found out that google blocks gmail sign in from scaleway server(which is located in Paris), is there anyway to somehow fix this problem? Thanks