Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Get a single queryset values list from two related models
I have an user model class User(AbstractBaseUser): name = models.CharField(max_length=100, default='Default') email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) active = models.BooleanField(default=True) and a related SecondaryEmails model class SecondaryEmails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='secondary_emails') email = models.EmailField() is_validated = models.BooleanField(default=False) Now I want to create a method to get a values_list containing both the User model's email and all the emails stored in the related SecondaryEmails model. I am able to get a values_list containing only the email of the User model >>> User.objects.filter(email='test@gmail.com').prefetch_related('secondary_emails').values_list('email') >>> <QuerySet [('test@gmail.com',)]> The related SecondaryEmails model contains another two emails 'a1@gmail.com', 'a2@gmail.com'. I wanted these two emails also to be appended in the values_list() like the following: <QuerySet [('test@gmail.com',), ('a1@gmail.com',), ('a2@gmail.com',)]> Thanking you in advance. -
makemigrations can't detect change in django
I know there are a lot of similar questions: but I will describe my problem as simply as I can. This is the app I want to migrate. This is my setting.py This is what happens when I type in makemigrations(after I add a field in my model) This is what happens when I type in showmigrations(after I add a field in my model) I have reinstall django using pip, I have created new app , I have created new project,new venv, I even have reinstall python itself, all same story. I suspect my django source code has been corrupted, but when I install django using pip, it use file that is downloaded before instead download new file. Trust me, I have tried all the way you a newbie could possibly tried, could someone tell me how to redownload django itself or someone who is way smarter than me know what's going on right now. Thx! -
unable to filter() users with their date_joined field
I want to count all the users whose date_joined matches with 'today's' date. I have two users who have today's date in the date_joined field but the count always returns zero. I am perhaps not filtering the data correctly. These are the waays that I have tried to filter the data models class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique= True) full_name = models.CharField(max_length=255) phone_no = models.CharField(max_length=10, blank= True) address = models.CharField(max_length=500, blank= True) plan = models.CharField(max_length=255, blank= True) age = models.CharField(max_length=2, blank= True) date_joined = models.DateTimeField(default=timezone.now) views from datetime import datetime, date def dashboard(request): all_users = CustomUser.objects.all().exclude(is_staff = True).count() all_users_bydate = CustomUser.objects.all().filter(date_joined= datetime.today()).count() print(all_users_bydate) all_users_bydate = CustomUser.objects.all().filter(date_joined= datetime.today().date()).count() all_users_bydate = CustomUser.objects.all().filter(date_joined= datetime.today().date()).count() even tried to explicitly filter all_users_bydate = CustomUser.objects.all().filter(date_joined= date(2021, 12, 11)).count() all of these ways did not work at all and always retuned zero. Please rectify me what I am doing wrong. -
Python - Django: select mulitple fields from different models to serialize into one json result
I'm currently working in my first Django project and am using the authentication mechanism that is included with Django. I currently have a game model with a foreign key relationship to a user in the auth_user table. Here are the following fields: class Game(models.Model): game_id = models.UUIDField(default=uuid.uuid4, editable=False, max_length=10) host = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) join_code = models.CharField(max_length=100, null=True) active = models.BooleanField(default=True) I currently have a view method that just grabs all of the active game objects, and then passes those results into a serializer that serializes the data to be returned to the client. def get(self, request, format=None): games = Game.objects.filter(active__exact=True) serializer = GameSerializer(games, many=True) return Response(serializer.data) I want to add the username and email fields that are in AUTH_USER_MODEL to the results to be serialized, but I haven't been able to find examples of adding specific fields from a related model to the results that are serialized. Basically, I'm trying to figure out the django model equivalent of the following SQL statement select u.username, u.email, g.* from game g inner join AUTH_USER_MODEL u on u.user_id = g.host_id Finally, once I have the results from that sort of query, how would I serialize the combined objects? Do I need … -
Add and delete in one instance django Formset
I have a formset which generally works (Add, Delete, Edit) items except when I decide to Add and Delete(or vice versa) in one instance, the formset throws the 'id': ['This field is required.'] error. Below are prints of request.POST: When it works: <QueryDict: {'csrfmiddlewaretoken': ['lnEG6qbrWRg4NdkKwg1UU86KTBuIgJIc4ZqJAWvZpASgxECnicmlUmVhJIInvqEJ'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-id': ['6'], 'form-0-year': ['2023'], 'form-1-id': ['7'], 'form-1-year': ['2024'], 'form-2-id': ['8'], 'form-2-year': ['2025']}> When it does not work (I deleted 2024 and added 2026): <QueryDict: {'csrfmiddlewaretoken': ['fh0mPGYzVt0AOjpE5Q9JuTp1zuqwNCuMYTMpjci7ocCMyKHhRMuau7eypBEb2jqj'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-id': ['6'], 'form-0-year': ['2023'], 'form-1-id': ['8'], 'form-1-year': ['2025'], 'form-2-id': [''], 'form-2-year': ['2026']}> [{}, {}, {'id': ['This field is required.']}] Model: class Year(models.Model): year = models.CharField(max_length=100, null=True) user = models.CharField(max_length=300, null=True, blank=True) Forms: YearFormset = forms.modelformset_factory( Year, fields=('year',), extra=1, widgets={ 'year': forms.TextInput( attrs={ 'require': 'required', 'class': 'form-control', 'placeholder': 'Enter Year here' }) } ) View: def year(request): year_items = Year.objects.filter(user=1) year_set = YearFormset(queryset=year_items) year_set.extra = 0 if year_items else 1 context = {'years':year_set} if request.method == 'POST': print(request.POST) submit_year = YearFormset(request.POST) if submit_year.is_valid(): Template: <form method="POST"> {% csrf_token %} <br> {{ years.management_form }} {% for year in years %} <div class="form-row"> <div class="col-4"> <div class="input-group"> {{year.id}} {{year.year}} <button class="btn btn-success add-form-row">+</button> </div> <br> </div> … -
Serialize and create one-to-one relation with parent_link true in django and django rest framework
How to save the object with one-to-one relation and having parent_link=True using serializer. Below are my models and serializer having some fields from the actual model that I wanted to implement. I am not able to save the 'user' relation in the database. It is throwing the integrity error. class Audit(models.Model): is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True class User(Audit): class Meta: db_table = 'user' email = models.EmailField(unique=True) password = models.TextField() is_active = models.BooleanField(default=False) class UserProfile(User): class Meta: db_table = 'user_profile' user = models.OneToOneField(User, on_delete=models.CASCADE, parent_link=True, primary_key=True) address = models.TextField(null=True) dob = models.DateField() language = models.CharField(max_length=50, null=True) class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['user', 'address', 'dob', 'language'] And the requested data looks like this. { "email": "abc@pqr.com", "password": "1234", "dob": "2021-12-11", "language" : "English" } -
How to define a relationship in Django Models such that a space in a model can be allocated to an object without overlapping?
I need to define models in Django such that it should check the server objects can fit into the rack object in question without overlapping each other and that you only use as many space(in Us) as you actually have in the rack. I tried defining the Django model as follows: ` from django.db import models class Location(models.Model): name = models.CharField(max_length =200) def __str__(self): return str(self.name) class Rack(models.Model): id = models.IntegerField(primary_key = True, auto_created = True) size = models.IntegerField() location = models.ManyToManyField(Location) def __str__(self): return str(self.id) class Server(models.Model): id = models.IntegerField(primary_key= True, auto_created=True) size = models.IntegerField() rack_id = models.ForeignKey(Rack, on_delete=models.CASCADE) owner = models.CharField(max_length = 200) locations = models.OneToOneField(Location, on_delete=models.CASCADE) def __str__(self): return str(self.id) ` I am unsure how to define the locations such that if I choose a location for a server, it is assigned to a location within the Rack, without overlapping the same location by any other server. At the same time, I need to make sure I only use as many space(in Us) as I actually have in the rack. -
Error 'AnonymousUser' object has no attribute '_meta'
I am writing an authorization system on my site and when I try to log in, I get the error 'AnonymousUser' object has no attribute '_meta'. Why is this happening? Here is structure of my project: ├───ithogwarts │ │ db.sqlite3 │ │ manage.py │ │ │ ├───ithogwarts │ │ │ asgi.py │ │ │ settings.py │ │ │ urls.py │ │ │ wsgi.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ settings.cpython-310.pyc │ │ settings.cpython-39.pyc │ │ urls.cpython-310.pyc │ │ urls.cpython-39.pyc │ │ wsgi.cpython-310.pyc │ │ wsgi.cpython-39.pyc │ │ __init__.cpython-310.pyc │ │ __init__.cpython-39.pyc │ │ │ ├───main │ │ │ admin.py │ │ │ apps.py │ │ │ models.py │ │ │ tests.py │ │ │ urls.py │ │ │ views.py │ │ │ __init__.py │ │ │ │ │ ├───migrations │ │ │ │ __init__.py │ │ │ │ │ │ │ └───__pycache__ │ │ │ __init__.cpython-310.pyc │ │ │ __init__.cpython-39.pyc │ │ │ │ │ ├───static │ │ │ └───main │ │ │ ├───css │ │ │ │ footer.css │ │ │ │ header.css │ │ │ │ index.css │ │ │ │ │ │ │ ├───img │ │ │ │ 1.jpg │ │ … -
django restrict choice options according to the usertype
I have two user types usertype a and usertype b i have a form to update the task with fields name,info and status i have STATUS_CHOICES = ( ('A','A'), ('B','B'), ('C','C') ) the user type a should c only ('A','A'),('B','B'), in dropdown and usertype b should have (C,C) as dropdown how do i acheive this in django the user type a should c only ('A','A'),('B','B'), in dropdown and usertype b should have (C,C) as dropdown how do i acheive this in django forms.py class Form(forms.ModelForm): class Meta: model = Model fields = (name', 'info',status') -
Django - Turn settings.DEBUG to True for one test
I have this test for checking if I can ping the swagger endpoint from django.test import SimpleTestCase from django.test.utils import override_settings from django.urls import reverse from rest_framework import status class SwaggerTest(SimpleTestCase): @override_settings(DEBUG=True) def test_successful_swagger_ping(self): """ Test to ensure that Swagger can be reached successfully. If this test throws 5XX that means there's an error in swagger annotation on some view function. """ response = self.client.get(reverse('swagger')) self.assertEqual(response.status_code, status.HTTP_200_OK) So this test fails, because I only have swagger added to url when settings.DEBUG=True. I thought @override_settings(DEBUG=TRUE) would fix that, but it doesn't. My test passes when I manually set settings.DEBUG=True under my settings.py file, otherwise it throws an error because it can't find the endpoint. I've tried decorating both the class and the function with @override_settings -
Can't send email through Django and Gmail
I keep getting this error while trying to send mail through gmail on my sign up form: raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n5.7.14 7Iv4Nop2BfVsxIWEI1h5NxEG5QKSiQP2IRGqFYj-mB1tr4my5OBVeMzEbuG1hSttzGi2z\n5.7.14 O6-2CSgs_9v57jLx6MkoOy8yKLcw5zgCYzPQ40opvla_U9TqolpkdWMi5c4jyT1_>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 v8sm557096wrc.114 - gsmtp') Here is my smtp settings # smtp settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'xbxx@gmail.com' EMAIL_HOST_PASSWORD = 'dgesfgg' -
How does a method of a class class run if you haven't instantiated an object for that class? Referring to Python's TestCase class
I am fairly new to Python (and programming in general) so this may be a noob question, but I was of the understanding that in python, when you create a class, and you create X methods within it, that if you want to leverage those methods, you need to instantiate the class or create an instance of the class. I am reviewing the TestCase module (testing goat for TDD) and I notice that we can run the program (performs all the logic within the methods of the classes) without actually creating any instance objects to "call" those methods directly. So my question is...how is it running. Ex. class AddStuff(TestCase): def test_equal_two(self): two = 1 + 1 self.assertEqual(two, 2) When I run python manage.py test, this will run, even though I haven't created an instance of AddStuff...I don't get it... -
Multiple model inheritance with one concrete and one abstract model in django
I wanted to inherit the Grandparent abstract model, parent concert model in the child model. How I'll be able to achieve this in django? There are conflicts in field name as the abstract model is having audit fields. which is common going to be common in both parent and child class. How do I override or remove the common field coming from the parent model? Below is the models which showcase what I wanted to achieve. class Audit(models.Model): is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True class User(Audit): class Meta: db_table = 'user' email = models.EmailField(unique=True) phone = models.CharField(validators=[phone_regex], max_length=50, unique=True) is_active = models.BooleanField(default=False) class UserProfile(User, Audit): class Meta: db_table = 'user_profile' address = models.TextField(null=True) profile_image = models.TextField(null=True) dob = models.DateField() ..... -
Serving Media files in cPanel Shared Hosting for Django Web App
I am not able to display media files on Cpanel shared hosting Django web app. I receive a Error 404 URL Not Found whenever I try to access the media file. I have specified + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my urls.py file. This error only occurs whenever DEBUG = False. I am using whitenoise to serve the static files without any issue it is only the media directory that causes the 404 web error. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') I am using Python v3.8.6, Django=2.1 and CPanel Shared Hosting via NameCheap. I know it's recommended to have a webserver to store and serve media files in Production Environment but I am unable to edit the Apache httpd.conf file as mentioned in the Django documentation. -
Django Limiting Session Login Time to N seconds
I am trying to limit the amount of time a user can stay logged in for using the settings.py and using Sessions. settings.py LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_AGE = 60 SESSION_SAVE_EVERY_REQUEST = True home.html {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! <p><a href="{% url 'logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> {% endif %} {% endblock %} urls.py from django.urls import path from django.views.generic.base import TemplateView # new urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home') ] views.py from django.shortcuts import render def index(request): # now the index function renders the home page return render(request,'home.html') Currently it stays logged in and displays the Hi user.username no matter how long the time passes. -
How to send non-empty Origin header in POST request if running an app on localhost?
I just upgraded to Django 4 and it includes the ticket 16010 with csrf origin verification changes. To my knowledge, if you are running an app on localhost, browsers won't send origin (they will send null). So, whenever we run a Django app on localhost, we should expect a header Origin: null in POST requests. But with the recent change CSRF on localhost can't be validated because of another change - CSRF_TRUSTED_ORIGINS now need to have a scheme. release notes Is it possible to add a non-empty Origin header when POSTing from localhost? -
is using base.hml in django templates good option?
I know extends base.html file in other html page is good to avoid repetition of same html tags , But is it good when come to page load speed does it increase load time of page ? , is page load time that extends from base.html same as page who does not ? -
Django Model does not exist error When accessing tabel from admin Panel
Ok so I was working on a project locally and then I followed a guide https://www.codingforentrepreneurs.com/blog/deploy-django-to-digitalocean-app-platform in order to deploy on digital ocean and i did successfully, However; When I open the Django admin panel and try to access my tables, some of the tables open up just fine while two other tables give the following error as illustrated.Error 1,Error 2. After hours and hours of searching questions here I reached a conclusion that something is wrong with the migrations. Regardless of how much I tried I failed to make it work. I will provide the Logs maybe it helps you out more. 10.244.3.92 - - [10/Dec/2021:22:08:06 +0000] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 3912 "https://scheduler-live-rcfr9.ondigitalocean.app/admin/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36" [scheduler-live] [2021-12-10 22:08:06] Not Found: /static/admin/js/nav_sidebar.js [scheduler-live] [2021-12-10 22:08:06] 10.244.3.92 - - [10/Dec/2021:22:08:06 +0000] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 404 3906 "https://scheduler-live-rcfr9.ondigitalocean.app/admin/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36" [scheduler-live] [2021-12-10 22:08:08] Internal Server Error: /admin/myapi/schedule/ [scheduler-live] [2021-12-10 22:08:08] Traceback (most recent call last): [scheduler-live] [2021-12-10 22:08:08] File "/workspace/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute [scheduler-live] [2021-12-10 22:08:08] return self.cursor.execute(sql, params) [scheduler-live] [2021-12-10 22:08:08] psycopg2.errors.UndefinedColumn: column myapi_schedule.Start_Time does not exist [scheduler-live] [2021-12-10 22:08:08] … -
Dango - How to use "setUpTestData" with TransactionTestCase
I've created a test class, which is a TransactionTestCase and I tried setting up the test data as so test.py class SomeTester(TransactionTestCase): @classmethod def setUpTestData(cls) -> None: cls.some_data = 'stuff" but when I reference self.some_data in test functions it says self.some_data is not defined. Can you not use setUpTestData with TransactionTestCase? This works with TestCase class. -
Initialize field to constant value in django Form
How can I set up a model/form combination so that the field in the model is initialized to a fixed value and there is no form element displayed when the form is presented to the user? I just want to initialize Source.updated = datetime.datetime(2000, 1, 1, 0, 0, 0, 0) each time a new Source is created from a form. The user cannot over-ride this initial default. (Subsequent interaction with the app will cause this field value to change, but it's not just auto_now because I want the initial value to be far in the past.) What I have now is class Source(Model): name = models.CharField(max_length=168, help_text="Source name") link = models.URLField(primary_key=True, help_text="Data source link") type = models.CharField(max_length=64, help_text="Data source type") # TODO: add this field to the model. # have it initialize to 2000-01-01 #updated = models.DateTimeField(help_text="Most recent time this source has been updated") class SourcesForm(forms.ModelForm): class Meta: model = models.Source fields = ['name', 'link', 'type',] # TBD: how to configure the form so that # it initializes the "updated" field with a fixed value # when .save() is called The logic I'm trying to implement is that: we're getting data from a remote source, so I want to know … -
is there a way to fluidly calculating total sales using JS with Django
I'm looking for a way to take the information being entered into a database and not only calculate the overall total for a year but also calculate the total for individual months. I'm using Django and Javascript. The Django View: @login_required def proposal_signed(request): prop = Proposal.objects.all().order_by('proposal_approved_date') return render(request, 'client/proposal_signed.html', { 'prop': prop, }) The HTML and JS: {% extends 'client/base.html' %} {% block content %} <br> <div class="jumbotron jumbotron-fluid"> <div class="container"> <div class="text-center"> <h1 class="display-4"> Sales For Signed Proposals </h1> </div> </div> </div> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> <title></title> </head> <div class="container"> <table id="countit"> <tr> <th><strong>Approval Date:</strong></th> <th><strong>Job Type:</strong></th> <th><strong>Address:</strong> <th><strong>Client:</strong></th> <th><strong>Bid/Job Total:</strong></th> </tr> {% for item in prop %} {% if item.proposal_approved_date %} <tr> <td>{{ item.proposal_approved_date }}</td> <td>{{ item.client.requested_service }}</td> <td>{{ item.client.work_site_address }}</td> <td>{{ item.who_to_bill_name }}</td> <td class="count-me">{{ item.client.invoice_set.get.bill_amount }}</td> </tr> {% endif %} {% endfor %} </table> <script language="javascript" type="text/javascript"> var tds = document.getElementById('countit').getElementsByTagName('td'); var sum = 0; for(var i = 0; i < tds.length; i ++) { if(tds[i].className === 'count-me') { sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML); } } document.getElementById('countit').innerHTML += … -
Django4 + Jinja2 href url not working in template
I can't get simple urls to work in my Jinja2 templates in Django 4. This literally should be the easiest code, but it keeps throwing errors like this: ("Encountered unknown tag 'url'.",) Request Method: GET Request URL: http://127.0.0.1:8000/browse/a/ Django Version: 4.0 Exception Type: TemplateSyntaxError Exception Value: ("Encountered unknown tag 'url'.",) Exception Location: /home/joop/.local/share/virtualenvs/khinsider-gSzZqK6P/lib/python3.8/site-packages/django/template/backends/jinja2.py, line 47, in get_template Python Executable: /home/joop/.local/share/virtualenvs/khinsider-gSzZqK6P/bin/python Python Version: 3.8.10 Python Path: ['/home/joop/sites/khinsider', '/snap/pycharm-community/261/plugins/python-ce/helpers/pydev', '/home/joop/sites/khinsider', '/snap/pycharm-community/261/plugins/python-ce/helpers/third_party/thriftpy', '/snap/pycharm-community/261/plugins/python-ce/helpers/pydev', '/home/joop/.cache/JetBrains/PyCharmCE2021.3/cythonExtensions', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/joop/.local/share/virtualenvs/khinsider-gSzZqK6P/lib/python3.8/site-packages'] This is the template code: <a href="{% url 'browse' 'a' %}">test</a>. The urls.py path: path('browse/<str:char>/', main.views.browse, name='browse') The settings TEMPLATES config: TEMPLATES = [ { "BACKEND": "django.template.backends.jinja2.Jinja2", "DIRS": ['jinja2'], "APP_DIRS": True, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] I tried all kinda of variations but nothing works. -
Django models & relationship with store products? how to solve relationship?
I have a relationship that makes my website unable to function properly? I have a picture of my debugging situation, do you why it shows the wrong line error? debugging result debugging result 2 from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to='Products/') updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() # to call out the table orderitem in reverse all total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) … -
Django/Ubuntu: Error 1045, "Access denied for user 'www-data'@'localhost' (using password: YES)"
I am trying to test out a Log-In page for a Django site hosted publicly on Apache2 by logging in remotely. However when entering any credentials to test I get the following error: [1045, "Access denied for user 'www-data'@'localhost' (using password: YES)"] I am assuming that this means the www-data Apache2 default user can't access my MySQL table? What would be the best way to allow access safely? -
React working on local machine but not on other local network machine
I am hosting a reactjs project on port 3000 as front end and django project on port 8000 as backend on the same machine. So when rending, reactjs will get data by calling django APIs. I (thought I) had correctly setup CORS headers in Django settings. Both http://localhost:3000/ and http://192.168.86.21:3000/ are working on my local machine. 192.168.86.21 is my LAN IP. But when I access http://192.168.86.21:3000/ on another machine or tablet in my LAN. Only static files are rendered. I inspect the Chrome it shows: " Access to fetch at '..django_ip_port...' from origin '..my_ip_port..' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. " It's really weird.