Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I access the original data from object in python. Here I've used group by to group data. Can someone please help me with this issue?
I am trying to group data based on the following data fields I have, and when I am not able to access the original data in the fields Printing the filtered_data is giving something like "object at 0x10dd1abf0>", so I need to access the original human-readable value in the objects. data_objects = ['*', '*', '*', ......] // This is list of data items filterd_data_objects = groupby( data_objects, lambda data: (data.x, data.y, data.z) and data.p ) for filterd_data_object, _ in filterd_data_objects: x = data_object[0] // this is not working I've tried this to access the original data y = data_object[1] z = data_object[2] p = data_object[3] -
self.form_valid(form) returns "TypeError: 'NoneType' object is not callable"
Getting 'TypeError: 'NoneType' object is not callable', when self.form_valid(form) is called. I got a lot of solution from stackoverflow for this kind of error, I tried everyone of them but till now the error is there. Before going to error, I want to describe my view, form and html input form. view.py class CancelView(FormView): template_name = 'cancel.html' form_class = CancelForm def post(self, request): form = self.form_class(request.POST) if form.is_valid(): if form.cleaned_data.get('canceled'): try: print(form) except Exception: return self.form_invalid(form) return self.form_valid(form) else: return redirect(reverse_lazy('MyPage')) return self.form_valid(form) Here form.is_valid() and form.cleaned_data.get('canceled') are working fine. If I print the form here it returns: <input type="hidden" name="canceled" value="True" id="id_canceled"> form.py class CancelForm(forms.Form): use_required_attribute = False canceled = forms.BooleanField( initial=False, widget=forms.HiddenInput(), required=False, ) HTML Template <form action="." method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}"> <p class="text-center link__btn--block"><input value="Decline Cancellation." class="w50" type="submit"></p> <input id="id_canceled" name="canceled" type="hidden" value="False"> </form> Error Log Traceback (most recent call last): File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, … -
Pandas Read CSV in django view not working
What I'm trying to do is, when user uploaded the CSV file. I'm trying to do functionalities in pandas. Django template <form action="{% url 'upload-timeslot' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> My view def bulk_timeslot_upload(request): if request.FILES: import pandas as pd csv = request.FILES['fileToUpload'] data = pd.read_csv(csv) print(data) return render(request, 'bulk-timeslot.html') when i tried to read csv, running server getting exited. If I import pandas globally, server not even running. -
Django User model : how to make it with image and username?
I'm trying to make a user model in Django. My User fields are id(auto increment, PK), userImage(unique), username(not unique). I need to make a web application that registers & logs in only with userImage and username. I don't want to use password for the model but it seems that Django user model asks for password as a default (even when using AbstractUser). Also tried custom backend but when I try testing in admin, it still requires password. Is there a way to customize my user model? -
How to make sure that my django project is using virtual environment that i created for it?
I know that there is already a question similar to this,but i think the answer i wanted is not there. I am new to django.i have created an virtual environment with virtualenv and a django project,but how can we know that my project is using the packages of virtual environment rather than using global packages??please give me some detailed answer.THANKS in advance. -
Customizing each row of the model in admin page
I am customizing django admin template. I can successfully remove button like (+add model) or some filter by changing overriding change_list_results.html and change_list.html but now I want to customize each rows of the model to off the link.(I don't want to let the user go each rows editing page.) I am checking change_list_result.html {% load i18n static %} {% if result_hidden_fields %} <div class="hiddenfields">{# DIV for HTML validation #} {% for item in result_hidden_fields %}{{ item }}{% endfor %} </div> {% endif %} {% if results %} <div class="results"> <table id="result_list"> <thead> <tr> {% for header in result_headers %} <th scope="col" {{ header.class_attrib }}> {% if header.sortable %} {% if header.sort_priority > 0 %} <div class="sortoptions"> <a class="sortremove" href="{{ header.url_remove }}" title="{% trans "Remove from sorting" %}"></a> {% if num_sorted_fields > 1 %}<span class="sortpriority" title="{% blocktrans with priority_number=header.sort_priority %}Sorting priority: {{ priority_number }}{% endblocktrans %}">{{ header.sort_priority }}</span>{% endif %} <a href="{{ header.url_toggle }}" class="toggle {% if header.ascending %}ascending{% else %}descending{% endif %}" title="{% trans "Toggle sorting" %}"></a> </div> {% endif %} {% endif %} <div class="text">{% if header.sortable %}<a href="{{ header.url_primary }}">{{ header.text|capfirst }}</a>{% else %}<span>{{ header.text|capfirst }}</span>{% endif %}</div> <div class="clear"></div> </th>{% endfor %} </tr> </thead> <tbody> {% for … -
when i run python manage.py runserver i got this error
Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python38-32\Lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\user\appdata\local\programs\python\python38-32\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "E:\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "E:\venv\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "E:\venv\lib\site-packages\django\core\management\base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "E:\venv\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "E:\venv\lib\site-packages\django\db\migrations\loader.py", line 49, in init self.build_graph() File "E:\venv\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "E:\venv\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "E:\venv\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "E:\venv\lib\site-packages\django\db\migrations\graph.py", line 195, in [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "E:\venv\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration admin.0004_auto_20200315_2142 dependencies reference nonexistent parent node ('users', '0001_initial') -
Django extending not functioning within other templates when run through Github Pages
I have a base.html file, when run locally on vs code, works to extend bootstrap and css page layout to other template pages. When run through github pages, django functionality is no longer working. Here is the TimeSheet.html where I extend style from the base.html {% extends "base.html" %} {% block content %} Here is my base.html <head> <!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <link> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> When I load the TimeSheet.html page on github pages, it is not properly extending the base, and just echos the code as a literal string. {% extends "base.html" %} {% block content %} -
I am getting a IntegrityError UNIQUE constraint failed for django
I am getting an integrity error for creating a customer here. When the first customer tries to create an account this code works. But when new customer comes and tries to create a account it give the UNIQUE constraint failed. Where as When a seller tries to create an account it creates it, it works for every new seller. But this codes doesn't seem to work for the customer. This was the first error. And I got another error as FieldError at /accounts/customer/register/ Cannot resolve keyword 'user' into field. Choices are: active, address, customer, customer_id, email, id, order, timestamp, update when I try to save the email of that Customer it gives this error. Since I have a billing model set up and its given in the bottom below. And this one doesn't work even for the first customer who comes and tries to create an account. I used a custom user model accounts models.py class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) … -
pipenv set path of virtual environment in vs code
I'm using visual studio code on windows 10, using python and django. The problem I have is that whenever I create a new virtual environment it takes place on its default folder, I'd like to change it to take place in the address I specify. How can I specify the folder that virtual environment takes place in? So far, I've tried different ways to solve this problem, but none of work for me, this could be because of the system and tools I'm using, I've tried setting the path variables using set command, like: set Path="~/.ven" I also looked for changing the variables of pip and pipenv but I couldn't make it work. I also searched the similar questions on stackoverflow, I couldn't find a proper answer. Also in the documentation of pipenv, I couldn't find the solution. Thanks for reading and your time. -
ModuleNotFoundError:No module named 'users.urls'
I'm using Django3, and I want to make app to add users login. and here is my code in users/urls.py.I'm stuck here for amount of time.What's the problem? enter image description here -
Add hyperlink to columns in DataTables
Im newbie in using DataTables, I created a webpage that uses client-side processing to load the data. I want to add Hyperlink in my columns using "columns.render" to view the details in entire row where the value of ID/pk corresponds to the hyperlinked text, so that if a user click the Id/hyperlink in ID columns they would be rerouted to a separate page, "VM/Details/(id/pk)". How I fixed this? JS $(document).ready(function() { var table = $('#vmtable').DataTable({ "serverSide": false, "scrollX": true, "deferRender": true, "ajax": { "url": "/api/vm/?format=datatables", "type": "POST" }, "columns": [ {"data":"id", "render": function(data, type, row, meta){ if(type === 'display'){ data = '<a href="VM/Details/' + data.id + '">' + data + '</a>'; } return data; } }, {"data": "Activity_Id"}, {"data":"NO"}, {"data":"First_name"}, {"data":"Last_name"} ] }); html <table id="vmtable" class="table table-striped table-bordered" style="width:100%" data-server-side="false" data-ajax="/api/vm/?format=datatables"> <thead> <tr> <th>Id</th> <th>Activity No</th> <th>NO</th> <th>First Name</th> <th>Last Name</th> </tr> </thead> </table> Path that I want to rerouted after click the hyperlink path('VM/Details/<int:pk>', vmDetails.as_view(), name='vm_details'), But I got an error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/VM/Details/undefined -
Incorrect Server Response in Ckeditor Django
I want a non-admin user to be able to send an image on ckeditor's post. The problem happens that I can send the image in the post if the user is admin but if it is a simple user I cannot because it shows Incorrect Server Response in Ckeditor Django. my settings below: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'l$+3%scpx$n(ne!ky6b#!1p6q7pw-cnvl2*35v9_4akia0hswn' DEBUG = False ALLOWED_HOSTS = ['devcapivara.com.br', 'www.devcapivara.com.br'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #My Apps 'accounts', 'core', 'post', #third 'ckeditor', 'ckeditor_uploader', 'widget_tweaks', 'easy_thumbnails', ] CKEDITOR_UPLOAD_PATH = 'uploads/' 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 = 'capivara_blog.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 = 'capivara_blog.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # auth LOGIN_URL = 'accounts:login' LOGIN_REDIRECT_URL = 'core:dashboard' LOGOUT_REDIRECT_URL = 'accounts:login' LOGOUT_URL = 'accounts:logout' # Usando o módulo USER da nossa aplicação ACCOUNTS AUTH_USER_MODEL = 'accounts.User' # Autenticação por email/username AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.ModelBackend', … -
Custom form widget in django model admin change_form.html
I have implemented my own version of vertical filter that works for not just M2M fields but some custom data. I wanted to show it in my Django admin change_form.html. I wanted to know how to implement that, or turn it into a custom form widget. Here's my code. file.html <div class="row"> <div class="col-6"> <p onclick="choose(this)"> something </p> </div> <div class="col-6" id="chosen"> </div> </div> file.js var chosen = $("#chosen") function choose(p){ chosen.append(p); } this is how it looks The initial task is to have the left side of the div to be populated with the fields in some model, which I am getting through field_list = list() for i in AdqtHomescreen._meta.get_fields(): if hasattr(i, 'attname'): field_list.append(i.attname) elif hasattr(i, 'field_name'): field_list.append(i.field_name) I already know how to add custom media to Django Forms using class MyModelAdmin(admin.ModelAdmin): class Media: js = ('file.js', ) -
Image upload with fetch api not working in django
My views.py file def change_profile_picture(request): if not request.user.is_authenticated: return JsonResponse({"status": "403", "msg": "Unauthorized request"}) if request.method == 'POST': if request.is_ajax(): form = UploadPictureForm(request.POST) if form.is_valid(): customuser = request.user.customuser customuser.picture = form.cleaned_data['picture'] customuser.save() return JsonResponse( { "status": "200", "msg": "Successful", "data": f"{customuser.picture.url}" } ) else: return JsonResponse({"status": "400", "msg": "invalid form"}) else: return JsonResponse({"status": "401", "msg": "Bad request"}) else: return JsonResponse({"status": "403", "msg": "invalid request method"}) forms.py class UploadPictureForm(forms.Form): picture = forms.ImageField( label="Profile picture" ) Javascript code: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $('.upload-btn').on('click', () => { document.getElementById('id_picture').click(); }) $('.close-btn').on('click', () => { document.getElementById('profile-picture').src = $('#profile-picture').data('target'); document.getElementById('submit-picture').style.visibility = 'hidden'; }) $('#submit-picture').on('click', () => { var picture = document.querySelector('input[type="file"]'); var formData = new FormData(); formData.append('csrfmiddlewaretoken', getCookie('csrftoken')); formData.append('picture', picture.files[0]); fetch('/auth/change-profile-picture/', { method: 'POST', body: formData, cache: 'default', mode: 'cors', credentials: 'include', headers: { "X-Requested-With": "XMLHttpRequest", } }) .then((res) => res.json()) .then((data) => { if(data.status … -
Non superusers unable to login and displaying password in admin - Django
In my Django project, I have a custom user class inside models.py of an app called "accounts": from django.db import models from django.contrib.auth.models import AbstractUser from localflavor.br.br_states import STATE_CHOICES class Company(models.Model): id = models.IntegerField(primary_key=True) class Client(AbstractUser): company = models.ForeignKey(Company, on_delete=models.CASCADE, default=0) role = models.CharField(verbose_name='Cargo', max_length=20) city = models.CharField(verbose_name='Cidade', max_length=20) state = models.CharField(verbose_name='Estado', max_length=2, choices=STATE_CHOICES) phone = models.CharField(verbose_name='Telefone', max_length=25) I have this variable set at my settings.py: AUTH_USER_MODEL = 'accounts.Client' But I am only able to login to the platform with a superuser. Non superusers get a wrong username or password (and they are active, I've checked). Also, in the admin page, it is showing the password of the Clients. Btw, I am using POSTGRES. 1) How can I make any user login into the platform (not admin page, but my main platform)? 2) How can I properly store their password and not show it in the admin page? Thank you. -
TypeError at /cart/cheese-grits/ update_cart() missing 1 required positional argument: 'qty'
I am trying to add more than one of the same item to a cart. I have been able to add one of each item to the cart, but when I tried to implement a quantity function, I get this error. When I was using a loop that made buttons, when I clicked them it would add one of that item to the order. I want to be able to add multiple of the same item. Thank you Views.py: def view(request): products = Product.objects.all() try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) products = Product.objects.all() context = {"cart": cart, "products": products } else: context = {"empty": True, "products": products } template = "mis446/home.html" return render(request, template, context) def update_cart(request, slug, qty): try: qty = request.GET.get('qty') update_qty = True except: qty = None update_qty = False try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass cart_item, created = CartItem.objects.get_or_create(cart = cart, product=product) if created: print ("yeah") if update_qty and qty: if int(qty) == 0: cart_item.delete() else: cart_item.quantity = qty cart_item.save() else: pass # if not cart_item in cart.items.all(): … -
Django AbstractBaseUser model not saving all the fields of the template in databse when information entered from registartion form?
enter image description here this is my forms code enter image description here This is my views code enter image description here this is my models code I am not sure what's wrong with my code it's only saving username , first name and last name data not other fields.enter image description here -
How to run Django app with Apache2, mod_wsgi and Anaconda?
I'm trying to run a django application with Apache2, wsgi_mod, Anaconda environment with Python3.8 in Ubuntu. When I run 'sudo service apache2 start' , the page keeps re-loading and the same error message is stacking at '/var/log/apache2/error.log'. Current thread 0x00007ff7b9507bc0 (most recent call first): [Thu Apr 02 20:02:27.236780 2020] [core:notice] [pid 24024:tid 140701942709184] AH00051: child pid 29871 exit signal Aborted (6), possible coredump in /etc/apache2 [Thu Apr 02 20:02:27.237711 2020] [core:notice] [pid 24024:tid 140701942709184] AH00051: child pid 29872 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' These are the sys.prefix and the sys.path (my_env) manager@ubserv01:/etc/apache2/sites-available$ python -c "import sys; print(sys.prefix)" /var/anaconda3/envs/my_env (my_env) manager@ubserv01:/etc/apache2/sites-available$ python -c "import sys; print(sys.path)" ['', '/var/anaconda3/envs/my_env/lib/python38.zip', '/var/anaconda3/envs/my_env/lib/python3.8', '/var/anaconda3/envs/my_env/lib/python3.8/lib-dynload', '/var/anaconda3/envs/my_env/lib/python3.8/site-packages'] This is the mod_wsgi-express module-config output: (my_env) manager@ubserv01:/etc/apache2/sites-available$ mod_wsgi-express module-config LoadModule wsgi_module "/var/anaconda3/envs/my_env/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so" WSGIPythonHome "/var/anaconda3/envs/my_env" Here is my /etc/apache2/sites-available/djangoProject.conf: LoadModule wsgi_module /var/anaconda3/envs/my_env/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so WSGIPythonHome /var/anaconda3/envs/my_env <VirtualHost *:80> ServerName opes.com ServerAdmin admin LogLevel warn DocumentRoot /var/www/opes/djangoProject <Directory /var/www/opes/djangoProject/djangoProject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIPassAuthorization On WSGIDaemonProcess djangoProject python-path=/var/www/opes/djangoProject python-home=/var/anaconda3/envs/my_env WSGIProcessGroup djangoProject WSGIScriptAlias / /var/www/opes/djangoProject/djangoProject/wsgi.py ErrorLog "/var/log/apache2/djangoProject" CustomLog "/var/log/apache2/djangoProject" common </VirtualHost> /var/www/opes/djangoProject is the directory where manage.py is located. I enable this file … -
Does any body know how to fix this issue in Django login oathtoken
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/api/login/ Django Version: 3.0.5 Python Version: 3.7.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authentication', 'rest_framework.authtoken', 'profilesapi'] 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 "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) The above exception (relation "authtoken_token" does not exist LINE 1: ...oken"."user_id", "authtoken_token"."created" FROM "authtoken... ^ ) was the direct cause of the following exception: File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/Users/XYZ/Documents/pycharm/DjangoChallenges/profile_project/profilesapi/views.py", line 130, in create return ObtainAuthToken().post(request) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/authtoken/views.py", line 46, in post token, created = Token.objects.get_or_create(user=user) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/db/XYZ/query.py", line 559, in get_or_create return self.get(**kwargs), False File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/db/models/query.py", line 411, in get num … -
Specifying a custom user model in django and calling an object
Alright, so I'm a bit stuck here. I decided to create my own user model, which is turning out to be a huge head ache. And not to mention this is my first django project from scratch... So I am creating a dating app. I have a sample project of which I want to use some code and bring it over and adapt it to my project. I'm really not sure how to go about adapting some of the changes I need for my custom model. Here is the error I am getting: NameError at /mingle/ name 'models' is not defined Request Method: GET Request URL: http://localhost:8000/mingle/ Django Version: 2.2.3 Exception Type: NameError Exception Value: name 'models' is not defined Exception Location: /Users/papichulo/Documents/DatingApp/dating_app/views.py in mingle, line 113 Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 Python Version: 3.7.3 Python Path: ['/Users/papichulo/Documents/DatingApp', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/papichulo/Library/Python/3.7/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'] Server time: Fri, 3 Apr 2020 00:15:57 +0000 SAMPLE code try: user = (User.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0]) except IndexError: user = None print(User.username) try: bio = models.UserProfile.objects.get(user=request.user).bio except models.UserProfile.DoesNotExist: create = UserProfile.objects.get_or_create(user = request.user) return redirect('profile') friend = models.UserProfile.objects.get(user=request.user).friends.all() context = dict(user = user, friend = friend) return render(request, 'index.html', context) My views.py def mingle(request): try: user = (Profile.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0]) except IndexError: user … -
How to query on the base_field of a Django ArrayField
Can I query the base_field of a Django ArrayField? For example, can I filter on "regions with a postcode that matches some regex" given the following model: models.py: from django.contrib.postgres.fields import ArrayField class Region(models.Model): postcodes = ArrayField(models.CharField(blank=True, null=True), blank=True, null=True) Something like Region.objects.filter(postcodes__contains__iregex=r'^SW1A.+') (obviously that doesn't work though) -
Django pgettext and format_lazy with raw regex string
As the title says... In Django 3.0 we can do: urlpatterns = [ path(format_lazy("{text_to_translate}", text_to_translate=pgettext("URL", "text_to_translate")), ] For actually translating text in the URL beyond the prefix added by i18n_patterns. However, what about re_path. What's the equivalent, if any, for being able to do: re_path(format_lazy(r"^{text_to_translate}/(?P<...>)/$", text_to_translate=pgettext("URL", "text_to_translate")), Since this is a raw string meant to be lazily compiled by re.compile. -
Different write and read operations with DRF
I am using Django Rest Framework for a project and I am running into a problem. When the frontend creates a Team they want to reference all relationships with an ID, but when getting the Team, they want the data from the relationship. How can I achieve this? models: class Team(models.Model): class Meta: db_table = "team" team_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) class Organization(models.Model): class Meta: db_table = "organization" organization_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) class Position(models.Model): class Meta: db_table = "position" position_id = models.AutoField(primary_key=True) team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="positions") class Player(model.Model): class Meta: db_table = "player" player_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) positions = models.ManyToManyField(Position, related_name="players") serializers: class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ["team_id", "name", "organization", "positions"] positions = PositionSerializer(many=True) # This is merely for output. There is no need to create a position when a team is created. organization = OrganizationSerializer() # Since an organization already exists I'd like to just give an organization_id when creating/editing a team. # I don't think the other serializers matter here but can add them on request. So when doing POST or PATCH on a team, I'd like the front end to be able to … -
Select all reverse relations Django ORM
My models are like this: class Credit(models.Model): name = models.CharField(max_length=100) product = models.ForeignKey('Products', models.DO_NOTHING) class CreditStatus(models.Model): status = models.CharField(max_length=100) credit_id = models.ForeignKey('Credit', models.DO_NOTHING) class CreditCommision(models.Model): comission = models.CharField(max_length=100) credit_id = models.ForeignKey('Credit', models.DO_NOTHING) Is it possible to select all these tables in one query? Please note that I can't change Credit model. I tried: CreditStatus.objects.select_related('credit').filter(status='ACTIVE') But it select only 2 tables, but I need to select all?