Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render a template within def get_object instead of raise raise Http404("Does not exist") in class based view
In the get_object method of class views, can I direct the user to a template instead of returning the object if an if statement fails? Currently raise Http404("Some message.") works good but it doesn't look nice, I want to use my own template. I'm trying to do this but with templates: def get_object(self): product = Product.objects.get(slug=self.kwargs.get('slug')) if product.deleted == False: if product.out_of_stock == False: return product else: raise Http404("This product is sold out.") # return reverse("404-error", kwargs={"error": "sold-out"}) # return render(request, "custom_404.html", {"error": "sold_out"}) else: raise Http404("This product is no longer available.") # return reverse("404-error", kwargs={"error": "deleted"}) # return render(request, "custom_404.html", {"error": "deleted"}) My main goal is to just avoid getting the object. I know I can perform the if statement in the get_context_data method, however I wasn't sure for objects containing sensitive data if there would be any way for a user to access it once it's in the get_object, so I just wanted to avoid getting the object altogether if the condition fails and display a template to the user. -
Django extend base.html along with its context
I've passed a variable to base.html from my views.py file in a context. I've extended this base.html to another several templates. The variable is only visible in the base.html and not any other extended template. It does work if I pass the same context to each templates views.py file. As I extended the base, shouldn't it also extend the variable? Is there any other way to get this working, or am I missing something? -
Student registrations system using django
I am developing a student registrations system using django. Task: Teacher will pay x amount for x students. (Completed) So After payment the teacher will receive a unique url to register their students. (Completed) The URL will be valid for 7 days. (Completed) Apply restrictions for x students for that url. ( Pending ) Example: If a teacher paid for 2 leaders and got the unique url. But he can add 1000 students with that url within 7 days. So my question is how to restrict the registration to 2 students only. Any help?? Thanks -
How to make the FileField downloadable for users that has permission to download in Django?
I am making a simple e-commerce website that sells my own software in a zip file, how to make a download link for the file that can only be accessed with the user who purchased the product? Any advice on how should i manage my product files? This is my Products model class Product(models.Model): name = models.CharField(max_length=150) price = models.FloatField() description = models.CharField(max_length=255, blank=True) product_type = models.CharField(max_length=20, default='tool') date_created = models.DateField(auto_now_add=True) date_updated = models.DateField(auto_now=True) image = models.ImageField(null=True, blank=True) -
Certain models not showing up in django 4 admin despite being registered
Using django 4.0.3 and the restframework. I have serval models registered in django admin: @admin.register(models.Drug) class DrugAdmin(admin.ModelAdmin): list_display = ('apl_label', 'name', 'drug_class', 'atc_code', ) @admin.register(models.Organism) class OrganismAdmin(admin.ModelAdmin): list_display = ('apl_label', 'long_name', 'short_name', 'genus', 'flagged', 'notes') .... For some reason, some o fthe models are not showing up in the admin view. In this example, Organism shows up, but Drug is hidden. I can go to http://localhost:8000/admin/api/drug/ and access this admin page, but it is not listed under http://localhost:8000/admin/. There is no error message either. I did run makemigrations and migrate. Permissions are only set globally in settings.py: ... 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], It is always the same models not showing up. I tried deleting the database and creating everything from scratch. No luck. Why does Django decide to not show certain models? -
How to take user input and let the user upload / submit a .json file to a Docker image
So I am pretty new to Docker but already really liking its functionalities and container / block mentality. Long story short, lately I've been selling some scripts but I kept running into the same problem. My clients were usually on Windows and I would have to spend a lot of time setting things up for them, broken packages in Windows, annoying TeamViewer sessions etc. Now here the beauty that is Docker comes in which allows me to ship ready-made images. Just fantastic! Given my newbie status in Docker I am having some trouble doing certain things. I am currently reading the book "Docker in Action" and loving it but something like my problem has not (yet) been covered there. Now I have the following code (this is not everything but the part I am struggling with): def broadcast_transaction(sender, private_key, amount, contract): # Get the nonce. Prevents one from sending the transaction twice nonce = web3.eth.getTransactionCount(sender) to_address = web3.toChecksumAddress(contract) # Build a transaction in a dictionary tx = { 'nonce': nonce, 'to': to_address, 'value': web3.toWei(amount, 'gwei'), 'gas': 300000, 'gasPrice': web3.toWei('5', 'gwei'), 'chainId': 0x38 } # sign the transaction signed_tx = web3.eth.account.sign_transaction(tx, private_key) # send transaction tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction) # get transaction … -
django pwa error = cannot import name 'url' from 'django.conf.urls
hello i am using django 4.0.3 and i try to use django-pwa in my project but when i runserver i ge this error i followed this tutorial geeksforgeeks:make-pwa-of-a-django-project for including progressive web application feature in my project i think url from django.conf.urls is deprecated. i am sure is exist some solutions... help me please Error File "C:\Users\Republic Of Computer\Desktop\Master cours et TD\python\tberra3lipy\venv\lib\site-packages\pwa\urls.py", line 1, in <module> from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' (C:\Users\Republic Of Computer\Desktop\Master cours et TD\python\tberra3lipy\venv\lib\site-packages\django\conf\urls\__init__.py) urls.py from django.contrib import admin from django.conf.urls.static import static from django.urls import path,include from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('donation/',include('donation.urls',namespace='donation')), path('',include('pwa.urls')), ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py from pathlib import Path import os INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pwa', 'accounts', 'donation', ] ROOT_URLCONF = 'src.urls' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' #pwa PWA_SERVICE_WORKER_PATH = os.path.join(BASE_DIR, 'static/js', 'serviceworker.js') PWA_APP_NAME = 'tberra3li' PWA_APP_DESCRIPTION = "app for blood donors" PWA_APP_THEME_COLOR = '#000000' PWA_APP_BACKGROUND_COLOR = '#ffffff' PWA_APP_DISPLAY = 'standalone' PWA_APP_SCOPE = '/' PWA_APP_ORIENTATION = 'any' PWA_APP_START_URL = '/' PWA_APP_STATUS_BAR_COLOR = 'default' PWA_APP_ICONS = [ { 'src': 'static/assets/img/icon-160x160.png', 'sizes': '160x160' } ] PWA_APP_ICONS_APPLE = [ { 'src': 'static/assets/img/icon-160x160.png', 'sizes': '160x160' } ] PWA_APP_SPLASH_SCREEN … -
Having Issue Veryfing Successful Transactions After API Call
i Just Integrated paystack to my website and am having issues verifying transaction status. this transaction is successful when the users enter card details but the documentation is not clear on how to verify this successful transactions. see the doc below to understand my point The verify payment docs verify transaction docs The docs talks about using the callback url to verify transactions and this seems not easy with python. kindly take a look at my code. def paystackdeposit(request, comment = None): user = request.user email = user.email if request.method == 'POST': form = DepositForm(request.POST) if form.is_valid(): amount = form.cleaned_data.get('amount') #the callback is expected to return the url and replace YOUR_REFERENCE with the reference code used in making get request to verify transaction status url = 'http://127.0.0.1:8000//postpayment_callback.php?reference=YOUR_REFERENCE' parsed_url = urlparse(url) captured_value = parse_qs(parsed_url.query)['reference'][0] url = "https://api.paystack.co/transaction/verify/:captured_value" headers = {'Authorization': 'Bearer sxk_lixzve_1xxreeeeeeeeeeeeeb8e794f74ffzzfdddd','Content-Type': 'application/json'} response = requests.request("GET", url, headers=headers) if response.data.status == success: account.balance += amount asof = account.modified account.save(update_fields=[ 'balance', 'modified', ]) return render (request, 'accounting/deposit_successful.html', { 'amount':amount, 'balance':balance, 'created': created, }) else: form = DepositForm(request.POST) return render(request, 'depositing/paystack_deposit_fund.html', {'form': form, 'refcode': refcode}) this is what the documentation says. If the transaction is successful, Paystack will redirect the user back to … -
Send confirmation email right after sign up with auth0 application
I am a django starter, and I'm doing a backend project. Now, I meet some troubles. The user will login when they are in my home page. After they click login button, they will be redirected to auth0 authentication application. A new user has to sign up and the backend will send a email for verification. The problem is that I cannot find a good solution to send an email after a user has signed up. My solution is send email when the new users sign up and login in automatically and they will be redirected to my home page of web application. Then, I check if the email is verified and is sent verification. But I want to send email right after the user click the submit button of sign up page. Does anyone has better ideas? -
Django cbv multiple items to delete as te same time
I'm new here the reason of this message it's because I'm learning django with class based views, and all is working fine, it’s a little bit confused because django with functions are totally different. What I'm trying to do it's something like the image above, but I really have no idea how to achieve this. Do you have any link where I can see how to do it? I do not know how to do it with a detailview and delete view. Any advice is welcome. Thank you What I wanto to achieve it's to select multiple data from model and delete as the image -
How do I pass field value as argument to next view django?
I cannot find the functions in the Django documentation that allow me to pass a value that one form creates in my db to another function. I would like to pull create an object in my create_player_view capture that created objects pk and pass it to scoring_view. Doing this through the form action field has been unsuccessful as no data is passing between the views. What is a better way to do this? I want simple behavior that takes the Match ID created in create_player_view and passes it for update/use in the scoring view. ###model class Players(models.Model): matchID = models.AutoField(primary_key=True) player1Name = models.CharField(max_length=10) player2Name = models.CharField(max_length=10) def __str__(self): return f'{self.matchID}: {self.player1Name} vs {self.player2Name}' class Scores(models.Model): matchID = models.OneToOneField(Players, on_delete=models.CASCADE, related_name='match') p1_set_1_score = models.IntegerField(default=0) p1_set_2_score = models.IntegerField(default=0) p1_set_3_score = models.IntegerField(default=0) p1_set_4_score = models.IntegerField(default=0) p2_set_1_score = models.IntegerField(default=0) p2_set_2_score = models.IntegerField(default=0) p2_set_3_score = models.IntegerField(default=0) p2_set_4_score = models.IntegerField(default=0) def __str__(self): return f'{self.matchID}: ' ###Views def create_player_view(request): """" allows users to name two players competing vs one another """ if request.method == "POST": form = PlayerForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect('tennis:m_score') #is it possible to pass this view created instance? else: message = "Form could not be completed" return render(request, "create_player.html", {"message":message}) else: form = … -
Django react router dom don't render file
my page don't render the HomePage but if i only use h1 Test HomePage h1 in render it work. i wanna know where i should fix it or what im doing wrong thanks for help or you need to see the other file you can tell me im kinda new to the programming import React, { Component } from "react"; import { render } from "react-dom"; import HomePage from "./HomePage"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; export default class App extends Component { constructor(props) { super(props); } render() { return ( <div> <HomePage/> </div> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); this is my HomePage Code import React, { Component } from "react"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; import { BrowserRouter as Router, Switch, Route, Link, Redirect, } from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); } render() { return ( <Router> <Switch> <Route exact path="/"> <p>This is the home page</p> </Route> <Route path="/join" component={RoomJoinPage} /> <Route path="/create" component={CreateRoomPage} /> </Switch> </Router> ); } } -
Why DRF giving me 404
I am keep getting 404 in DRF whenever I send request from postman even though the url is correct. urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('backend.urls')) ] backend/urls.py from django.urls import path, include from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('/post', views.PostView, basename='post') urlpatterns = [ path('', include(router.urls)), ] from postman I am sending post request on this endpoint http://127.0.0.1:8000/post but I am keep getting 404 not found error. What am I doing wrong? -
I want to show last 4 products in Django
There are many products in the database. but I only want to show the 4 most recently added products. in the variable similar views.py def product_detail(request, category_slug, id): category = Category.objects.all() product = get_object_or_404(Product, category__slug = category_slug, id=id) images = ProductImages.objects.filter(product_id=id) similar = Product.objects.all().filter(category__slug=category_slug) context = { 'category': category, 'product': product, 'images': images, 'similar': similar, } return render(request, 'detail.html', context) -
Django- link answer choice to question and survey
I am trying to create a number of surveys in Django and put them in a survey index page. I have run into an issue: Up until now, all of my surveys had questions which had the same set of answer choices, so in my Django models I linked the answers only to the survey because it was the easiest for me and it was working. Now I have to add a new survey where each question has a different set of answers choices (if you are curious, this is the survey: https://www.fresno.ucsf.edu/pediatrics/downloads/edinburghscale.pdf). My problem is that for this new survey I am now getting every possible answer choice in the whole survey for each question. How can I link the answer choices to the question so that I will only see the choices for the corresponding question? Yes, I have read the Django polls tutorial and have tried requesting the question_id, but then I got an error along the lines of "missing question_id" so I went back to my original code. I think the right approach would be to link the answer choices to both the question and the survey, but not sure. Here is my model: class Questionnaire(models.Model): … -
how do I make a math Django and react web application?
Hope all is well. I want to have an input field in my react frontend that takes in a math expression (e.g 1 + 1) and I want my backend to respond with the answer 2. How do you do this using reactjs and Django? So far I have some of the frontend finished: it will send the input data to the backend using the API url. import React, {useState, UseEffect } from 'react'; function Home() { const [query, setQuery] = useState(""); return ( <div className='Home'> <form action={APIL_URL} method="POST"> <input name="linear-algebra-expression" id="linear-algebra-expression" type="text" onChange={e => setQuery(e.target.value)} value={query}> </input> </form> </div> ) } export default Home; I am aware that in my Django backend I am going to have something like: class LinearAlgebraView(APIView): def post(self, request): expression = request.POST['linear-algebra-expression'] return (... ?) I want to be able to return the computed data from Django to react at the samne web page where the user entered the math expression in the form/input. How do I do this? Thanks -
Django: How to create a view that can be emailed to users?
In my DB, I have a bunch of objects of model 'Foo'. Users can create, update, delete objects in the admin panel. Once a week I would like to send a digest of all objects that were created, updated, or deleted. I am using the django-simple-history plugin so I am able to create a dictionary that has changes for a given date range. This part is OK. I would like to take this data, put it in a HTML page, and then email it to a distribution list. For the 2nd part, do I create a Django view or just create a HTML template and do variable substitution? This view will never been shown on a webpage. Not sure what is the easiest way to do this. -
hosting django app its return path: .github/workflows/main_school-database.yml
am trying to host my django app on Microsoft azure but when i choose my github account, my repository and my branch when its successeful but when I click on Preview File its throws me an error saying: File path: .github/workflows/main_school-database.yml and with something i did not know. its looks like i need to create yml file inside my project directory and paste that code its throws me. I'm a begineer in Microsoft Azure and this is my first time building an applications on Azure with django after i migrate from Heroku to Microsoft Azure. is anybody who can help please? the logs: # Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy More GitHub Actions for Azure: https://github.com/Azure/actions More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions name: Build and deploy Python app to Azure Web App - school-database on: push: branches: - main workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python version uses: actions/setup-python@v1 with: python-version: '3.9' - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate - name: Install dependencies run: pip install -r requirements.txt # Optional: Add step to run tests here (PyTest, … -
ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects
The Heroku Build is returning this error when I'm trying to deploy a Django application for the past few days. The Django Code and File Structure are the same as Django's Official Documentation and Procfile is added in the root folder. Log - -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> No Python version was specified. Using the buildpack default: python-3.10.4 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (pyproject.toml): started Building wheel for backports.zoneinfo (pyproject.toml): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python /app/.heroku/python/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py build_wheel /tmp/tmpqqu_1qow cwd: /tmp/pip-install-txfn1ua9/backports-zoneinfo_a462ef61051d49e7bf54e715f78a34f1 Complete output (41 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.10 creating build/lib.linux-x86_64-3.10/backports copying src/backports/__init__.py -> build/lib.linux-x86_64-3.10/backports creating build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.png' under directory 'docs' warning: no files found matching '*.svg' under directory … -
Django file upload testcase: how to send both form data and files in request
I want to write a testcase for file upload page which also have other form fileds. So I come up with the following code: file_b = open(test_file2, 'rb') file_c = open(test_file3, 'rb') form_data = {'form_field_1': 'abc', 'form_field_2': 'def'} form_data = form_data.update({'file_name': self.file_b, 'co-file_name': self.file_c}) self.client.post(reverse('overrun_cause_modal', kwargs={'workflowid': self.wf_id}), data=form_data, format='multipart') the above code caused form to be invalid: form = WorkflowForm(data=form_data) form.is_valid() --> False if I do comment out: form_data = form_data.update({'file_name': self.file_b, 'co-file_name': self.file_c}) then form is valid. How can I send both form data and files in request so that I can have a valid regular form and also request.FILES['file_name'], request.FILES['co-file_name'] as well as request.FILES['file_name'].name and request.FILES['co-file_name'].name? -
Django migration IntegrityError: invalid foreign key (but the data exists)
I am gradually updating a legacy Django application from 1.19 -> 2.2 and beyond. To upgrade to 2.2, I just added on_delete=models.CASCADE to all models.ForeignKey fields that did not have the error. Possibly unrelated, when I run manage.py migrate, Django throws the following error (I shortened the table/field names for brevity): django.db.utils.IntegrityError: The row in table 'X' with primary key '3' has an invalid foreign key: X.fieldname_id contains a value '4' that does not have a corresponding value in Y__old.id. Note in particular the __old.id suffix for the db table that Django expects to contain a row with id 4. When manually inspecting the db, the table Y does really contain a valid row with id 4! I'm assuming, to support the migration, Django is making some temporary tables suffixed with __old and somehow it is unable to migrate said data? The db row Y in question is really simple: a char, boolean, and number column. -
Where does manage.py get the frontend when there isn't a main.js?
I want to know why my changes aren't reflecting in the browser/console I'm working on a React + Django app and encountered this warning react-dom.development.js:86 Warning: The tag <thread> is unrecognized in this browser When I saw this I found the one instance I wrote <thread> and replaced it with <thead> I then saved my changes and re ran python manage.py runserver and webpack --mode development --watch ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/frontend/ After reloading my app I'm still confronted with the same warning message and when I inspect the warning I can see in the Chrome console that the file is still using <thread> I thought it could be because I didn't clear my static/frontend/main.js before re running webpack which didn't change anything I then notice when I run python manage.py runserver without running the separate webpack command, and after deleting static/frontend/main.js my app still gets loaded to localhost... It was my understanding that static/frontend/main.js is what python uses to display my app in the browser Where is python getting the frontend to display my app when there isn't a main.js file? -
ValueError: Could not find function validator when calling makemigrations in Django 4.0
Using the solution here to validate URLField, I am getting ValueError when I run python manage.py makemigrations and I'm not sure why. What am I doing wrong? from django.contrib.auth.models import User from django.db import models from django.core.exceptions import ValidationError from urllib.parse import urlparse def validate_hostname(*hostnames): hostnames = set(hostnames) def validator(value): try: result = urlparse(value) if result.hostname not in hostnames: raise ValidationError(f'The hostname {result.hostname} is not allowed.') except ValueError: raise ValidationError('Invalid URL') return validator class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) twitter = models.URLField( blank=True, null=True, validators=[validate_hostname('twitter.com', 'www.twitter.com')] ) Traceback $ python manage.py makemigrations Migrations for 'userprofiles': userprofiles/migrations/0002_userprofile_twitter.py - Add field twitter to userprofile Traceback (most recent call last): File "/home/master/github/mywebsite/src/manage.py", line 22, in <module> main() File "/home/master/github/mywebsite/src/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 214, in handle self.write_migration_files(changes) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 255, in write_migration_files migration_string = writer.as_string() File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/db/migrations/writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/db/migrations/writer.py", line 99, in serialize _write(arg_name, arg_value) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/db/migrations/writer.py", … -
Model instances autocreation on interval
I want to implement django models autocreation but have no clue how to do it. As example we set 1 year interval, and when it passes the model instance is automatically created. -
Can not see an app with name "advertisements" in admin interface
I tested it many times. When I add an app with the name advertisements (add models, admin + register in INSTALLED_APPS) it is not listed in the admin interface (it is very hard to see but it disappears after microseconds). models.py: from django.db import models # Create your models here. class Advertisement(models.Model): pass admin.py: from django.contrib import admin from .models import Advertisement # Register your models here. @admin.register(Advertisement) class AdvertisementAdmin(admin.ModelAdmin): pass apps.py: from django.apps import AppConfig class AdvertisementsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'advertisements' settings.py: INSTALLED_APPS = [ # ... "advertisements", ] Changing an app directory to something like advertisements2, app name (in apps.py) to advertisements2 solves the problem.