Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sqlite3.OperationalError: no such table: django_site__old
I'm trying to make a webpage using python and mezzanine as its cms. but I got this error after successfully creating Superuser: Superuser created successfully. Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\db\backends\utils.py", line 62, in execute return self.cursor.execute(sql) File "C:\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 326, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such table: django_site__old The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\annie\Documents\DMCproject\manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python39\lib\site-packages\mezzanine\core\management\commands\createdb.py", line 61, in handle func() File "C:\Python39\lib\site-packages\mezzanine\core\management\commands\createdb.py", line 109, in create_pages call_command("loaddata", "mezzanine_required.json") File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python39\lib\site-packages\django\core\management\commands\loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "C:\Python39\lib\site-packages\django\core\management\commands\loaddata.py", line 115, in loaddata connection.check_constraints(table_names=table_names) File "C:\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 276, in check_constraints cursor.execute( File "C:\Python39\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Python39\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Python39\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Python39\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Python39\lib\site-packages\django\db\backends\utils.py", … -
django allauth for confirm by phone
I want after signup page , user redirect to confirm with phone page .. How handle it in with allauth .. it redirect after signup page to confirm mail page in any case or redirect to page /account/inactive/ In the event that is-active default false -
Django Rest Framework - Create ForeignKey lookup fields
I'm trying to Create LikeSong which have Related Field with Song model In need to pass slug instead of pk class LikedSongSerializer(serializers.ModelSerializer): song = serializers.SlugRelatedField( queryset=Song.objects.all(), slug_field='slug' ) class Meta: model = LikedSong fields = [ 'song', 'media_type' ] def create(self, validated_data): liked = LikedSong.objects.get_or_create(user=self.context['request'].user, **validated_data) return liked but i got this error AttributeError: Got AttributeError when attempting to get a value for field `song` on serializer `LikedSongSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the tuple instance. Original exception text was: 'tuple' object has no attribute 'song'. [15/Jan/2021 21:24:00] "POST /api/music/like_song/ HTTP/1.1" 500 20927 -
Queries on multiple fields, each with a custom method, with django-filter
I have this filter: class MsTuneFilter(django_filters.FilterSet): def all_titles(self, queryset, name, value): return MsTune.objects.filter( Q(name__icontains=value) | Q(title__icontains=value) | Q(alt_title__icontains=value) ) def ind_1(self, queryset, name, value): return MsTune.objects.filter( Q(index_standard_1__startswith=value) | Q(index_gore_1__startswith=value) | Q(alt_index_gore_1__startswith=value) | Q(alt_index_standard_1__startswith=value) ) title = django_filters.CharFilter(method='all_titles', label="All title fields") index_standard_1 = django_filters.CharFilter(method='ind_1', label="Index 1") class Meta: model = MsTune fields = ['index_standard_1', 'title', ....] It all works well when I'm making queries which do not involve both 'title' and 'index_standard_1'. Nevertheless, if I'm searching for something with a specific title AND with a specific index, either the index search or the title is ignored, i.e. the query returns all the indexes or all the titles, ignoring a parameter of my search. What am I overlooking? -
"Reverse query name" in django model's use case
I need to know where the "Reverse query name" show's it self in django modeling(most common use case). -
How can i pass a dynamic url to another url
Im new to Django. So, my problem is that i want my dynamic url like this: website.com/password/2332 "2332" is the dynamic part to pass to this: website.com/password/2332/revealpassword urls.py: path("password/<str:link>", views.password), path("password/<str:link>/revealpassword", views.reveal_password, name="reveal_password") html file: <a href="{% url 'password:reveal_password' link %}">Reveal</a> the Problem is at the "link". How can i pass the stuff that is in the url to the new url -
Django forms checkbox required even if require:false in form attrs
how can i make my checkbox not required using django forms? my forms.py invoice = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class':'checkboxInvoice','required': 'False'})) my models.py invoice = models.BooleanField(default=False, blank=True, null=True) -
Django is having trouble finding static folder/css
I have a Django project in which I am getting a 404 on the CSS file. In my app (the only one I have) I have a template directory with a few different HTML files. I also have a static directory (found in the same directory as app) I have a CSS file saved as such /static/css/main.css/. See below for my settings.py file which sets the static folder: import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '5&-12%c=er64$=$0w6*0sc__s8k_4ldiq(mkowlmqdatn!!g!8' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'feed' ] 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 = 'kahlo.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 = 'kahlo.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } … -
Django restframework and javascript - one of two identical calls not working
I am pretty puzzled about this error, and I cannot find the solution. I have two nearly identical models, which both work in the browser, but one of them does not work when accessed via JS: models: class Ad(models.Model): name = models.CharField("name", max_length = 32, unique = True) file = models.ImageField(upload_to = "ads") class Product(models.Model): name = models.CharField("name", max_length = 128) price = models.FloatField("price", null = True, blank = True) user = models.ForeignKey(User, on_delete = models.CASCADE) views: class AdDataViewSet(LoginRequiredMixin, viewsets.ViewSet): login_url = '/login/' def list(self, request): query = Ad.objects.all() try: results = AdSerializer(data = query, many = True) results.is_valid() return Response(data = results.data, status = status.HTTP_200_OK) except Exception as e: return Response(data = str(e), status = status.HTTP_400_BAD_REQUEST) class ProductDataViewSet(LoginRequiredMixin, viewsets.ViewSet): login_url = '/login/' def list(self, request): query = Product.objects.all() try: results = ProductSerializer(data = query, many = True) results.is_valid() return Response(data = results.data, status = status.HTTP_200_OK) except Exception as e: return Response(data = str(e), status = status.HTTP_400_BAD_REQUEST) serializers: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["pk", "name", "price"] class AdSerializer(serializers.ModelSerializer): class Meta: model = Ad fields = ["pk", "name", "file"] urls: router = routers.DefaultRouter() router.register(r'products', views.ProductDataViewSet, basename = "products") router.register(r'ads', views.AdDataViewSet, basename = "ads") urlpatterns = [ path("", … -
Django Forms access fields using ajax or fetch
is there any way to access or "GET" Django forms fields using fetch or ajax? I am trying to sending the form using JsonResponse but know how can I do that? -
django.db.migrations.exceptions.NodeNotFoundError: Migration accounts.0001_initial dependencies reference nonexistent parent node
I'm trying to deploy my project on heroku ,i'm using django 3.1 and i'm unable to do that. I'm getting error due to migrations. Please i humble request you to give some time to this question to resolve this problem. Whenever i run the command heroku run python manage.py migrate ,it gives following traceback. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 255, in build_graph self.graph.validate_consistency() File "/app/.heroku/python/lib/python3.6/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 "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/app/.heroku/python/lib/python3.6/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 accounts.0001_initial dependencies reference nonexistent parent node ('auth', '0023_remove_user_current_balance') migration dependency dependencies = … -
React build shows white page with Django
I am trying to load React build files in a Django template (serving the React build files via Django static files). I’ve had success using this approach in the past with other Django templates, but with this particular case, the React app is not attaching to my div in the Django template. The React app is created using create_react_app with minimal changes. My src/index.js file: (only changed the root element) import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('chat-root') ); reportWebVitals(); My public/index.html file: (only changed the root element) <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" … -
Best way to store/model game data on a Django website?
Please allow me to set up the environment for my question: On my website, users register for an account and then go to the game page Once 5 players load in to the game page, a new game starts. The game works as follows: Players guess numbers until they find the "magic number", which is a random number from 1-100 Once 3 players have guessed the magic number correctly, the other 2 are declared the losers and kicked from the page My question is as follows: what is the best way to store individual game information? In order for the game to operate correctly, the website needs to somehow hold information on the game; specifically, a counter that increments every time a player guesses the magic number correctly. Points of consideration: I would like to make it so multiple games could be going on at once (website.com/game could have multiple gaming sessions going on at once on it), so the solution should not inhibit that. I am running my website with Django, along with HTML/CSS/JavaScript This is (probably obviously) a simplified version of the game I am implementing online. In reality, the solution would be able to hold multiple dynamic … -
Setting up a custom workflow for the edit model form view
Context I have a model, let's call it Application. class Application(models.Model): # various fields here status = status = models.CharField( max_length=100, choices=APPLICATION_STATUSES, default=PENDING_STATUS[0], ) assigned_operator = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, editable=True, null=True, ) This model has some fields, but the ones we care here are the status, which is simply a choice field, and the assigned_operator field, which defines a 1-1 relationship with a User instance. This model also has its corresponding ApplicationAdmin view defined. Description The requirement is that when trying to edit an Application, from the admin view, the default workflow, where you make whatever changes you want and then simply save the form, should be replaced with the following workflow: The application form is readonly unless the user is the assigned_operator of the application, in which case the application is editable. When the user is not the application's assigned_operator the actions at the bottom will be 1 button: "Assign to myself" - When clicked the Application model is updated to reference the current user as its assigned_operator and the page refreshes When the user is the application's assigned_operator the actions at the bottom will be 3 buttons: "Save changes" - Does what default "Save" button does "Reject" - … -
Queries on multiple fields, each with a custom method, with django-filter
I have this filter: class MsTuneFilter(django_filters.FilterSet): def all_titles(self, queryset, name, value): return MsTune.objects.filter( Q(name__icontains=value) | Q(title__icontains=value) | Q(alt_title__icontains=value) ) def ind_1(self, queryset, name, value): return MsTune.objects.filter( Q(index_standard_1__startswith=value) | Q(index_gore_1__startswith=value) | Q(alt_index_gore_1__startswith=value) | Q(alt_index_standard_1__startswith=value) ) title = django_filters.CharFilter(method='all_titles', label="All title fields") index_standard_1 = django_filters.CharFilter(method='ind_1', label="Index 1") class Meta: model = MsTune fields = ['index_standard_1', 'title', ....] It all works well when I'm making queries which do not involve both 'title' and 'index_standard_1'. Nevertheless, if I'm searching for something with a specific title AND with a specific index, the index search is ignored, i.e. the query returns all the indexes, ignoring my search. What am I overlooking? -
name 'serializer' is not defined
I'm trying to build an API on Django REST framework but when I try to use the POST method I get this error: name 'serializer' is not defined This is the API view: class apiOverview(APIView): serializer_class = serializers.EmailsSerializer def get(self, request, format=None): an_apiview = [ ] return Response({'message':'Hello!', 'an_apiview': an_apiview}) def post(self, request): serializer_class = self.serializer_class(data=request.data) if serializer.is_valid(): url = serializer.validated_data.get('url') message = f'The url is {url}' return Response({'message': message}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The error is in this line particularly when trying to validate: if serializer.is_valid(): url = serializer.validated_data.get('url') message = f'The url is {url}' return Response({'message': message}) All apps are correctly installed. -
Error trying to attach an image to an email with DRF
I'm trying to attach an image in a email that i send in a task with celery Im working with Django Rest Framework This are my task.py from celery import shared_task from email.mime.image import MIMEImage from django.contrib.staticfiles import finders from django.template.loader import get_template from django.core.mail import EmailMultiAlternatives @shared_task def send_new_dispatch_guide_email_task(**kwargs): subject = kwargs['subject'] from_email = 'contact@ecmat.cl' to = kwargs['email'] email_context = { 'name': kwargs['name'], 'button_msg': kwargs['button_msg'], 'button_link': kwargs['button_link'], 'subject': subject, 'text': kwargs['text'], 'entity_in_question': kwargs['entity_in_question'], 'after_text': kwargs['after_text'], 'purchase_order_code': kwargs['purchase_order_code'], 'dispatch_guide_code': kwargs['dispatch_guide_code'], 'provider_name': kwargs['provider_name'], 'withdrawal_address': kwargs['withdrawal_address'], 'destination_address': kwargs['destination_address'], 'items_quantity': kwargs['items_quantity'], 'withdrawal_date': kwargs['withdrawal_date'], 'withdrawal_time': kwargs['withdrawal_time'], 'goto_link': kwargs['goto_link'] } text_content = "" html = get_template('dispatch_guide.html') html_content = html.render(email_context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach(logo_data(file_name='linkedin.png', image_id='1')) msg.attach(logo_data(file_name='twitter.png', image_id='2')) msg.attach(logo_data(file_name='youtube.png', image_id='3')) msg.attach(logo_data(file_name='image_2.png', image_id='4')) msg.attach(logo_data(file_name='image_5.png', image_id='5')) msg.attach(logo_data(file_name='logoemail_2.png', image_id='6')) msg.send() return None @shared_task def send_new_dispatch_guide_email_provider_task(**kwargs): subject = kwargs['subject'] from_email = 'contact@ecmat.cl' to = kwargs['email'] email_context = { 'name': kwargs['name'], 'subject': subject, 'text': kwargs['text'], 'entity_in_question': kwargs['entity_in_question'], 'after_text': kwargs['after_text'], 'purchase_order_code': kwargs['purchase_order_code'], 'dispatch_guide_code': kwargs['dispatch_guide_code'], 'withdrawal_address': kwargs['withdrawal_address'], 'destination_address': kwargs['destination_address'], 'items_quantity': kwargs['items_quantity'], 'withdrawal_date': kwargs['withdrawal_date'], 'withdrawal_time': kwargs['withdrawal_time'] } text_content = "" html = get_template('dispatch_guide_provider.html') html_content = html.render(email_context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach(logo_data(file_name='linkedin.png', image_id='1')) msg.attach(logo_data(file_name='twitter.png', image_id='2')) msg.attach(logo_data(file_name='youtube.png', image_id='3')) msg.attach(logo_data(file_name='image_2.png', image_id='4')) msg.attach(logo_data(file_name='image_5.png', image_id='5')) msg.attach(logo_data(file_name='logoemail_2.png', image_id='6')) msg.send() return None def … -
How to create reusable components for UI in Django
I am building a project in Django which has 5 different applications inside it. Some applications are falling under same pattern and some are not. Can I create a UI components using bootstrap on the top of all these applications to reuse over the entire project. Any help would be appreciated.. Thanks in advance -
Django register form
so, I made the registration page with django and it doesn't show the form register.html <form method="post"> {{ form.as_table }} {% csrf_token %} <input type='submit' value="Register"> </form> and this is the views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserCreationForm() return render(request, 'register.html', { 'form ' : form}) def login(request): return render(request, 'login.html') And all it shows is the register button -
pip installing does not install to virtualenv
I'm very new to all of this, so bear with me. I started, and activated, a virtual environment. But when I pip install anything, it installs to the computer, not the the virtual env. I'm on a Mac, trying to build a Django website. Example: With the virtual machine activated. I type: python -m pip install Django Then I can deactivate the virtual env, and type: pip freeze And it will list out the freshly installed version of Django. Any clue as to why this is happening? -
Django Template Broke When Model Field Type Changed From CharField to ForeignKey
I had a set of templates that all start with the same object_list. The first (reviews_list) displays every item in the object list. The rest of them display a subset of the items based on an attribute: {% if review.library == "Movies" %}. This worked fine until I changed the Review model. Where library used to be a CharField, it's now a ForeignKey, though the name of the field did not change. reviews_list still renders properly but all of the other templates are showing empty. I have tried both of the following and everything's still empty. On library's pk as a string: {% if review.library == "1" %} On library's pk as an int: {% if review.library == 1 %} I had wiped the database before doing the migration, then repopulated, so there shouldn't be any weird data issues. The template is pretty short, so pasting it below. How can I get items to display in the template based on the value of a field that's an fk? Thanks {% extends 'base.html' %} {% block title %}TV Reviews{% endblock title %} {% block content %} <h1 class="jumbotron-fluid">List Of TV Reviews</h1> {% for review in object_list %} {% if review.library == … -
Why django changes timezone while creating Post Model?
def test_post_order_positioning_by_date(self): Post.objects.create( body="test", date_added="2020-12-31 18:51:19.959463+01:00", author=self.user, uniqueID="61672dba-0d36-43b1-b36a-bbd0a3d317b5", image="" ) post = Post.objects.get(uniqueID="61672dba-0d36-43b1-b36a-bbd0a3d317b5") print(post.date_added) This function when printig post.date_added show code below: 2020-12-31 17:51:19.959463+00:00 Here is the model code: class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='author') body = models.TextField(max_length=500, default="") date_added = models.DateTimeField(auto_now_add=False) image = models.ImageField(default=None, upload_to="posts/") uniqueID = models.UUIDField(unique=True, max_length=255, primary_key=True) def __str__(self): return str(self.uniqueID) def pre_save_post_receiver(sender, instance, **kwargs): print(sender, instance) pre_save.connect(pre_save_post_receiver, sender=Post) Any idea why this happens? I tried overide_settings and changins timezone for this function and django module timezone with timezone.localtime(timezone.now()) but both of these attempts failed. -
Python: Matplotlib Animation in Django
This is more a question of asking for guidance than to solve a specific problem. I am trying to display a live graph constructed with matplotlib's animation feature in Django, however I am stuck and do not know how to approach this. If someone has advice, it would be greatly appreciated. -
Ajax Validation stops after first use with model django form
I have a model form in django that I am rendering on the front end and validating with Ajax. but the Validation works only once which is the first time I visit the page. If I submit the form again, I don't get any response from Ajax. Here is the code: $(document).ready(function(e) { $('#new_order').submit(function(e) { // On form submit event $.ajax({ // create an AJAX call... data: $(this).serialize(), // get the form data type: $(this).attr('method'), // GET or POST url: $(this).attr('action'), // the file to call success: function(response) { // on success.. if (response.success) { document.getElementById("new_order").reset(); $('.message').html(response.success); setTimeout(function(){ $('.message').hide() }, 1000) } else if(response.err_code == 400){ for(var key in response.error){ document.getElementById("new_order").reset(); $('.message').html(response.error[key][0]); setTimeout(function(){ $('.message').hide() }, 1000) }} }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); } }); return false; }); e.preventDefault(); }); While the views.py is this: @login_required def counter(request): message = {} user = request.user if user.user_type != 'counter_staff' and user.user_type != 'manager': message = 'You are not authorized to view this page' return render(request, 'counters.html', {'message' : message}) else: form = NewOrderForm if request.method == 'POST': form = NewOrderForm(request.POST) if form.is_valid(): new_order = form.save(commit=False) new_order.taken_by= user new_order.order_date_time = datetime.now() new_order.save() message['success'] = 'Order Taken Successfully' … -
Display Django Foreign key on webpage
I have three models. class Supplier(models.Model): name = models.CharField(max_length=200, null=True) class Order(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True, blank=True) on_order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=True) I can display a table of all the products of a given order. However, I cannot seem to render the name of that supplier on the html page like <h4> Supplier: {{order.supplier}}</h4> this is the view: def PurchaseOrder(request, pk_order): orders = Order.objects.get(id=pk_order) products = Product.objects.filter( on_order_id=pk_order).prefetch_related('on_order') total_products = products.count() supplier = Product.objects.filter(on_order_id=pk_order).prefetch_related('on_order') context = { 'supplier': supplier, 'products': products, 'orders': orders, 'total_products': total_products, } return render(request, 'crmapp/purchase_order.html', context) I've tried so hard... and didn't get very far. Please help...