Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError at /create_order/ __str__ returned non-string (type NoneType)
Getting an error when placing a new order.That was working fine before connecting with User in models. When I create a separate user_page view and link Customer model with User(import from django.contrib.auth.models) it gives this error: TypeError at /create_order/ str returned non-string (type NoneType) Code in views @login_required(login_url='login') def user_page(request): orders=Customer.objects.filter(user=request.user) context={'orders':orders} return render(request, 'blog/user_page.html', context) @unauthenticated_user def registration_page(request): if request.method=='POST': form=CreationUserForm(request.POST) if form.is_valid(): user=form.save() group=Group.objects.get(name='customer') user.groups.add(group) Customer.objects.create( user=user, ) return redirect('login') else: form=CreationUserForm() return render(request, 'blog/registration.html', {'form':form}) @login_required(login_url='login') @admin_only def home_page(request): orders=Order.objects.all() customer_data=Customer.objects.all() total_orders=orders.count() pending=Order.objects.filter(status='PENDING') total_pending=pending.count() out = orders.filter(status='OUTFORDELIEVERY') total_out = out.count() delievered = orders.filter(status='DELIEVERED') total_delievered = delievered.count() context={'orders':orders, 'customer_data':customer_data, 'total_orders':total_orders, 'total_pending': total_pending, 'total_out':total_out, 'total_delievered':total_delievered} return render(request, 'blog/home_page.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def product_page(request): return render(request, 'blog/product.html') @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def customer_page(request, id): customer=Customer.objects.get(id=id) orders=customer.order_set.all() total_orders=orders.count() myFilter=OrderFilter(request.GET, queryset=orders) orders=myFilter.qs context={'customer':customer, 'total_orders':total_orders, 'orders':orders, 'myFilter':myFilter} return render(request, 'blog/customer.html', context) @login_required(login_url='login') def create_order(request): if request.method=='POST': form=CustomerForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form=CustomerForm() context={'form':form} return render(request, 'blog/new_order.html', context) Code in Models from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user=models.OneToOneField(User, null=True, on_delete=models.CASCADE) name=models.CharField(max_length=200, null=True) email=models.EmailField() phone=models.IntegerField(null=True) date_created=models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Tag(models.Model): name=models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): name=models.CharField(max_length=200, null=True) CATEGORY=( ('INDOOR','INDOOR'), ('OUTDOOR','OUTDOOR') … -
Django/Javascript: How to pass variable to template filter in javascript function?
I am currently passing a template variable in views.py: def home_view(request, *args, **kwargs): if scrape.get_countries().count() == 0 or (timezone.now()-scrape.get_global().last_updated).total_seconds()/3600 > 24: scrape.fetch_api_data() scrape.fetch_time_data2() return render(request, 'home.html', {'all_dates': scrape.get_dates()}) where all_dates is a dictionary. In a javascript function in my home.html, I want to be able to access values from the dictionary using a key variable called code. <script> function create_graph(country, code, dates) { var date = "{{ all_dates|get_item:code|get_item:'05/05/2020'|get_item:'confirmed'}}"; window.alert(date); </script> FYI, get_item is just a simple template filter in another file @register.filter def get_item(dictionary, key): if key: return dictionary.get(key) However, when running the server, I get this error message: VariableDoesNotExist at / Failed lookup for key [code] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'global': <Country: Global>, 'countries': <QuerySet [<Country: Global>, <Country: ALA Aland Islands>, <Country: Afghanistan>, <Country: Albania>, <Country: Algeria>, <Country: American Samoa>, <Country: Andorra>, <Country: Angola>, <Country: Anguilla>, <Country: Antarctica>, <Country: Antigua and Barbuda>, <Country: Argentina>, <Country: Armenia>, <Country: Aruba>, <Country: Australia>, <Country: Austria>, <Country: Azerbaijan>, <Country: Bahamas>, <Country: Bahrain>, <Country: Bangladesh>, '...(remaining elements truncated)...']>, 'all_dates': {'..': {}, 'AX': {}, 'AF': {'05/04/2020': {'confirmed': 2894, 'recovered': 397, 'deaths': 90}, '05/03/2020': {'confirmed': 2704, 'recovered': 345, 'deaths': 85}, '05/02/2020': {'confirmed': 2469, 'recovered': 331, 'deaths': 72}, '05/01/2020': {'confirmed': 2335, 'recovered': … -
Yet another No Reverse Match
I have impletmented the detailview with views.py this afternoon. I have a model with the pk set as a UUID. the URLs line concerned is: path('user/detail/<uuid:pk>', UserDetailView.as_view(), name='userdetail'), the template referring to it is: <a href="{% url 'userdetail' user.pk %}"> which is generating the following URL: http://127.0.0.1:8000/accounts/user/detail/809b0ec2-d604-4171-8966-0817bfd59c88 however I get: Reverse for 'userdetail' with arguments '('',)' not found. 1 pattern(s) tried: ['accounts/user/detail/(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$']. If I use the username e.g. email from AbstractBase User, the detail view doesn't like it as it wants Pk or slug. Help would be greatly appreciated. -
Crispy forms are not showing in the template browsing
i am trying to make a blog in django and on the github here is the code i am trying set the cripy form template in change password option and made some file names password_change_form.html, password_change_done.html etc. but when try to browse http://127.0.0.1:8000/accounts/password_change/done/ or any kind of pages related to password change section it is not showing the crispy form. but login or signup links are showing in crispy form. password change forms are showing in basic django form. i want to change it into the desired ones. i made two apps : blogapp and accounts. i am copying the urls below: blogapp/urls.py: from django.urls import path from .views import (BlogappListView, BlogappPostView, BlogappCreateview, BlogappUpdateView, BlogappDeleteView, ) urlpatterns = [ path('post/<int:pk>/delete/',BlogappDeleteView.as_view(),name='post_delete'), path('post/<int:pk>/edit/',BlogappUpdateView.as_view(),name='post_edit'), path('post/new/', BlogappCreateview.as_view(),name='post_new'), path('post/<int:pk>/',BlogappPostView.as_view(),name='post_detail'), path('',BlogappListView.as_view(),name='home'), ] accounts/urls.py: from django.urls import path from .views import SignUpView urlpatterns = [ path('signup/',SignUpView.as_view(),name='signup') ] blog_project/urls.py: from django.contrib import admin from django.urls import path,include from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('accounts/',include('accounts.urls')), path('accounts/',include('django.contrib.auth.urls')), path ('',include('blogapp.urls')), path('',TemplateView.as_view(template_name='home.html'),name='home') ] i just can't figure out what am i missing and or what did i wrong? password change suppose to show the crispy form....not in django basic form. please let me know where is my mistake.thanx in … -
Do I need to use REST framework on Django?
Do I need to use the REST framework on Django, if I were to use a front-end framework such as React and database engine such as MongoDB or PostgreSQL? I also don't fully understand what a REST framework is. -
Django Rest Framework change serializer foreign key field's queryset based on user
Suppose I have these models: class Department(Model): ... class Building(Model): department = ForeignKey(Department, on_delete=CASCASE, related_name='buildings') staff = ManyToManyField(User) and I have 2 serializers for these models class DepartmentSerializer(ModelSerializer): class Meta: model = Department # how do I change this list of buildings accordingly to the user making the request? fields = (..., 'buildings') class BuildingSerializer(ModelSerializer): class Meta: model = Buiding fields = '__all__' What I want to do is, when a user requests for a Department, e.g. via a ViewSet, the result comes back is JSON data from the serializer, but the buildings field only contains the buildings that the user works in. So for example, user 'alice' and 'bob' both work in department 1. Department 1 consists of 5 buildings, [1, 2, 3, 4, 5]. However, alice only works in buildings 1 and 2, while bob works in buildings 3 and 4. And when alice requests to get department 1 data, she should get back { "id": 1, ... "buildings": [1, 2] } and if bob requests for department 1 as well, he should get back { "id": 1, ... "buildings": [3, 4] } Is there a way to do that using Django Rest Framework? I've thought about using … -
TemplateSyntaxError at on django and html
I am having an error "TemplateSyntaxError at /" i can not understand how to solve it.please help with this..thank you. en <!DOCTYPE html> {%load staticfils%} <html lang="en"> <head> <meta charset="UTF-8"> <title>home</title> <link rel="stylesheet" href="{%static'css/main.css'%}" /> </head> <body> <h1>Hello world</h1> </body> </html> -
Custom domain on linux server apache2 Django
I'm trying to set custom domain on my Django project, but still I have message err_CONNECTION_TIMED_OUT. Ip works fine. Apache2/project.conf <VirtualHost *:80> ServerName www.uczsieit.pl ServerAlias uczsieit.pl ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/adam/personal_blog_project/personal_blog/conf/static <Directory /home/adam/personal_blog_project/personal_blog/conf/static> Require all granted </Directory> Alias /media /home/adam/personal_blog_project/personal_blog/conf/media <Directory /home/adam/personal_blog_project/personal_blog/conf/media> Require all granted </Directory> <Directory /home/adam/personal_blog_project/personal_blog/conf> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/adam/personal_blog_project/personal_blog/conf/wsgi.py WSGIDaemonProcess django_app python-path=/home/adam/personal_blog_project/personal_blog python-home=/home/adam/$ WSGIProcessGroup django_app </VirtualHost> I added domain to Django Allowed hosts and set Reverse DNS and A/AAAA Records as well. In error.log of apache lack of info about errors. -
Pycharm no longer runs python scripts inside django project - not finding settings
I tried changing the root directory for the project (to match a productions servers structure so relative importing matches) and managed to screw up pycharm to the point that I can't even run scripts on new django projects. I imagine this has to do with how the venv is configured in pycharm, but have tinkered for hours changing relative import names and can not figure it out. I vaguely remember having to change the environment variables in the pycharm configs, but can't find anything like that when googling. Thank you in advance for any and all help. The error I receive is: C:\Users\steve\Documents\www\Scripts\python.exe C:/Users/steve.levy/Documents/www/mysite/main/test.py Traceback (most recent call last): File "C:/Users/steve/Documents/www/mysite/main/test.py", line 1, in <module> from mysite.main.models import ModelTest File "C:\Users\steve\Documents\www\mysite\main\models.py", line 5, in <module> class ModelTest(models.Model): File "C:\Users\steve\Documents\www\lib\site-packages\django\db\models\base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\steve\Documents\www\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\steve\Documents\www\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\steve\Documents\www\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\steve\Documents\www\lib\site-packages\django\conf\__init__.py", line 61, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Process finished with exit code 1 manage.py: #!/usr/bin/env python """Django's command-line … -
Django and MongoDB on Centos 7
I'm trying to connect Django and MongoDB on a remote machine running Centos 7. I've made the following changes to the settings.py file DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'database_name', 'HOST': '127.0.0.1', 'PORT': 27017, 'USER': 'mongodb_user_name', 'PASSWORD': 'mongo_db_password', } } Version numbers of packages used: Django 2.2.12 djongo 1.3.2 MongoDB 4.2.5 When I start the server using python3 manage.py runserver, I get the following message: Performing system checks... System check identified no issues (0 silenced). May 07, 2020 - 20:29:57 Django version 2.2.12, using settings 'djangoserver.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However, when I connect to the remote machine using it's ip address http://XXX.XX.XX.XX:8000, I get an unable to connect message. Is the settings file set correctly? Any help will be appreciated. -
Django query omitting expected results
I must perform a query on a large database with a somewhat intricate modeling, which I will try to abridge below: class ScreeningItem(models.Model): # other fields receivedItem = models.OneToOneField(ReceivedItem, null=True, on_delete=models.SET_NULL) class ReceivedItem(models.Model): # other fields dossier = models.ForeignKey(Dossier, null=True, on_delete=models.SET_NULL) class Dossier(models.Model): # other fields subjects = models.ManyToManyField('SubjectTypes', through='Subjects', through_fields=('dossier', 'subjectType')) class Subject(models.Model): main = models.BooleanField(null=True) dossier = models.ForeignKey(Dossier, null=True, on_delete=models.SET_NULL) subjectType = models.ForeignKey(SubjectType, null=True, on_delete=models.SET_NULL) class SubjectType(models.Model): # other fields name = models.CharField(max_length=255, null=True, blank=True) parent = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) Now, the problem is that I must find in ScreeningItem table items when the far, far away related field SubjectType.name contains specific words. No, worse. As you can see below, there's a parent-child self reference in that model, and I must look for those specific words in the related SujectType, its parent, and its grandparent, in case they exist. My attempt: exp = 'something' queryset = ScreeningItem.objects.filter( Q(receivedItem__dossier__subjects__subjecttype__name__iregex=exp) | Q(receivedItem__dossier__subjects__subjecttype__parent__name__iregex=exp) | Q(receivedItem__dossier__subjects__subjecttype__parent__parent__name__iregex=exp)) However, when I received a number of records much below I was expecting, I checked the database and discovered, for my astonishment, that there were many ScreeningItem which had a ReceivedItem which had a Dossier which was related to SubjectTypes which had the word I was … -
Errors deploying Django on Heroku
I have 2 problems Before I didn't upload my model to the DB (MariaDB) error load model Now it gives me an error in the configuration DB Before I used this configuration import dj_database_url from decouple import config DATABASES = { 'default': dj_database_url.config( default=config('JAWSDB_MARIA_URL') ) } Now the documentation shows another config Django but for both it shows me the same error enter load -
Django: How to graph/visualize the variable average in a scatter plot?
was wondering how do I visualize this data in a scatter plot way so it appears in the same Django template page below so that the average price is in the middle as a dot showing the price and the other prices in the list are other smaller dots scattered around it? Ford C-MAX 2011 1.6 Diesel 3950 May 7, 2020, 7:28 p.m. Ford C-MAX 2011 1.6 Diesel 5250 May 7, 2020, 7:28 p.m. Ford C-MAX 2011 1.6 Diesel 16950 May 7, 2020, 7:28 p.m. Ford C-MAX 2011 1.6 Diesel 3950 May 7, 2020, 7:32 p.m. Ford C-MAX 2011 1.6 Diesel 5250 May 7, 2020, 7:32 p.m. Ford C-MAX 2011 1.6 Diesel 5950 May 7, 2020, 7:32 p.m. Ford C-MAX 2011 1.6 Diesel 6750 May 7, 2020, 7:32 p.m. Ford C-MAX 2011 1.6 Diesel 8950 May 7, 2020, 7:32 p.m. {'price__avg': 7125.0} {'price__max': 16950} {'price__min': 3950} Note that these values are coming from a query form and results are being drawn from the database so for a different query (e.g. Ford Focus etc. ) these and price values would be different. Basically just looking for a way to visualize the results with emphasis on the average. -
Pass value from url request with Django generic detail view
From the GenericList, when clicking on one I redirect towards url(r'^machine/(?P<pk>[0-9]+)$', MachineDetailView.as_view(), name='machine-detail'), Where class MachineDetailView(DetailView): model = Awg template_name = 'gui/machine_detail.html' context_object_name = 'last_entry' ordering = ['-timestamp'] However what I need is to fetch AWG records where machine.id is foreign key in AWG's. In my mind it would look like that: class MachineDetailView(DetailView): last_entry = Awg.objects.filter(machine_id=Machine.objects.filter(id=pk).first()).first() model = Awg template_name = 'gui/machine_detail.html' context_object_name = 'last_entry' ordering = ['-timestamp'] That doesn't work because I don't know how to get that pk that is in the url requested. Apologies if noob, I did try to look in django docs. -
What does it mean by "For populating columns a and b, add the code in this model" in Django?
I have a requirement at work where the columns of a paginated table in the UI should be: Person ID First Name Last Name Person Status: Latest Status of Person Full Name Is Adult (Adult if person > 18 years of age) Profile Pic (Icon) if available Now, I have three models, namely: Person: Fields first_name, last_name, date_of_birth, gender, profile_pic (Nullable), created_at, modified_at PersonStatus: Fields person (FK Person), status_text, created_at, modified_at FormulaFields: formula(TextField that is able to store python code of up to 2000 characters), column_number (Integer >=4), created_at, modified_at I'm unclear what FormulaFields does, will need to clarify on Monday but want to finish it, or at least do something. For populating columns 5 and 6, I need to add the code in FormulaFields model. The column number of Formula Field should map with the Column number of above table (at the top, person ID to profile_pic). The above line confuses me, "For populating columns 5 and 6, add the code in FormulaFields model". To show the column full name and is adult, I need to add them as columns in the FormulaFields model, or do I add a method in FormulaField that will calculate them (but FormulaField doesn't … -
Render Markdown to HTML in Django templates
I would like to render Markdown to HTML so that I could simply write markdown inside my HTML templates. Example: home.html: #This is a simple markdown in HTML And I would like Django to interpret my Markdown and display it as if it was HTML: <h1> This is a simple markdown in HTML </h1> What would be the easiest way to implement it? -
django ListView with aggregated data from another model
I want to create a list of my projects with the summary of cost elements connected to each project. How can I do that in django view? The head row of my expected table is: Project name, Sum cost of activities Proj1 100 Proj2 150 Here are my models: class Project(models.Model): name = CharField("Name",max_length=50) class Activity(models.Model): cost = BigIntegerField("Cost", default=0) project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True,) class ProjectListView(ListView): queryset = Project.objects.all() #model = Project def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) ??? # want to calculate sum cost of activities somehow return data -
How to multi thread and do tasks in django?
I am working on a website based on Django. users can register and enter a URL, and my website should check and get some information from that URL, for example, every hour, how should I handle these tasks? how should I write the structure of my website? -
Python Django - compare datetime weeks
I have a queryset of objects with a DateTimeField and another queryset of objects with a DateTimeField. How can I find which objects from the first queryset A belong to the same week of an object of the queryset B. So, the queryset A is filled with events, and the queryset B is filled with objects representing weeks of the year. I'd like to map the events to their corresponding week object (the week object has a DateTimeField that is created on monday using datetime.today) I can imagine ways to solve this but there must be an elegant, better way. I'm using django 3.0.5, there is no way to create a query from its week number. -
Looking for the right way how to update existing object with form and Dynamic RadioSelect Choice in Django
I have been learning Django a few weeks. I am trying to render list of entries dynamically with possibility to choose one of them by Radio Select Choice. Chosen item has to update field in existing object model. I have tried a lot of ways to do it recently. I have written the code that render list of radio buttons dynamically but I have not figured out how to catch selected item and updated corresponding object in model with form. Could anyone help me to catch the idea which is the best way to render list of entries with radio buttons dynamically, select one of them and update corresponding field in existing object model. Thanks. ### Model class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='Comments_Article') author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField(max_length=500) chosen = models.BooleanField(default=False) ### View class ChooseComment(FormMixin, DetailView): model = Article template_name = 'comment_page.html' context_object_name = 'get_article' form_class = ChooseCommentForm def get_form_kwargs(self): kwargs = super(ChooseComment, self).get_form_kwargs() kwargs['article_object'] = self.get_object().id return kwargs def post(self,request, *args, **kwargs): id = request.POST['chosen'] obj = get_object_or_404(Comment, id=id) form = ChooseCommentForm(request.POST, instance=obj) if form.is_valid(): return self.form_valid(form) else: self.form_invalid(form) def form_valid(self, form): self.object = form.save(commit=False) self.object.chosen = … -
how can I detect the machine language in django?
So, I know that language = request.session.get(LANGUAGE_SESSION_KEY) gets language saved to session but my question is.. Is this the language used by the computer? and if not how can I detect the language used by my computer? -
how to store location in Point field using Mongo Engine and fetch nearest 5 restaurant around a location
I am new to mongoengine and trying to store location data into MongoDB using mongoengine , I am doing some silly mistake but not able to figure out. My requirement is to store location data into MongoDB and fetch all the restaurant a in 1000 Meter radius around a mobile device location My Model Class from mongoengine import * class ResLocation(Document): id = IntField(required=True) loc = PointField(required=False) updated_date_time = DateTimeField(default=datetime.datetime.utcnow) In the views.py saving the location `def store_restra_location(id, lat, lon): location = {type: "Point", "coordinates": [lat, lon]} res_location = ResLocation(id=id, loc=location) res_location.save()` Fetching the nearest restaurant def get_nearest_res(lat, lon): distance = 1000 # distance is in meters restaurants = ResLocation.objects(point__near=[lat, lon], point__max_distance=distance) all_res = [] for res in restaurants: all_res += [ { "id": res.id, "lat": res.lat, "lon": res.lon } ] I am a completely noob in dealing with Mongo with mongoengine -
python manage.py collectstatic - Digital Ocean - Django
I tried again to host my django project on digital ocean and I get this error after I send "python manage.py collectstatic". Can you help me interpret this error? I can't understand if it is correlated to my code in django or something that I wrote wrong during the process of hosting the project on the server. TRACEBACK (django_env) mattia@droplet:~/piattaforma$ python manage.py collectstatic Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect for path, storage in finder.list(self.ignore_patterns): File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/home/mattia/piattaforma/static' MY DJANGO PROJECT CODE piattaforma/settings.py """ Django settings for piattaforma project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ … -
Renaming a Django superclass model and updating the subclass pointers correctly
I'm having trouble refactoring a superclass in Django v2.12 involving three models, with one superclass model and two subclass models: class BaseProduct(models.model): # ... class GeneralProduct(BaseProduct): # ... class SoftwareProduct(BaseProduct): # ... The BaseProduct model needs to be renamed to just Product, so I changed this code to: class Product(models.model): # ... class GeneralProduct(Product): # ... class SoftwareProduct(Product): # ... And then ran python manage.py makemigrations, in which Django seems to correctly see what changed: Did you rename the buyersguide.BaseProduct model to Product? [y/N] y Did you rename generalproduct.baseproduct_ptr to generalproduct.product_ptr (a OneToOneField)? [y/N] Did you rename softwareproduct.baseproduct_ptr to softwareproduct.product_ptr (a OneToOneField)? [y/N] y Migrations for 'yourapp': .../yourapp/migrations/002_auto_20200507_1830.py - Rename model BaseProduct to Product - Rename field baseproduct_ptr on generalproduct to product_ptr - Rename field baseproduct_ptr on softwareproduct to product_ptr So far so good. The migration it comes up with looks about as terse as it should be: # Generated by Django 2.2.12 on 2020-05-07 18:30 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('yourapp', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='BaseProduct', new_name='Product', ), migrations.RenameField( model_name='generalproduct', old_name='baseproduct_ptr', new_name='product_ptr', ), migrations.RenameField( model_name='softwareproduct', old_name='baseproduct_ptr', new_name='product_ptr', ), ] This all looks perfect, but applying that migration using python manage.py migrate crashes out: … -
Can't post data from Angular 8 to Django
I'm trying to send data from Angular to Django and I keep getting the following error message in my browser: HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8000/polls/token", ok: false, …} error: error: SyntaxError: Unexpected token N in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:32795:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6802:31) at Zone.runTask (http://localhost:4200/polyfills.js:6579:47) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:6876:34) at invokeTask (http://localhost:4200/polyfills.js:8014:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:8051:21) message: "Unexpected token N in JSON at position 0" stack: "SyntaxError: Unexpected token N in JSON at position 0↵ at JSON.parse (<anonymous>)↵ at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:32795:51)↵ at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6802:31)↵ at Zone.runTask (http://localhost:4200/polyfills.js:6579:47)↵ at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:6876:34)↵ at invokeTask (http://localhost:4200/polyfills.js:8014:14)↵ at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:8051:21)" __proto__: Error text: "None" __proto__: Object headers: HttpHeaders lazyInit: () => {…} lazyUpdate: null normalizedNames: Map(0) {} __proto__: Object message: "Http failure during parsing for http://localhost:8000/polls/token" name: "HttpErrorResponse" ok: false status: 200 statusText: "OK" url: "http://localhost:8000/polls/token" __proto__: HttpResponseBase Here is my Angular frontend: data.service.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; const httpOptions = { withCredentials: true, }; const test = 'test'; @Injectable({ providedIn: 'root' }) export class DataService { constructor(private http: HttpClient) { } public sendPostRequest(){ return this.http.post("//localhost:8000/polls/token", test, httpOptions); } } here's an excerpt of …