Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing self-referencing field in Django
I have class User, with field friends class User(AbstractUser): USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['password'] username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=100) friends = models.ManyToManyField('self') when I migrated class to database, it created two tables. app_user and app_user_friends app_user in itself has no reference to friends, but app_user_friends has id of a user, and id of a friend. The issue is: qhen I try to access friends of a user by calling user = models.User.objects.get(id=user_id) print(user.friends) I get app.User.None Should I be calling it differently or is there something wrong with the model? -
Get associative array from raw sql query in django
I am developing an django web application. I am using raw sql queries without using models. Below is the code what I have till now. def getCntlData(self, FID, PID): sqlst = 'select * from employee where employeeid = %s' cursor.execute(sqlst, [PID]) data_row = cursor.fetchall() return data_row The data I want is in the format of Associative array or in the form of dictionary, like what PHP gives on querying mysql. [{"employeename":"Max","employeeage":"34"}] -
Using Django in AWS lambda
I'm writing a simple http server in aws lambda and would like to use Django, however I'm not looking to deploy an entire django app on lambda through zappa. Is there any way to just import django's HttpResponse library in a lambda function like below? from django.http import HttpResponse def lambda_handler(event, context): # TODO implement msg = "hello its me" return HttpResponse(msg, content_type='text/plain') I've already created a deployment package with all the django libraries inside and uploaded to lambda, but I'm getting an error: Requested setting DEFAULT_CHARSET, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.: ImproperlyConfigured any help is appreciated, thanks in advance! -
Struggling with Class Based Form Django (save foreign key attributes)
I have imported my MySQL DB to Django. In this DB, I have an intermediate table called GroupUsers which links User and GroupName. I would like to make a form where I can fill in the user attributes and add it directly to a selected group. So basically we have an user form with an extra field corresponding to the groups that I need to select among three categories: family, friends, pro. I'm not able to make it work. #models.py class GroupUsers(models.Model): group = models.ForeignKey(GroupName, on_delete=models.CASCADE) user = models.ForeignKey('User', on_delete=models.CASCADE) class Meta: managed = False db_table = 'group_users' unique_together = (('group', 'user'),) def __str__(self): return self.group.name class User(models.Model): email = models.CharField(unique=True, max_length=180) last_name = models.CharField(max_length=32) first_name = models.CharField(max_length=32) class Meta: managed = False db_table = 'user' verbose_name = "user" def __str__(self): return self.first_name class GroupName(models.Model): group_id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) description = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'group_name' verbose_name = 'Group' def __str__(self): return self.name #forms.py class UserCreateForm(forms.ModelForm): class Meta: model = User fields = ('first_name','last_name', 'email') def __init__(self, *args, **kwargs): super(UserCreateForm, self).__init__(*args, **kwargs) self.fields['group'] = forms.ModelChoiceField(queryset=GroupName.objects.all()) #view.py class UserCreateView(SuccessMessageMixin, LoginRequiredMixin, CreateView): template_name = 'dashboard/users/user_create_form.html' model = User form_class = UserCreateForm def get_object(self, queryset=None): obj … -
MultiValueDictKeyError at /main/add at 'num1'
The project tree look like this project files tress views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt def home(request): return render(request, 'base.html') @csrf_exempt def add(request): val1 = int(request.POST['num1']) val2 = int(request.POST['num2']) res = val1 + val2 return render(request, "main/index.html", {'add_result': res}) Index.html {% extends 'base.html' %} {% block content %} <h3>This two number adding form</h3> <form action="{% url 'add' %}" method="POST"> Enter the first here: <input type="text" name="num1" placeholder="First Number"><br> Enter the second here: <input type="text" name="num2" placeholder="Second Number"><br> <input type="submit"> </form> <hr> <div> Result : <p>{{ add_result }} </p> </div> {% endblock %} base.html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ADDTWONUMBER</title> </head> <body> <H4>THIS IS FORM OF ADDING TWO NUMBER</H4> <li><a href="main/add">click here to add two number</a></li> <div> {% block content %} {% endblock %} </div> </body> </html> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name = 'home'), path('main/add' , views.add, name = 'add'), ] Errors MultiValueDictKeyError at /main/add 'num1' Request Method: GET Request URL: http://127.0.0.1:8000/main/add Django Version: 3.0.4 Exception Type: MultiValueDictKeyError Exception Value: 'num1' Exception Location: /home/hudacse6/Env/lib/python3.7/site-packages/django/utils/datastructures.py in getitem, line 78 Python Executable: /home/hudacse6/Env/bin/python Python Version: 3.7.4 Python Path: … -
How to change Django app name from a plugin?
I've installed a plugin called Django Constance and I want to change the app name in the admin page. I normally use ugettext_lazy from Django but I couldn't here as the verbose app name in the library doesn't have it. how can I change the app name? is there a way to override only this app name from the admin template without overriding the whole content block? thanks. -
Django - Models category error in Admin: “Select a valid choice. That choice is not one of the available choices”
So I am trying to build a recipe field in django-admin. I have a Model category called Meals and I have categories to chose from on the admin page but as soon as I try to save my entry, I get the Select a valid choice. Breakfast is not one of the available choices & prevents me from saving anything. I've tried moving the daily_meals value from Recipe Field into Meal Category and uncommenting the first meal and commenting the second value in Recipe Field. I would like to be able to create new meals in the meals category just like the food category while already having pre-saved meals in the list. Meal categories admin error after save Here is my code: Models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone # Food Category class Category(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name # Meal Category class Meal(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) class Meta: ordering = ('name',) verbose_name = 'meal' verbose_name_plural = 'meals' def __str__(self): return self.name # Recipe Field class Recipe(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey(Category, … -
In Django, how do I render fields of fields from a queryset in JSON when sending a response from an AJAX view?
I'm using Django 2 with Python 3.7. In my view, I have this code for sending JSOn to an AJAX call ... articlestat_query = ArticleStat.objects.get_stats() ... data = { 'articlestat': serializers.serialize('json', list(articlestat_query)), ... } return JsonResponse(data) The query "articlestat_query" pulls models that look like this ... class ArticleStat(models.Model): objects = ArticleStatManager() article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlestats') elapsed_time_in_seconds = models.IntegerField(default=0, null=False) score = models.FloatField(default=0, null=False) The issue is when my JSON is generated, the "article" piece gets returned as "article" and its numeric primary key, e.g. "article": 12345678 How do I configure my serialization so that the JSON of that field is rendered instead of its primary key. IOW, the JSON would be "article": {"title": "hello world", "author": "George Costanza" ... -
How to modify and get session's variables with Django
I'm working on a form which is rendered in all web site's pages, I need that the server (Django) stops rendering this form on the web pages if the user closes or completes it. I've been reading about request.session but it does not clear the data when, for example, I restart the browser or clean the cache. Any idea about how to do this? Thank you in advance! -
Object of type Decimal is not JSON serializable Django 2
I am trying to reload previous cart if a user logs in, but its giving me, Object of type Decimal is not JSON serialisable and I am totally unable to track the trace of the error. I tried different ways to manipulate the cart dictionary but it seems i'm getting stuck at one single point after all. class Cart(object): def __init__(self, request): self.request = request self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart if request.user.id: order, created = Order.objects.get_or_create(user=request.user, status='CART') if not created: for p in order.particulars.all(): self.add(p.product, quantity=p.qty, update_quantity=True) else: print('user not found') def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ quantity = int(quantity) product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # update the session cart self.session[settings.CART_SESSION_ID] = self.cart # mark the session as "modified" to make sure it is saved self.session.modified = True print(self.request.user) if str(self.request.user) != 'AnonymousUser': # load the data from user order = Order.objects.get(user=self.request.user, status='CART') for k in self.cart.keys(): p … -
ModuleNotFoundError: No module named 'redsquare.moduloMatriculas'" DJANGO
I'm trying to import a models.py file from moduloMatriculas in moduloFormaturas, however the error "ModuleNotFoundError: No module named 'redsquare.moduloMatriculas'" occurs redsquare means the name of the project, in the image it has a red square. Arquitetura Django import models -
Django custom user model meta overlaps when importing from another project
I'm remaking a script to sync data from an old python2 project to a new with python3. The way the last programmer made it work appears to be by importing both, the new and old models into a script in the old project using: sys.path.append("route to the new project") It works for importing every model except for a custom user model from the new project, when I try to work with it, like using UserProfile.objects.all() it crashes with: relation "user_userprofile" does not exist LINE 1: SELECT "user_userprofile"."id" FROM "user_userprofile" The right table is user_models_userprofile, because the app containing the model is "user_models" instead of "user". The app_label from the imported model shows "user", which is probably the default app_label when extending AbstractUser, it is probably ignoring the app_label attribute from my model and using the one from AbstractUser. Any ideas of how to make it work? Also sorry for my english. -
I need a better way to add a custom field to request.data | Django Rest Framework |
i usually put it in the initial def, but it give me errors when it try to get the api from the browser. what i usually use: def initial(self, request, *args, **kwargs): self.request.data['user'] = self.request.user super().initial(request, *args, **kwargs) the error i got: 'Request' object has no attribute 'accepted_renderer' -
Trying to install django to my virtual env
I am new to linunx and pipenv. I tried to install django on my new environment with "pipenv install django" and this happend: Installing django… Adding django to Pipfile's [packages]… ✔ Installation Succeeded Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… ✔ Success! Updated Pipfile.lock (4f9dd2)! Installing dependencies from Pipfile.lock (4f9dd2)… An error occurred while installing asgiref==3.2.5 --hash=sha256:3e4192eaec0758b99722f0b0666d5fbfaa713054d92e8de5b58ba84ec5ce696f --hash=sha256:c8f49dd3b42edcc51d09dd2eea8a92b3cfc987ff7e6486be734b4d0cbfd5d315! Will try again. An error occurred while installing django==3.0.4 --hash=sha256:50b781f6cbeb98f673aa76ed8e572a019a45e52bdd4ad09001072dfd91ab07c8 --hash=sha256:89e451bfbb815280b137e33e454ddd56481fdaa6334054e6e031041ee1eda360! Will try again. An error occurred while installing pytz==2019.3 --hash=sha256:1c557d7d0e871de1f5ccd5833f60fb2550652da6be2693c1e02300743d21500d --hash=sha256:b02c06db6cf09c12dd25137e563b31700d3b80fcc4ad23abb7a315f2789819be! Will try again. An error occurred while installing sqlparse==0.3.1 --hash=sha256:022fb9c87b524d1f7862b3037e541f68597a730a8843245c349fc93e1643dc4e --hash=sha256:e162203737712307dfe78860cc56c8da8a852ab2ee33750e33aeadf38d12c548! Will try again. 🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 4/4 — 00:00:00 Installing initially failed dependencies… ☤ ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 4/4 — 00:00:00 [pipenv.exceptions.InstallError]: File "/home/codrut/.local/lib/python3.7/site-packages/pipenv/cli/command.py", line 254, in install [pipenv.exceptions.InstallError]: editable_packages=state.installstate.editables, [pipenv.exceptions.InstallError]: File "/home/codrut/.local/lib/python3.7/site-packages/pipenv/core.py", line 1992, in do_install [pipenv.exceptions.InstallError]: skip_lock=skip_lock, [pipenv.exceptions.InstallError]: File "/home/codrut/.local/lib/python3.7/site-packages/pipenv/core.py", line 1253, in do_init [pipenv.exceptions.InstallError]: pypi_mirror=pypi_mirror, [pipenv.exceptions.InstallError]: File "/home/codrut/.local/lib/python3.7/site-packages/pipenv/core.py", line 862, in do_install_dependencies [pipenv.exceptions.InstallError]: _cleanup_procs(procs, False, failed_deps_queue, retry=False) [pipenv.exceptions.InstallError]: File "/home/codrut/.local/lib/python3.7/site-packages/pipenv/core.py", line 681, in _cleanup_procs [pipenv.exceptions.InstallError]: raise exceptions.InstallError(c.dep.name, extra=err_lines) [pipenv.exceptions.InstallError]: [] [pipenv.exceptions.InstallError]: ['Traceback (most recent call last):', ' File "/home/codrut/.local/share/virtualenvs/Django-B9r4LqTh/bin/pip", line 5, in <module>', ' from pip._internal.cli.main import main', "ModuleNotFoundError: No module named 'pip'"] ERROR: ERROR: Package installation failed... To mention that a few minutes ago I installed … -
A user can manually edit another user view from URL
I just noticed that a user can manually access another users update profile view by changing to the other users pk or username(as slug) in the URL. for instance http://127.0.0.1:8000/account/dashboard/18/updateprofile Lets say that is the users update profile url, if this user changes the pk to 19 and edit, the user with pk 19 profile will be edited, is this a bug or is this an error from my side? Thank you. -
Changed DB engine to MySQL. Now Django does not create tables
I have a Django app with a standard sqlite3 DB. Now I want to use MySQL. So I changed my DATABASES in settings.py, and it works well, but I can't run server because it says django.db.utils.InternalError: (1049, "Unknown database 'django'") So I created this DB in the client, and now it says django.db.utils.ProgrammingError: (1146, "Table 'django.Cat' doesn't exist") Seems like I have to create all tables by myself, which is the worst variant I can do. #settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '/path/to/db.conf', }, } } and #conf.db [client] database = django host = localhost user = DjangoUser password = password_you_cant_guess default-character-set = utf8 How to make Django create all tables I have? I even can't run python3 manage.py with any command because it gives my this exception. -
Send audio stream blobs data using sockets from javascript to pyhon django
Im trying to send real-time input microphone auido data from javascript to python django using websockets: function handleDataAvailable(event) { if (event.data && event.data.size > 0) { if (recordedBlobs.length >99){ recordedBlobs.shift() console.log(recordedBlobs) chatSocket.send(recordedBlobs); } recordedBlobs.push(event.data); } } const handleSuccess = function(stream) { recordedBlobs = []; mediaRecorder = new MediaRecorder(stream); //mediaRecorder.onstop = handleStop; mediaRecorder.ondataavailable = handleDataAvailable; mediaRecorder.start(10); // collect 10ms of data } navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(handleSuccess); And then in python i receive the data in the consumer.py: class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): print(text_data) How can i get the waveform of the audio received in python ? i can only get a string named 'blob' while printing text_data -
Django 3 multi-base not working when migrate
I use Django 3 with 3 apps: security, historian, bench. Each app has its own database. in the settings.py: DATABASE_ROUTERS = [ 'security.router.securityRouter', 'bench.router.benchRouter', 'historian.router.historianRouter', ] DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DB_DJANGO', 'HOST': 'LOCALHOST\\SQLEXPRESS', 'PORT': '1433', 'USER': 'user', 'PASSWORD': '******', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', } }, 'BdBench': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'BD_Bench', 'HOST': 'LOCALHOST\\SQLEXPRESS', 'PORT': '1433', 'USER': 'sa', 'PASSWORD': '5eCUr1tE', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', } }, 'BdBenchMeas': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'BD_Bench', 'HOST': 'LOCALHOST\\SQLEXPRESS', 'PORT': '1433', 'USER': 'user', 'PASSWORD': '******', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', } }, 'BdSecurity': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'BD_Security', 'HOST': 'LOCALHOST\\SQLEXPRESS', 'PORT': '1433', 'USER': 'user', 'PASSWORD': '******', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', } }, 'BdHistorian': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'BD_Historian', 'HOST': 'LOCALHOST\\SQLEXPRESS', 'PORT': '1433', 'USER': 'user', 'PASSWORD': '******', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', } }, } I use for each app: a router.py file: to security / router.py: class securityRouter(object): APPS = ['security', 'auth', 'sessions', 'contenttypes'] BD = 'BdSecurity' def db_for_read(self, model, **hints): if model._meta.app_label in self.APPS: return self.BD return None def db_for_write(self, model, **hints): if model._meta.app_label in self.APPS: return self.BD return None def allow_relation(self, obj1, … -
Django inlineformset_factory and ManyToManyField field, once again
first of all, sorry for my English! I have a little problem with "inlineformset_factory" and "ManyToManyField". Perhaps the option "inlineformset_factory" isn't the right choice. I have two classes, Prodotti and Categoria. In models.py are class Categoria(models.Model): ''' tabella delle Categorie dei prodotti ''' NomeCategoria = models.CharField(max_length=50,blank=True,null=True) class Prodotti(models.Model): ''' tabella Prodotti a catalogo ''' NomeProdotto = models.CharField(max_length=50,blank=True,null=True) CategoriaProdotto = models.ManyToManyField(Categoria, related_name='prodotti_categoria') I need a form to modify the name of a specific Categoria, es. Antiossidante, and eventually change the list of Prodotti that have this Categoria. I try a lot with "inlineformset_factory" and the use of "Prodotti.CategoriaProdotto.through" but I have problems with fields, only "id" is accepted. i.e. ProdottiFormset = inlineformset_factory(Categoria, Prodotti.CategoriaProdotto.through, fields=('id',)) But, changing the name of Categoria it isn't saved. This is my project: views.py def ModificaCategoria(request, pk): # recuperiamo la categoria da modificare, bisogna passare l'ID categoria = get_object_or_404(Categoria, pk=pk) ProdottiFormset = inlineformset_factory(Categoria, Prodotti.CategoriaProdotto.through, fields=('id',)) if request.method == "POST": form = CategoriaModelForm(request.POST, request.FILES, instance=categoria) formset = ProdottiFormset(request.POST, instance=categoria) if formset.is_valid(): formset.save() return render(request, "dopo_modifica_categoria.html") # return redirect(...) else: categoria = Categoria.objects.get(pk=pk) form = CategoriaModelForm(instance=categoria) formset = ProdottiFormset(instance=categoria) context = { "form": form, "formset": formset, } return render(request, "modifica_categoria.html", context) Template: {% extends 'base.html'%} {% block head_title %}{{ … -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet when loading wsgi.py
I have a problem with Django and wsgi that I cannot pinpoint. The app works fine on my local test server and it also works fine on a local apache WAMP setup (without any venvs). When deploying it to our Linux server again the local test server runs (as does makemigrations, migrate or check): python3 manage.py runserver /home/www-test/myapp-venv/lib/python3.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.8) or chardet (2.0.3) doesn't match a supported version! RequestsDependencyWarning) /home/www-test/myapp-venv/lib/python3.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.8) or chardet (2.0.3) doesn't match a supported version! RequestsDependencyWarning) Performing system checks... System check identified no issues (0 silenced). March 18, 2020 - 16:22:20 Django version 2.2.11, using settings 'myapp.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. python3 manage.py check /home/www-test/myapp-venv/lib/python3.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.8) or chardet (2.0.3) doesn't match a supported version! RequestsDependencyWarning) System check identified no issues (0 silenced). However when I try to deploy it with wsgi/Apache on the Linux machine I get Traceback (most recent call last): File "myapp/wsgi.py", line 20, in <module> application = get_wsgi_application() File "/home/www-test/.local/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/www-test/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/www-test/.local/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/www-test/.local/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.7/importlib/__init__.py", … -
Django - safely render HTML in template
I am building a django web application where the user can submit text via a tinymce editor. For that task I use the django-tinymce extension. The question: Is it secure to render the HTML in the template using the safe filter like so ? : {{ richtext | safe }} If not, how can it be made safe ? -
Whats the difference between models and models.Model in django?(and similarly for forms and forms.Form )
I know that "models" is a module of package django.db, But why we inherit like class Foo(models.Model): while the all required fields like CharField, IntegerField, etc. are part of models, what does the subclass Model do here exactly? I am new to OOP and Django so any resources and answers are heavily appreciated and welcomed. -
Django: failed to run gunicorn
I try to run gunicorn but it failed I have install gunicorn in my virtual env (pip install gunicorn) cd intensetbm_app/intensetbm-etool gunicorn intenseTBM_eTool.wsgi:application my project architecture: envs intensetbm_app | intensetbm-etool | | intenseTBM_eTool | | | wsgi.py | | | settings.py | | | ... | | manage.py | | ... intensetbm_static wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'intenseTBM_eTool.settings') application = get_wsgi_application() trace (partial): ... File "/home/test/intensetbm_app/intensetbm-etool/intenseTBM_eTool/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' [2020-03-18 15:00:20 +0000] [43251] [INFO] Worker exiting (pid: 43251) [2020-03-18 15:00:20 +0000] [43248] [INFO] Shutting down: Master [2020-03-18 15:00:20 +0000] [43248] [INFO] Reason: Worker failed to boot. -
No URL to redirect to
I am trying to create a page where these parameters can be filled by the user. This code allows the data to be stored in mysql but does not show the saved data. And shows "ImproperlyConfigured at /public/about/ No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model." MODELS class MedicalInfo(models.Model): BLOOD = ( ('A+', 'A+ Type'), ('B+', 'B+ Type'), ('AB+', 'AB+ Type'), ('O+', 'O+ Type'), ('A-', 'A- Type'), ('B-', 'B- Type'), ('AB-', 'AB- Type'), ('O-', 'O- Type'), ) @staticmethod def toBlood(key): for item in MedicalInfo.BLOOD: if item[0] == key: return item[1] return "None" patient = models.ForeignKey(User, on_delete=models.CASCADE, related_name="patiento") bloodType = models.CharField(max_length=10, choices=BLOOD) allergy = models.CharField(max_length=100) alzheimer = models.BooleanField() asthma = models.BooleanField() diabetes = models.BooleanField() stroke = models.BooleanField() comments = models.CharField(max_length=700) def __str__(self): return f'{self.user.username} Medinfo' def save(self): super().save() VIEWS.PY class MedinfoCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/public/medinfo.html' model = MedicalInfo fields = ['bloodType', 'allergy', 'alzheimer', 'asthma', 'diabetes', 'stroke', 'comments'] def form_valid(self, form): form.instance.patient = self.request.user return super().form_valid(form) HTML {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Medinfo </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> … -
is there any reason i cannot register and then login user in the same function using Angular and Django?
Using Angular and Django. When a user registers I want them to be automatically logged in and sent to their homepage. I have a registerUser function in my UserApiComponent that looks like: registerUser(){ this.userApiService.createuser(this.register).subscribe() this.user_cred = { username: this.register.username, password: this.register.password } console.log(this.user_cred) this.userauthcomponent.login(this.user_cred) } In my UserAuthComponent my login function is: login(user_cred){ this.authenticationService.login({'username': this.user_cred.username, 'password': this.user_cred.password}).subscribe( resp => { let response = resp; this.user_id = response.user_id this.router.navigateByUrl('/dashboard/'+this.user_id) }); } From my regular login page the login function works completely fine and I am able to login a user. From my registration page I am able to easily register a user. However, when I try to register AND login a user at one time so that the user does not have to login after registering I keep getting a bad request error: *core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "http://127.0.0.1:8000/users/api-token-auth/", ok: false, …} error: non_field_errors: ["Unable to log in with provided credentials."]* I know the credentials are correct because the console.log is outputting the correct info. I also tried just putting all the login logic inside of the registerUser function as follows: registerUser(){ this.userApiService.createuser(this.register).subscribe() this.user_cred = { username: this.register.username, password: this.register.password } this.authenticationService.login({'username': this.register.username, 'password': this.register.password}).subscribe( …