Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSONFIeld(null=True): Is allowing null bad practice?
It's my first time working with Django's JSON fields. When going through examples I usually see the field implementations that set the default to an empty object. However, for my purposes, I'd prefer to allow the field to be None as well. Since all the examples set a default, I'm not sure if allowing null will yield any negative consequences I'm unaware of currently. -
this error apears when i try to run this command django-admin.py makemessage -l ar [closed]
this error appears when I try to run this commanddjango-admin.py makemessage -l ar and it opens django-admin.py file and here is what is in it any ideas? -
DoesNotExist at /cafelist/1
I'm making website using Python Framework of 'Django'. I have some problems with Django about post number. when I visit the website https://tutorialproject-ggurf.run.goorm.io/cafelist/1, I receive this message: DoesNotExist at /cafelist/1 Cafe matching query does not exist. settings.py contains: """ Django settings for tutorialdjango project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # 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 = 'si#o7ysrm956&&)&*q0t6uqr^tx$6(_uj85zzhm*rqy4wyzvd5' # 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', 'main', ] 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 = 'tutorialdjango.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 = 'tutorialdjango.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / … -
Issue with POST email, returning to same page, templates and httpresponse
First of all, I only started using Django a week ago... so pretty new :). I have a one page website. At the bottom there is a contact form. I am using different components for the website, so for the contact form I have 'contact.html' which is loaded into index.html via {& include ... &}. When someone sends a message via contact form, after click send, the user returns to the same page but with a thank you message instead of the contact form (see screenshot). The issue is that I need to 'kill' the process going on underneath because if I reload the page a message pops and if I resubmit, email gets resend again (see screenshot). I have had a look at httpresponse but I am unsure how to replicate the same process. Anyone could help? This is a screenshot of contact.html and views.py -
unable to access models in Django Application
When i try to run following query in the shell i gets following error from flights.models import * Traceback (most recent call last): File "<console>", line 1, in <module> ModuleNotFoundError: No module named 'flights How should I access my models inside flights app. why I get error No module flights when i have clearly flights app -
Django TestCase: duplicate database on fixture loading
Context I just arrived on someone's Django project and I encounter a behavior I never experienced before. It has been a one man project for a year and a half now and the app became both quite complexe; like, a lot of dependencies and custom modules Usually, I create a FIXTURE_DIRS in settings.py and it allows me to simply load fixtures while I run my tests: class OnboardedViewTest(TestCase): fixtures = ["users.yaml", "surveys.yaml", "users_survey.yaml"] cbv = OnboardedView() def test_non_onboarded_users_fail_test_func(self): some_testing In the context of this application, it raises the following exception AssertionError: Problem installing fixture '/app/tests/fixtures/users.yaml': Database queries to 'userdata' are not allowed in this test. Add 'userdata' to tests.test_some_app.OnboardedViewTest.databases to ensure proper test isolation and silence this failure. Ok then, what if I explicitly add this userdata database (and the other named default) to this test class ? class OnboardedViewTest(TestCase): fixtures = ["users.yaml", "surveys.yaml", "users_survey.yaml"] cbv = OnboardedView() databases = ["default", "userdata"] def test_non_onboarded_users_fail_test_func(self): some_testing Error I'm then getting a psycopg2.errors.DuplicateDatabase Creating test database for alias 'userdata'... Got an error creating the test database: database "test_some_app" already exists Type 'yes' if you would like to try deleting the test database 'test_some_app', or 'no' to cancel: Traceback (most recent call last): … -
Popup does not open when clicking on marker safari
I am showing position from django model like marker with popup: my view file <script> const MAP_KEY = "{{ MAP_KEY }}"; const added_place_json = JSON.parse('{{ added_place_json | escapejs}}'); </script> my js file for (const place of added_place_json){ L.marker([place.fields.lat, place.fields.long]).bindPopup( `<div class="card" style="width: 15rem;">\n` + ` <h6 class="card-header">Name place:<br>${place.fields.name}</h6>\n` + ` <div class="card-body">\n` + ` <p class="card-text" style="overflow: scroll">Place comment:<br>${place.fields.comment}</p>\n` + ` </div>\n` + `</div>` ).addTo(map) }; This works well on google chrome, but it doesn't work on safari. When I click on the marker in safari nothing happens -
In my Django app, no pictures display on screen
Hi, there. I created CRUD posting app which can upload multiple pictures optionally before. And I tried enter post detail page, text contents, but no pictures have been shown on a display. Here are some parts of my python code which are related with this issue. models.py class Post(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) text = models.TextField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Picture(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, default="", null=True) picture = models.BinaryField(null=True, editable=True) content_type = models.CharField(max_length=256, null=True, help_text='The MIMEType of the file') owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post_detail.html <style> .picture_wrap{ display: flex; flex-direction: column; } </style> <h1>{{ post.title }}</h1> {% if picture.content_type %} {% for picture in picture_list %} <div id="picture_wrap" class="picture_wrap"> <img style="max-width:50%;" src="{% url 'posts:post_picture' picture.id %}" onclick="document.getElementById('overlay').style.display = 'block';"> </div> {% endfor %} {% endif %} <p> {{ post.text|linebreaks }} </p> views.py class PostDetailView(OwnerDetailView): model = Post template_name = 'posts/post_detail.html' def get(self, request, pk): x = Post.objects.get(id=pk) pl = Picture.objects.filter(post=x) context = { 'post' : x, 'picture_list' : pl } return render(request, self.template_name, context) Somebody...Please do me some guides on this issue... -
CORS Problem with Caddy Spring and Django Websocket
Hi i have a CORS Problem with my Production environment all dockerized Caddyfile starfinder.domain.com { encode gzip zstd root * /var/www @notStatic { not path /static/* /media/* } reverse_proxy @notStatic starfinder-web:8000 file_server } messages.domain.com { reverse_proxy starfinder-messages:8080 header Access-Control-Allow-Credentials "true" header Access-Control-Allow-Origin https://starfinder.domain.com header Access-Control-Allow-Headers "Authorization" } Javascript var socket = new SockJS('https://messages.domain.com/chat'); Spring @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/chat").setAllowedOrigins("https://starfinder.domain.com").withSockJS(); } } Relevant docker-compose.yml version: "3.7" services: caddy: image: caddy:2.2.1 restart: unless-stopped ports: - "80:80" - "443:443" volumes: - /home/dennis/caddy/Caddyfile:/etc/caddy/Caddyfile - /home/dennis/caddy/caddy_config:/config - caddy_data:/data - /var/www:/var/www starfinder-web: build: ./starfinder command: gunicorn penandpaper.wsgi -b 0.0.0.0:8000 volumes: - ./starfinder/:/usr/src/app/ ports: - 8001:8000 volumes: - /var/www:/var/www starfinder-websocket: build: ./websocket ports: - 8080:8080 entrypoint: java -jar /var/www/starfinder-websocket-1.0-SNAPSHOT.jar When I tried the following: replacing urls (Dockerlike) with starfinder-web:8000 replacing urls with domain.com replacing urls with starfinder.domain.com All resulted in a Access to XMLHttpRequest at 'https://messages.domain.com/chat/info?t=1608371877132' from origin 'https://starfinder.domain.com' has been blocked by CORS policy With the current setup i don't get an explicit error but websocket loses connection immediately and has a 502 Status Code. Chrome Console: Opening Web Socket... abstract-xhr.js:132 GET https://messages.domain.com/chat/info?t=1608373262623 502 Whoops! Lost connection … -
Django save multiple versions of a Image within a class
I have the following function where the avatar the user has uploaded get's converted in two versions (smaller and larger version). Instead of writing this function multiple times for multiple fields of multiple models I would like to reimplement this as a class that I can reuse This is my function: def avatar_tamper(self): if self.avatar: if not (self.avatar_tn and os.path.exists(self.avatar_tn.path)): image = Image.open(self.avatar) outputIoStream = BytesIO() outputIoStream_tn = BytesIO() baseheight = 500 baseheight_tn = 175 hpercent = baseheight / image.size[1] hpercent_tn = baseheight_tn / image.size[1] wsize = int(image.size[0] * hpercent) wsize_tn = int(image.size[0] * hpercent_tn) imageTemproaryResized = image.resize((wsize, baseheight)) imageTemproaryResized_tn = image.resize((wsize_tn, baseheight_tn)) imageTemproaryResized.save(outputIoStream, format='PNG') imageTemproaryResized_tn.save(outputIoStream_tn, format='PNG') outputIoStream.seek(0) self.avatar = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.avatar.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) outputIoStream.seek(0) self.avatar_tn = InMemoryUploadedFile(outputIoStream_tn, 'ImageField', "%s.png" % self.avatar.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream_tn), None) elif self.avatar_tn: self.avatar_tn.delete() This is how I call the function at models.py save call: def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) avatar_tamper(self) super(User, self).save(*args, **kwargs) return self.user Can smb help? Kind regards -
Django CSS files are missing while deploying using IIS
I need your assistance. I am deploying Django app on Windows Server 2019. And This went perfectly but CSS files are missing. This the path of my application: C:\inetpub\wwwroot\myapp. And the static folder is under myapp. I added virtual directory in IIS manager and it is set as below: in Alias: static in Physical path: C:\inetpub\wwwroot\myapp\static please any assist? -
Release Django view at given time
Attempting to write a competition website which will need to release a page at a given time. I could just deploy it at this time manually but this is really not ideal and cannot find anywhere how to do it automatically. Would it be possible to deploy a view from a given time and then keep it up? If so, how? -
Accessing Django View data fro JavaScript using Fetch Api
I'm trying to get data from Django view using fetch API but the fetch API isn't reaching the Django view. function connect(username) { alert('connect'); let promise = new Promise((resolve, reject) => { // get a token from the back end let data; alert("before append") // data.append('csrfmiddlewaretoken', $('#csrf- helperinput[name="csrfmiddlewaretoken"]').attr('value')); alert("vc") fetch("/videocall/", { method: 'POST', // headers: { // "X-CSRFToken": getCookie("csrftoken"), // "Accept": "application/json", // "Content-Type": "application/json" // }, headers:{ 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax() 'X-CSRFToken': csrftoken, }, //credentials: "same-origin", body: JSON.stringify({'username': username}) }).then(res => res.json()).then(_data => { // join video call alert("Joint") data = _data; return Twilio.Video.connect(data.token); }).then(_room => { alert("room") room = _room; room.participants.forEach(participantConnected); room.on('participantConnected', participantConnected); room.on('participantDisconnected', participantDisconnected); connected = true; updateParticipantCount(); connectChat(data.token, data.conversation_sid); resolve(); }).catch(e => { alert("catch") console.log(e); reject(); }); alert(promise) }); return promise; }; Here's my django view def videocall(request): print("Trying to login") if request.method == "POST": print("Trying to login") It's not even printing trying to login which i printed in django view. I think there's some problem in URL in fetch. I'm new to Django please help me in this regard -
Multiple classes with the same name firing on a single class click
I have the script below to like or unlike a particular post, but the posts are displayed using a for loop in Django so they all have the same class. When an upper like button is clicked, all of the remaining buttons are also clicked which I suspect is due to the jquery. I tried the solution in this thread to add StopPropagation and ImmediatePropagation but it's not working jQuery $(".class").click(); - multiple elements, click event once The Jquery code $('a.like').on('click', function(event){ event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); $.post('{% url "posts:post_like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // toggle link text $('a.like').text(previous_action == 'like' ? 'Unlike' : 'Like'); // update total likes var previous_likes = parseInt($('span.count .total').text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); } } ); }); In the image, all three of the 'like' links would change to unlike when a single one is clicked [![Image of the output][1]][1] [1]: https://i.stack.imgur.com/qXuwz.png -
django remove the `Superuser status`
how to remove the superuser status in creating an admin user in django admin?, i mean for example, i am Staff status and i have a permission to create another user, as a Staff status admin i dont want to see the Superuser status in creating user. please see the picture below from django.contrib import admin from .models import Customer, UnitMasterlist, ProductCategory, Product, Logo, StoreName,Banner,Customer_Cart from import_export import resources from import_export.admin import ImportExportModelAdmin class Customer_CartResource(resources.ModelResource): class Meta: model = Customer_Cart fields = ('id', 'profile', 'products', 'Customer_Checkout_Detail', 'quantity', 'unitmasterlist', 'unitprice', 'discount_percentage' , 'discount_price', 'total_amount', 'created_at','updated_at',) @admin.register(Customer_Cart) class ProductAdmin(ImportExportModelAdmin): list_display = ('id', 'profile', 'products', 'Customer_Checkout_Detail', 'quantity', 'unitmasterlist', 'unitprice', 'discount_percentage', 'discount_price', 'total_amount', 'created_at','updated_at',) ordering = ('id',) list_filter = ("profile", "products") resource_class = Customer_CartResource note that is my all code in my admin.py, please bear with me, i am new in django enter image description here -
How to serialize some nested relational models in django using rest?
I have some django models with different relations to each other (i.e. Many-to-many, Foreinkey). Now, I want to serialize them using djnago-rest. Here's an example of my models and their relations: class CommonFieldsAbstarct(models.Model): name = models.CharField(max_length=30, unique=True) class ServerModel(CommonFieldsAbstarct): server_ip = models.GenericIPAddressField(default='172.17.0.1') server_port = models.IntegerField(default='9001') class SNMPLineModel(CommonFieldsAbstarct): ip_address = models.GenericIPAddressField() port = models.IntegerField(default=161) class SNMPModel(CommonFieldsAbstarct): # target line = models.ForeignKey(SNMPLineModel, on_delete=CASCADE) servers = models.ManyToManyField(ServerModel) class MetaDataModel(models.Model): key = models.CharField(max_length=20) value = models.CharField(max_length=20) snmp_device = models.ForeignKey(SNMPModel, on_delete=CASCADE) Before, I used to use this way to create json manually: def meta_data_json(meta_data): meta_data_list = [] for meta in meta_data: meta_data_list.append({ meta.key: meta.value }) return meta_data_list def server_json(servers): return [{'ip': server.server_ip, 'port': server.server_port} for server in servers] def create_json(): snmp = SNMPModel.objects.filter(name__contains='a-name') return { 'name': snmp.name, 'address': snmp.line.ip_address, 'port': snmp.line.port, 'servers': server_json(snmp.servers.all()), 'meta_data': meta_data_json(MetaDataModel.objects.filter( snmp_device=snmp.pk ) ), 'device_pk': snmp.pk } My Question: Now, how can I create such an above json through django-rest-framework instead? I don't have any problem with many-to-many. In fact, my problem is with their foreignkey(s). And here is what I've done so far: serializers.py from rest_framework import serializers class MetaDataSerializer(serializers.ModelSerializer): class Meta: fields = [ 'id', 'key', 'value', ] model = MetaDataModel class ServerSerializer(serializers.ModelSerializer): class Meta: fields = [ 'id', … -
AttributeError: 'str' object has no attribute 'as_widget'
I am trying to have more control of my Django forms by adding a custom filter from django import template register = template.Library() @register.filter(name='addclass') def addclass(value, arg): return value.as_widget(attrs={'class': arg}) but getting the AttributeError: 'str' object has no attribute 'as_widget' error here is my view def index(request): notes = Note.objects.all() form = NoteForm() if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): form.save() return redirect('keep:index') context = {'notes':notes, 'form':form} return render(request,'Keep/note_form.html',context) def update(request,id): notes = Note.objects.get(id=id) form = NoteForm(instance=notes) if request.method == 'POST': form = NoteForm(request.POST, instance=notes) if form.is_valid(): form.save() return redirect('keep:index') context = {'notes': notes, 'form': form} return render(request,"Keep/update.html",context) def delete(request,id): obj = get_object_or_404(Note,id=id) if request.method == "POST": obj.delete() return redirect('keep:index') return render(request,"Keep/delete.html") PS. Before you throw me links to other similar questions, i want you to know i checked pretty much all the links and none of the solutions worked for me. Most common is this: else: form = UserForm() return render(request, 'register_user.html', {'form': form}) but as you can see, i did exact same thing but that doesn't work -
bootstrap popover with form in data-content working in Django 1.11 and 2.0 but not in Django 2.1-3.1
I have code below and it is working as it should in django 1.11 and after upgrading it works in django 2.0 but for some reason it is not working in higher versions of django starting from 2.1 till 3.1.4. <button type="button" class="btn btn-sm btn-secondary" id="dodaj-poziv-za-clanove-tijela" data-container="body" data-toggle="popover" title="Da li želite da dodate članove tijela u sastanak ?" data-content= "<form method='POST' action='{% url 'poziv_clanovi_dodaj' poziv_id=poziv.id %}'> <button type='submit' class='btn btn-success btn-sm clanovi float-right'>Dodaj</button> {% csrf_token %} </form>" > Dodaj poziv za članove tijela</button> In browser this button looks normal for working django versions 1.11 and 2.0 but in those that are not witch is every version above 2.0 including 2.1,2.2 and 3.0,3.1 it button has "> in it and after submitting i get csrf token error -
Django - [Errno 2] No such file or directory error: when attempting to save an uploaded file to a dynamic url
Models.py: class Enterprise(models.Model): name = models.CharField(max_length = 100) def __str__(self): return f"{self.id}_{self.name}" class Client(models.Model): name = models.CharField(max_length = 100) def __str__(self): return f"{self.id}_{self.name}" class Engagement(models.Model): name = models.CharField(max_length = 100 def __str__(self): return f"{self.id}_{self.name}" class StockCount(models.Model): name = models.CharField(max_length = 100) def __str__(self): return f"{self.name}" class InventoryList(models.Model): UploadedFile = models.FileField(_('Upload Inventory Listing'), upload_to = file_upload_location, validators=[validate_file_extension], max_length = 500) enterprise = models.ForeignKey('Enterprise', on_delete=models.CASCADE, related_name = 'inventorylists') client = models.ForeignKey('Client', on_delete=models.CASCADE, related_name = 'inventorylists') engagement = models.ForeignKey('Engagement', on_delete=models.CASCADE, related_name = 'inventorylists') stockcount = models.ForeignKey('StockCount', on_delete=models.CASCADE, related_name = 'inventorylists') views.py: def upload(request): if request.method == 'POST': form = InventoryListForm(request.POST, request.FILES) if form.is_valid(): # file is saved list = form.save(commit = False) list.enterprise = Enterprise.objects.get(pk = 1) list.client = Client.objects.get(pk = 1) list.engagement = Engagement.objects.get(pk = 1) list.stockcount = StockCount.objects.get(pk = 1) list.save() return HttpResponse(f'You have just made a post request - {list.id}') else: return render(request, "observe/upload.html", {"form": form}) else: return render(request, "observe/upload.html", {"form": InventoryListForm()}) forms.py: class InventoryListForm(ModelForm): class Meta: model = InventoryList exclude = ['enterprise', 'client', 'engagement', 'stockcount'] def __init__(self, *args, **kwargs): super(InventoryListForm, self).__init__(*args, **kwargs) upload_to callable function: def file_upload_location(instance, filename): ext = filename.split('.')[-1] # return f"{instance.enterprise}/{instance.client}/{instance.engagement}/{instance.stockcount}/{filename}" # return f"{filename}" FileType = '\\Inventory List' name = str(filename) path = os.path.join(str(instance.enterprise), str(instance.client), str(instance.engagement), … -
Twitter OAuth page asks user to re-authorize app, even though they've done it before
Say a user logged into Twitter comes to my site. Assume they have authorized my app. If I send that user to the OAuth authorization page, it keeps asking the user to (re-)authorize my app, even though they've done it a million times. Is there a way to skip the authorization process if they've already done it? Here's my code: #views.py def oauth(request): auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth_url = auth.get_authorization_url() request.session['request_token'] = auth.request_token return redirect(auth_url) get_authorization_url() seems to send my user to a re-authorization page no matter how many times they've authorized my app. I need it to skip this and redirect to my callback URL if they've already granted permissions. Anyone has any tips? -
Upload multiple images for a single product in django
I have created some nice models in models.py for uploading multiple images in single products, for different products. The good thing it uses one image model for all products. Now i'm failing to create a perfect forms.py. May someone help me please. from django.db import models from django.utils.safestring import mark_safe from ckeditor_uploader.fields import RichTextUploadingField from mptt.fields import TreeForeignKey from mptt.models import MPTTModel from django.urls import reverse from django import forms from django.forms import ModelForm, Form, TextInput, Textarea def get_upload_path(instance, filename): model = instance.album.model.__class__._meta name = model.verbose_name_plural.replace(' ', '_') return f'{name}/images/{filename}' class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lt=100, length_lt=100) class Image(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to=get_upload_path) default = models.BooleanField(default=False) width = models.FloatField(default=100) length = models.FloatField(default=100) album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE) class Product(models.Model): title = models.CharField(max_length=20) album = models.OneToOneField(ImageAlbum, related_name='model', on_delete=models.CASCADE) class Vehicle(Product): STATUS = ( ('True', 'True'), ('False', 'False'), ) brand = models.CharField(max_length=30) price = models.DecimalField(max_digits=8, decimal_places=2) mileage = models.IntegerField() ... -
sqlite3 is not recognized as an external or internal command
I'm creating a poll app using django. When I try to access the database as shown in the video I get error: 'sqlite3' is not recognized as an internal or external command, operable program or batch file. I've already manually installed and set the path in environment variables but still its showing error. Thanks for the help. -
JavaScript Uncaught TypeError: Cannot read property 'style' of null: Button Onclick makes html disappear
In a django project, I've set up a JavaScript function to select/block certain pages. I have another JavaScript function for the pages that are being loaded. This function has an onclick event listener that submits text to a form field. The problem I'm having is that when I click a button to add text to a form field, the entire page disappears. Both functions are in a static file called "main.js" The exact error message showing in the console is... Uncaught TypeError: Cannot read property 'style' of null at showPage (players:6382) at HTMLButtonElement.button.onclick (players:6388) Here's the function controlling showing/blocking of individual pages. function showPage(page) { document.querySelectorAll('tbody').forEach(tbody => {tbody.style.display = 'none';}) document.querySelector(`#${page}`).style.display = 'table-row-group'; ---(This line in error message) } document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('button').forEach(button => { button.onclick = function() { showPage(this.dataset.page); ---(This line in error message) } }); }); Here's an example from the html template of a button targeted by this function. <button class="posbutton" data-page="page1">QB</button> This is the function that submits text to a form field. function myFunction(txt) { var myTxt = txt; if (txt.includes('QB')) { document.getElementById("QB_name").value = myTxt; } else if (txt.includes('RB')) { document.getElementById("RB_name").value = myTxt; } else if (txt.includes('WR')) { document.getElementById("WR_name").value = myTxt; } else if (txt.includes('TE')) { … -
test failed at `create_superuser`
I'm doing a tutorial and following the code as is, but my test failed from django.test import Client, TestCase from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@email.com', password='password123' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email='test@email.com', password='password123', name='Test user full name' ) def test_users_listed(self): """Test that users are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) Test error: ERROR: test_users_listed (core.tests.test_admin.AdminSiteTests) Test that users are listed on user page ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 9, in setUp self.admin_user = get_user_model().objects.create_superuser(email='admin@email.com', password='password123') AttributeError: 'UserManager' object has no attribute 'create_superuser' I'm using the following versions: Django>=3.1.4,<3.2.0 djangorestframework==3.12.2,<3.13.0 flake8>=3.6.0,<3.7.0 -
Calculation In Multiple Html Tables on a single page
Hey i want to Perform Calculations At the End of Every Table(on a footer) in a single page. Suppose i have two tables and i want to perform calculations on a Total Amount Column. How Can i do That. Using Jquery and Javascript. There Might Be More then Two Table so please be sure it works on multiple tables on a single page. These Values in HTML Table are come using (For Loop) in Django. This Image Contains 2 HTML Tables and i want calculations on both table on a total amount column.