Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create Razorpay Order in my Django DRF project gives 401 Error. "Authentication credentials were not provided."
Im trying to create a view where we create an order through razorpay, but continuously getting 401 error despite the keyId and KeySecret being correct. Even postman and curl gives the same error. I have tried removing the authentication, adding authentication through postman etc, but the issue persists. The Key works for razorpay's global API correctly, but the error is only in my function. Any help would be welcome thanks curl -X POST -H "Content-Type: application/json" -H "Authorization: Basic cnpwX3Rlc3RfNGZTSXNRaWdoeTZnU3o6Y1pZT3pvbnRWOFlEM1V1bzFneVlYalVF" -d "{\"amount\": 10000, \"currency\": \"INR\", \"receipt\": \"order_receipt\"}" http://127.0.0.1:8000/api/orders/create-razorpay-order/ {"detail":"Authentication credentials were not provided."} path('create-razorpay-order/', views.create_razorpay_order, name="create_razorpay_order"), def create_razorpay_order(request): razorpay_key = 'KEYID' razorpay_secret = 'RAZORPAYKEYSECRET' # Concatenating the API key and secret with a colon key_id_secret = f'{razorpay_key}:{razorpay_secret}' # Base64 encode the concatenated string base64_encoded_key_id_secret = base64.b64encode(key_id_secret.encode()).decode() # Endpoint for creating an order on Razorpay's server razorpay_order_url = 'https://api.razorpay.com/v1/orders' # Amount in paise (e.g., 10000 represents ₹100.00) amount = 10000 # Data to be sent in the request body data = { 'amount': amount, 'currency': 'INR', # Currency code (e.g., INR for Indian Rupees) 'receipt': 'order_receipt1', # Unique identifier for the order (optional) } # Headers for the request headers = { 'Content-Type': 'application/json', 'Authorization': f'Basic {base64_encoded_key_id_secret}', } # Make a … -
Django render a view depending geolocation from the browser
I'm trying to load my home page according to the geolocation given by the browser, if the coordinates are ok, I load a list of airports around these coordinates, otherwise I load all airports. However, I can't manage this between GET & POST requests. Each time I get all the airports in the page. In fact when the view is loaded (by the GET request) all airport are displayed, after when the page is entirely loaded the POST event is raised with the GPS information. So the list of airports around location is performed but the rendering is always wrong. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.home_view), views.py def home_view(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') if request.method == 'POST': Latitude = float(request.POST.get('latitude')) Longitude = float(request.POST.get('longitude')) context = aviationweatherapi.getStationInfo(Latitude,Longitude) print ("Get airports list around current GPS location") else: #The request is GET context = aviationweatherapi.getStationInfo(None, None) print ("Get all airports") context.update({'IP':ip}) return render(request,'acceuil.html',context) template_Base.html (base of the acceuil.html) <body> {% csrf_token %} {% block contenu %} {% endblock %} <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script> <script> const findLoc = () => { const success = (position) => { const latitude = position.coords.latitude; const longitude = position.coords.longitude; … -
How to set custom JWT in django using dj-rest-auth
I have setup a backend JWT authentication system using django, dj-rest-auth and simpleJWT. Currently, the dj-rest-auth is setting default JWT in the response cookies. To use custom cookies, I have to use simpleJWT's /token and /token/refresh urls. So, while testing in postman or swagger, I'm not getting the custom JWTs neither in the response body nor in the cookies(except the default ones provided by dj-rest-auth). Is there a way around so that I can receive those custom JWTs as cookies or response body? I am also using social authentication so those tokens have to be present in the response JWTs as well. My urls.py file urlpatterns = [ path('', include(router.urls)), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('users/', include('dj_rest_auth.urls')), path('users/registration/', CustomRegisterView.as_view(), name='custom_rest_register'), ] serializer.py class EnrichedTokenPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) // custom token logic return token` I am using Django>=5.0.2 django-allauth>=0.61.1 djangorestframework>=3.14.0 djangorestframework-simplejwt>=5.2.2 dj-rest-auth>=5.0.2 Any suggestions would be helpful. I have done the authentication using dj-rest-auth and simpleJWT. I have a custom token serializer function to create custom tokens which return from /token url of simpleJWT. But while loggin in through Postman, these custom tokens were not present. I want them to be sent from the server either … -
I keep getting these errors "GET /static/style.css HTTP/1.1" 404 179 , "GET / HTTP/1.1" 200 10881 , Broken pipe from ('127.0.0.1', 57644)
STATIC_URL = '/static/' STATICFILES_DIRS = ((os.path.join(BASE_DIR, 'static')), ) STATIC_ROOT = os.path.join(BASE_DIR, 'files') STATIC FILES_FINDERS = [ > > "django.contrib.staticfiles.finders.FileSystemFinder", > > "django.contrib.staticfiles.finders.AppDirectoriesFinder", > > ] urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('paintings/', views.paintings, name='paintings'), path('sculptures/', views.sculptures, name='sculptures'), path('engravings/', views.engravings, name='engravings'), path('future_auction/', views.future_auction, name='future_auction'), path('winners/', views.winners, name='winners'), static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I was trying to deploy my project but when i turned DEBUG = False ALLOWED_HOSTS = ['*'] and run the server,i got these issues -
Django: no access to database from async function
I am writing tests for my Django application using asyncio and running into a database access issue. Here is minimal code that reproduces the error: import pytest from authentication.models import User @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio class TestDatabaseAccess: @pytest.fixture(autouse=True) def _fixture(self): User.objects.create(username='username') async def test_main(self): async def get_user_async(user_id): user = await sync_to_async(User.objects.get)(id=user_id) return user await get_user_async(1) I get error: def execute(self, query, params=None): if params is None: return Database.Cursor.execute(self, query) query = self.convert_query(query) return Database.Cursor.execute(self, query, params) E django.db.utils.OperationalError: no such table: authentication_customuser What am I doing wrong? My fixture works fine and has access to database, I can print all users form there But async test throwing an error. -
Creating two separate models for patient and doctor using Django
I want to create registration as a patient and as a doctor such that when user login my website they get two options(as patient or as doctor).How to achieve this using Django? Registration form has different fields for Doctor and Patient. I want code.I'm not able to understand relationship.Also urls.py for this project. -
Django Ñ problem? ValueError: source code string cannot contain null bytes
I'm working on Django and connecting to a remote SQL Server database. I managed to make the connection to the database using the MSSQL engine, but when I run inspectdb, the generated file contains errors due to the character "Ñ", in the file they appear as ±. So when I try to run the server, I get the following error: ValueError: source code string cannot contain null bytes. refering to the generated file with inspectdb I suspect that the problem is related to the database encoded in Modern_Spanish_CI_AS and also Ñ character is causing trouble. So far, I've tried the following: In settings.py, in database options: 'unicode_results': True Also, 'extra_params': 'ClientCharset=utf8' Modifying in base.py: mssql: unicode_results = options.get('unicode_results', True) Some less elegant solutions like opening the generated file with Notepad and saving it in UTF-8 or ISO 8859-1 -
When posting on django website it posts it to a different page
Making a website that has a forum for text posts and a greenhouse page for images, when I try to post on the forum page it posts it to the greenhouse page, and when i try to add a comment on a post in the forum page I get: PlantPost matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/greenhouse/create_comment/1/ Django Version: 5.0.4 Exception Type: DoesNotExist Exception Value: PlantPost matching query does not exist. Exception Location: C:\Users\hurle\OneDrive\Documents\Desktop\profile_env\Lib\site-packages\django\db\models\query.py, line 649, in get Raised during: greenhouse.views.create_comment Python Executable: C:\Users\hurle\OneDrive\Documents\Desktop\profile_env\Scripts\python.exe Python Version: 3.12.1 Python Path: ['C:\\Users\\hurle\\OneDrive\\Documents\\Desktop\\bloomhub4', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Users\\hurle\\OneDrive\\Documents\\Desktop\\profile_env', 'C:\\Users\\hurle\\OneDrive\\Documents\\Desktop\\profile_env\\Lib\\site-packages'] forum create_comment.html {% extends "home.html" %} {% block content %} <h2>Add Comment</h2> <form action="{% url 'forum:create_comment' post.id %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %}``` **forum create_post.html** ```{% extends "home.html" %} {% block content %} <h2>Create Post</h2> <form action="{% url 'create_post' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} forum models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() image = models.ImageField(upload_to="forum_images/", null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content … -
Can I add the controller part of the MVC pattern to the MTV pattern in Django?
I'm trying to develop a multiplayer web game using Django. I understand that in Django's MTV Pattern, the view part takes on the role of the controller. But the view part needs a user in the frontend who accesses the website in order to be able to carry out actions. But in my WebGame there are also actions that need to be executed in the background, which need to be executed at certain times without any user in the frontend. So can I insert a folder in my Django code with the controller classes and specify when which function should be executed regularly? If I'm on the wrong path when it comes to solving my problem, I'm of course also interested in alternative suggestions. I watched a few videos and read a few books, but I couldn't find anything that really matched my problem. -
Calling python package by package name
I want to call my local package utility by its name like in Django django-admin. It has structure like: utility-name [command] I've found the method of calling utility using __ main __.py. Structure of using this method is: python -m myappname. But it isn't what I wanted. So how I can use structure of calling like in django-admin? I'm junior programmer so if this information isn't enough u may ask questions -
Why do I get a Integrity Error when using this code in Django?
I am having issues while learning about SQLite databases in Django. I am trying to check if a specific url is already in the database, but I keep getting a Integrity Error. this is the code that is supposed to check if it is already in the database: if not Songs.objects.filter(tidal_url=song_url): new = Songs(name=name, artist=artist, tidal_url=song_url) new.save() These are my models: from django.db import models from django.contrib.auth.models import User # Create your models here. class Songs(models.Model): name = models.CharField(max_length=255) artist = models.CharField(max_length=255) tidal_url = models.CharField(max_length=255, unique=True) class UserDownload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) song = models.ForeignKey(Songs, on_delete=models.CASCADE) dl_path = models.CharField(max_length=255) Can anyone figure out why this is happening? -
django a filed can not make it althougfh i make makemigrations and migrate
hi i have a filed i cannot make it in database although i make makemigrations and migrte this is models.py ``your text`` class Display(models.Model) : `your text` url=models.URLField(unique=True) `your text` text = models.CharField(max_length=150) `your text` class Display_Data(models.Model) : `your text` displays = models.ManyToManyField(Display,related_name='display_data') `your text` users= models.ForeignKey(UserProfile,on_delete=models.CASCADE,default="1") `your text` choosenum=models.IntegerField() `your text` puplish_date =models.DateTimeField(default=datetime.now) and this is models.py for accounts app `your text`class UserProfile(models.Model): `your text` user=models.OneToOneField(User,on_delete=models.CASCADE) `your text`user_nickname=models.CharField(max_length=150) `your text`nikename_url=models.URLField() `your text`userphoto =models.ImageField(upload_to='imageprofile/%Y/%m/%d/') and this is views.py for display app `your text`def check_url_exists_and_person(url_to_check): `your text`user_info_array = [] `your text`for i in range(1, 6): latest_successful_record = Display_Data.objects.filter(displays__url=url_to_check, choosenum=i).order_by('-puplish_date').first() if latest_successful_record: user_info = { 'user_nickname': latest_successful_record.users.userprofile.nikename, 'url': latest_successful_record.users.userpofile.nikename_url } else: user_info = None user_info_array.append(user_info) return user_info_array i received a mistake from Django 'Unknown column 'display_display_data.users_id' in 'field list'") why database have not a filed user_id although i make it in models.py i make a new database and delete files of migrations in application display and app userprofile and the filed is not create -
I am getting NoReverseMatch error when adding students data in django admin panel
I am a beginner and trying to create a basic college portal. I am getting NoReverseMatch at /admin/api/student/add/ error when adding students data in django-admin panel. urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/',admin.site.urls), path('api/',include('api.urls')), ] admin.py from django.contrib import admin from .models import Student, Instructor, Course, Enrollment @admin.register(Student) class StudentAdmin(admin.ModelAdmin): list_display = ['std_id', 'firstname', 'lastname', 'date_of_birth', 'cgpa'] @admin.register(Course) class CourseAdmin(admin.ModelAdmin): list_display = ['course_id', 'coursename', 'cred_hrs'] @admin.register(Instructor) class InstructorAdmin(admin.ModelAdmin): list_display = ['instructor_id', 'instructor_name'] @admin.register(Enrollment) class EnrollmentAdmin(admin.ModelAdmin): list_display = ['enrollment_id', 'student', 'course', 'instructor'] models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class Student(models.Model): std_id = models.CharField(max_length=6,primary_key = True, unique=True , editable=False) firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) date_of_birth = models.DateField() cgpa = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(4)] ) class Course(models.Model): CREDIT_HOURS_CHOICES = [ (1, '1 credit hour'), (2, '2 credit hours'), (3, '3 credit hours'), ] course_id = models.CharField(max_length=6,primary_key = True, unique=True , editable=False) coursename = models.CharField(max_length=100) cred_hrs = models.IntegerField(choices=CREDIT_HOURS_CHOICES) class Instructor(models.Model): instructor_id = models.CharField(max_length=6,primary_key = True, unique=True , editable=False) instructor_name = models.CharField(max_length=100) class Enrollment(models.Model): enrollment_id = models.AutoField(primary_key=True) student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) instructor = models.ForeignKey(Instructor,on_delete = models.CASCADE) I am new to this kind of stuff so yeah... … -
Group by or distinct for django to remove the row which has the duplicate column
I have table like this below Table A ID name score 1 aaa 100 2 bbb 200 3 ccc 300 4 bbb 100 5 kkk 600 6 ccc 300 Now name bbb and ccc is duplicated so, I want to remove then and depict like this, ID name score 1 aaa 100 2 bbb 200 3 ccc 300 5 kkk 600 I found out that django model doesn't have groupby so, I guess need to use annotate or distinct So my idea is like this below, MyModel.objects.annotate(Count('name')) However it doesn't work as I hope. Any help or hint? -
Passing information from view to form with FormWizard
I'm trying to pass data from my view to my form class using WizardView. Without WizardView, I do this using get_forms_kwargs() like the below: def get_form_kwargs(self): kwargs = super(MenuAdd, self).get_form_kwargs() kwargs.update({'month': self.kwargs['month']}) return kwargs And in my form class I use: def __init__(self, *args, **kwargs): self.month = kwargs.pop('month', None) All good - I'm able to use 'month' for validation in e.g. clean(). When I'm using WizardView though, I'm specifying the step in get_forms_kwargs() as follows, per the docs: def get_form_kwargs(self, step=0): kwargs = super(MenuAddWizard, self).get_form_kwargs() kwargs.update({'month': self.kwargs['month']}) return kwargs My get_form() doesn't like this: File "python312\Lib\site-packages\formtools\wizard\views.py", line 311, in post return self.render_next_step(form) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "python312\Lib\site-packages\formtools\wizard\views.py", line 322, in render_next_step new_form = self.get_form( ^^^^^^^^^^^^^^ File "myproject\views.py", line 1614, in get_form form = super().get_form(step, data, files) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "python312\Lib\site-packages\formtools\wizard\views.py", line 432, in get_form return form_class(**kwargs) ^^^^^^^^^^^^^^^^^^^^ TypeError: BaseFormSet.__init__() got an unexpected keyword argument 'month' Any idea how to properly pass kwargs (or any other way) to a form with Django Form Wizard? -
I don't understand why the Django built in 'Reverse' function is not working
I am trying to learn Django in python, when today, I stumbled upon this error: "NoReverseMatch at /downloader/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name." I am not sure why this is happening, but here is my code: (this is the views.py code) if not request.user.is_authenticated: return HttpResponseRedirect(reverse("login")) (here is my urls.py) urlpatterns = [ path("", views.index, name="index"), path("add/", views.add, name="add"), path('scrape/', views.scrape_all, name='scrape_all'), path('find_url/', views.find_song_urls, name='find_song_urls'), path('downloader/', views.downloader, name="downloader"), path("login/", views.login_view, name="login"), path("logout/", views.logout_view, name="logout"), path("create_acount/", views.create_account, name="create_account") ] I was just trying to make a login function with my project but I don't get what I am doing wrong. -
How to know if the syntax of my urls is a valid django url syntax?
I generate my URLs dynamically and I want to know if there is a way to check if the syntax is valid or not. Because I'll create my URL from the Django admin panel, and if the syntax isn't correct for Django, the code will crash. For example, if I make a mistake and create a URL like this: test/<:custom_pk>/`, the app will crash, and I won't be able to modify it from the admin panel because of the crash. The error is : File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 307, in init self.converters = _route_to_regex(str(route), is_endpoint)[1] File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 277, in _route_to_regex raise ImproperlyConfigured( django.core.Exceptions.ImproperlyConfigured: URL route 'test/<:custom_id>' uses parameter '<:custom_id>' which isn't a valid Python identifier. I try to send to my urlpatterns an url which had an incorrect syntax and i except this error : File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 307, in init self.converters = _route_to_regex(str(route), is_endpoint)[1] File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 277, in _route_to_regex raise ImproperlyConfigured( django.core.Exceptions.ImproperlyConfigured: URL route 'test/<:custom_id>' uses parameter '<:custom_id>' which isn't a valid Python identifier. -
A very faulty Django when it comes to rendering image in my template
Right lets try this again. My Django images are not showing in my template. Despite setting this up correctly. This is my setup - a fully replicable setup -, as follows: # settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #urls.py from django.urls import path, include from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.views.static import serve urlpatterns = [ path('<uuid:uuid>', views.details), ] # Only for development. Do not use this in production. if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.template import loader from .models import MediaModule def details(request, uuid): articles = MediaModule.objects.all().values() article = get_object_or_404(MediaModule, uuid=uuid) title = article.article_headline return render(request, 'media-article.html', {'article': article, 'title':title, 'articles':articles}) #media-article.html <img src="{{article.article_image.url}}" alt="{{article.article_image.url}}"/> #models.py from django.db import models import uuid # Create your models here. class MediaModule(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article_image = models.ImageField(upload_to='media/assets') This is my file directory layout: Root-| media-| templates-| models.py views.py urls.y media-article.html media-| assets-| image.jpg Is there a valid reason as to why, hen I go to the debug console in my browser - does it give me a 404 error despite the … -
bypassing integrityError gotten from unique field in a django model
I want a unique field generated at database level. The way unique=True works is it raises an error if it see's a duplicate value in the database. I don't want that though, I want it to simply generate a new unique number instead of raising an error. This is the model that gives a user an account number, Any help will be much appreciated class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) account_number = ShortUUIDField(unique=True,length=10, max_length=25, prefix="217", alphabet="1234567890") -
In django how can I resolve a reverse error when copying text from an html table row and attempting to write it to a text file?
I have a django app with a page that shows a data table of text strings populated from a model. Each string is a website url. I need to be able to click on any one of these rows and have that url string written to a text file. What I have so far results in a 'reverse' error as soon as the server tries to load the home page. Here is the model: class Environment(models.Model): url = models.CharField(max_length = 250, null=True, blank=True) def __str__(self): return self.url Here is the view for the home page, which displays a list of urls populated from the model: def home(request): envs = Environment.objects.all() f = open('environment.txt', 'r') file_content = f.read() f.close() context = {'title':'Home Page', 'year':datetime.now().year, 'envs':envs, 'file_content':file_content} return render(request, 'app/home.html', context) here is the view for the writing of the url text to the file: def write_url_to_file(request, url): with open('environment.txt', 'w') as file: file.write(url) file.close() return redirect('app:home') Here is the url pattern: path('write-url/<str:url>/', views.write_url_to_file, name='write_url_to_file'), Here is the template tag. The idea is to click a url to write it to a text file: <table> <tr> <th>Environment</th> </tr> {% for env in envs %} <tr> <td><a href="{% url 'app:write_url_to_file' env.url %}">{{ env.url … -
Why do I get a server side HTTP 400 error when I try to access my django server with my mobile phone?
I have set up a simple, local running django server which provides buttons to trigger some bash commands on the server (currently my MacBook Pro). The output of these commands is then displayed on the website. Anyways: The website is working fine as long as I access it from the DuckDuckGo Browser on my MacBook. I also tried with the Brave Browser installed on my Desktop PC - works fine. Now, as I try to access the website from my iPhone, a connection is established, the buttons are working and also, the text on the buttons disappeared. But more importantly, I get a strange error on the server inside the console which is running the server. The error says: [26/Apr/2024 11:33:04] code 400, message Bad request version ('p¤\x99é4rÙu*\x08\x8dÎ\x06¨A©\x06\x8f?l\x19\x9fz\x97\x00,êê\x13\x01\x13\x02\x13\x03À,À+Ì©À0À/̨À') [26/Apr/2024 11:33:04] You're accessing the development server over HTTPS, but it only supports HTTP. Using WireShark, I compared the package traffic between the iPhone and the server, and between the desktop / macbook and the server. It was obvious that the phone tries to use HTTPS / TLS to connect to the server while the desktop / macbook connect using HTTP. But as this fails, the TLSv1 package contains the following alert … -
Why is Django randomly deleting images from my template for no reason
Django never ceases to baffle me with completely uncalled for actions. I I have a media article template which is derived from a Django model. All works a treat and looks awesome, except for the images. One minute they're present, the next Django needs a new glasses prescription as it suddenly decides it can't see the image which is blatantly in the directory with which I have set up. Here's my full reproduceable example and see if anyone can figure out why Django decides its not going to show the image: #models.py from django.db import models import uuid # Create your models here. .... uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article_image = models.ImageField(upload_to='media/assets') .... In my views.py, I have the following: def details(request, uuid): articles = MediaModule.objects.all().values() article = get_object_or_404(MediaModule, uuid=uuid) title = article.article_headline return render(request, 'media-article.html', {'article': article, 'title':title, 'articles':articles}) The file directory is as follows: Root| |- media |- template | - media-article.html |- media | - assets | - image.jpg #media-article.html <img src="{{article.article_image}}" alt="{{article.article_image}}"/> Just why does Django think "Ah-hah, there's the image!", and then says "Actually, I'm going to deliberate pretend the image is not there, because I am going to be difficult now" Why does it … -
"Error: InconsistentMigrationHistory - Django migration admin.0001_initial applied before its dependency Users.0001_initial"
I am encountering an error while running `python manage.py migrate` in my Django project. The error message is as follows: It appears that there is an inconsistency in the migration history of my Django project. Specifically, the `admin.0001_initial` migration is being applied before its dependency `Users.0001_initial`. How can I resolve this issue and ensure that migrations are applied in the correct order? Thank you for your assistance. i tried python manage.py makemigrations and then python manage.py migrate Database connection is good even im able to see dabase table on server but on local machine there is no table \dt List of relations Schema | Name | Type | Owner --------+---------------------+-------+-------- public | django_content_type | table | cc_app public | django_migrations | table | cc_app (2 rows) -
Django-tables2 linkify to other app of project: TemplateDoesNotExist error
Since my project is a bigger one, I have several apps with each app having some database tables (with each table in its own file): project --project -all -overview -home In all/probe_list.html I have a table which displays Probe objects. I want to link the probe name to a details page that is in the overview app (overview/probe_details.html). The link works and shows the correct URL 127.0.0.1:8000/overview/probe_detail/1 but I get TemplateDoesNotExist error since django searches for all/probe_detail.html. project/urls.py urlpatterns = [ path('', include('home.urls')), path('all/', include('all.urls', namespace='all')), path('overview/', include('overview.urls', namespace='overview')), ] all/urls.py app_name = 'all' urlpatterns = [ path('probe_list', views.AllProbesView.as_view()), ] all/models/probe.py class Probe(Compound): targetName = models.CharField(max_length = 100, verbose_name="Target(s)") inVivoActivity = models.CharField(max_length=10, verbose_name="In vivo use"); mechanismOfAction = models.CharField(max_length = 255, verbose_name="Mechanism") def get_absolute_url(self): return reverse('overview:probe_detail', args=[str(self.id)]) def __str__(self): return f'{self.name}, {self.targetName}, {self.mechanismOfAction},{self.inVivoActivity}' class Meta: app_label = 'all' all/tables.py class AllProbesTable(tables.Table): name = tables.Column(linkify=True) class Meta: model = Probe template_name = "django_tables2/bootstrap5-responsive.html" sequence = ("targetName", "name", "mechanismOfAction" ,"inVivoActivity",) exclude = ("id",) all/views.py class AllProbesView(SingleTableView): model = Probe table_class = AllProbesTable queryset = Probe.objects.all() template_name = "all/probe_list.html" all/templates/all/probe_list.html {% load render_table from django_tables2 %} {% render_table table %} overview/urls.py app_name = 'overview' urlpatterns = [ path('probe_detail/<int:pk>', views.ProbeDetailView.as_view(), name="probe_detail"), ] overview/views.py (not ready … -
PostgreSQL: How to tag every table in my database? Generic Foreign Keys, array column, or other method
I'm currently designing a PostgreSQL database where I need to implement a tagging functionality. Essentially, any item from any table in my database can be tagged via key-value tags, very much like Azure tags. I'm considering different approaches for implementing this feature and I'm confused about the best approach: Using Django's Generic Foreign Keys: One approach I'm considering is leveraging Django's Generic Foreign Keys functionality to create a versatile "Tags" table that can reference any other table in the database. This allows flexibility and avoids complex logic. However, there might be drawbacks like performance implications or the database not making sense without Django's ORM. Manual Implementation in a single table, without Generic Foreign Keys: Another option is to implement the "Tags" table manually without relying on Django's Generic Foreign Keys. I would create a separate table that can reference any other table in the database, but without the use of formal foreign keys. This would require to either store some logic in the database or the backend, being more complex to maintain. Separate cross-reference tags table for each table: Alternatively, I could create a separate table (i.e. car_tags, house_tags, person_tags) for each table in my database that requires tagging. This …