Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve "ModuleNotFoundError: No module named 'storages.backends.azure_storage'"
I have a django app and I have the module: django-storages[azure] installed with the command: pip install django-storages[azure] And now I try to run the collectstatic command. But if I enter the command: python manage.py collectstatic I get this error: File "C:\Users\USER\Desktop\Riley\lost-and-found-system\shadow\Lib\site-packages\django\core\files\storage\handler.py", line 35, in __getitem__ return self._storages[alias] ~~~~~~~~~~~~~~^^^^^^^ KeyError: 'staticfiles' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\Desktop\Riley\lost-and-found-system\shadow\Lib\site-packages\django\core\files\storage\handler.py", line 52, in create_storage storage_cls = import_string(backend) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\Desktop\Riley\lost-and-found-system\shadow\Lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\Desktop\Riley\lost-and-found-system\shadow\Lib\site-packages\django\utils\module_loading.py", line 15, in cached_import module = import_module(module_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1381, in _gcd_import File "<frozen importlib._bootstrap>", line 1354, in _find_and_load File "<frozen importlib._bootstrap>", line 1325, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 929, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 994, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "C:\Users\USER\Desktop\Riley\lost-and-found-system\storages\backends\custom_azure.py", line 1, in <module> from storages.backends.azure_storage import AzureStorage ModuleNotFoundError: No module named 'storages.backends.azure_storage' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\USER\Desktop\Riley\lost-and-found-system\manage.py", line 22, in <module> main() File "C:\Users\USER\Desktop\Riley\lost-and-found-system\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\USER\Desktop\Riley\lost-and-found-system\shadow\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() … -
How to use '[' or ']' for the file name of upload_to in Django filefield
I'm trying to put the file name that includes '[' and ']' in the Django model. Examples include: [Test] Test.pdf However, the actual locally saved file names are as follows: Test.pdf Problems occur when importing files via file name because '[' and ']' are saved as removed. models.py: def evidence_directory_path(instance, filename): return f'{instance.user_uuid}/Evidence/{slugify(instance.product)}/{filename}' class Evidence(models.Model): user_uuid = models.CharField(max_length=50) title = models.CharField(max_length=200) product = models.CharField(max_length=500) uploadedFile = models.FileField(upload_to=evidence_directory_path) dateTimeOfUpload = models.DateTimeField(auto_now=True) The output of the following functions is as follows: def evidence_directory_path(instance, filename): print(filename) return f'{instance.user_uuid}/Evidence/{slugify(instance.product)}/{filename}' [Test]Test.pdf However, the actual file name saved is as follows: TestTest.pdf What kind of mistake am I making? I have no idea. -
Django models with hard coded model fields in filtersets
This question is about filtering. But to explain here is some supporting facts... There is a concept in my program of objects being virtual or not virtual. Using rest_framework I have two models in my models.py: So to do that I have tried: class ModelA(models.Model): @property def is_virtual(self): return False class ModelB(ModelA): @property def is_virtual(self): return True So ModelB inherits ModelA. And ALL ModelA objects are NOT virtual, and ALL ModelB objects ARE virtual. Instead of adding this to the database where the column is always True for ModelAs and False for ModelBs I would like to hardcode it in the model class and supporting classes. In my serializers.py I have: class ModelSerializer(serializers.ModelSerializer): is_virtual = serializers.SerializerMethodField() def get_is_virtual(self, obj): return obj.is_virtual All this above basically works UNTIL I want to filter search on is_virtual. In my filters.py: class ModelFilterSet(filters.FilterSet): is_virtual = filters.BooleanFilter(method='filter_is_virtual') def filter_is_virtual(self, queryset, name, value): if value: return queryset.filter(is_virtual=True) else: return queryset.filter(is_virtual=False) Then when I GET http://localhost:8080/api/modela/?is_virtual=false I get: Internal Server Error: /api/modela/ Traceback (most recent call last): File "D:\projects\my_app\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\projects\my_app\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\projects\my_app\venv\lib\site-packages\django\views\decorators\csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) … -
Django AdminSite overrides admin template
I tried to complete Django tutorial and it says that you can override Django's templates with providing example on how to change title of admin page (here). When I tried, nothing changed, so I went to google and investigate. My project structure currently looks like this (django_trial is my project's name): - django_trial/ - django_trial/ - polls/ - ... - templates/ - admin/ - base_site.html (copy of template from Django with modified title) - base_site.html (copy of admin/base_site.html from above, just in case) - venv I tried to see what template it loads, so I put code below in my polls/admin.py from django.template.loader import get_template a = get_template("admin/base_site.html") print(repr(a.origin)) and it printed <Origin name='/home/my_username/Projects/django_trial/templates/admin/base_site.html'>, so my template override seems to work somewhat correctly. Then I tried modifying actual library files and changing original .../venv/lib/python3.10/site-packages/django/contrib/admin/templates/admin/base_site.html didn't do anything as well. In the end, I managed to change admin page title when I modified .../venv/lib/python3.10/site-packages/django/contrib/admin/sites.py. There is a class AdminSite and it has the line site_header = gettext_lazy("Django administration") Seems it has top priority, so its modification actually changed admin page title. What could I do wrong so this line always take priority? -
My models are not showing in Django Admin after OTP Token implementation
I wanted to secure my Django Admin so I followed the steps in here and I implemented django-otp to the my website. The token works fine. I can login my admin page safely but my models doesn't show up in my admin page. For example: Before the OTP Implementation I was able to post a new blog or something but now I cant at all. There are nothing about blogs in my admin. I am logging as a superuser and I tried to create another superuser and logging but it didn't change. I think this error might be caused by the admin.py file configurations, but I'm not sure. Here is my urls.py from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # new from django.conf import settings from django.views.static import serve from django.contrib.auth.models import User from django_otp.admin import OTPAdminSite from django_otp.plugins.otp_totp.models import TOTPDevice from django_otp.plugins.otp_totp.admin import TOTPDeviceAdmin class OTPAdmin(OTPAdminSite): pass admin_site = OTPAdmin(name='OTPAdmin') admin_site.register(User) admin_site.register(TOTPDevice, TOTPDeviceAdmin) urlpatterns = [ path('admin/', admin_site.urls), path('', include('pages.urls')), path('', include('portfolio.urls')), path('', include('services.urls')), path('', include('blog.urls')), re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}), ] Here is an example of my admin.py from django.contrib … -
How to properly scope validator function in parent class for use in child class
I'm trying to use validators, but I'm having a mysterious issue with using validators in a parent/child class. Right now I've created a base class for all media in my project; all media in this model need a name and a thumbnail: class BaseMedia(BaseModel): def validate_thumbnail(image_obj): validate_image_file_extension(image_obj) dimensions = [image_obj.width, image_obj.height] if dimensions[0] != 400 or dimensions[1] != 400: raise ValidationError( "Thumbnail dimensions must be 400 x 400; uploaded image is %s x %s" % (dimensions[0], dimensions[1]) ) media_title = models.CharField( max_length=25, verbose_name="Title (25 char)", null=True ) thumbnail = models.ImageField( null=True, verbose_name="Thumbnail (400 x 400 px)", upload_to="microscopy/images/thumbnails", validators=([validate_thumbnail],), ) and then I have a child class that inherits and implement the core media itself; for example: class MicroscopyMedia(BaseMedia): def validate_image(image_obj): validate_image_file_extension(image_obj) dimensions = [image_obj.width, image_obj.height] if dimensions[0] != 1920 or dimensions[1] != 1070: raise ValidationError( "Image dimensions must be 1920 x 1070; uploaded image is %s x %s" % (dimensions[0], dimensions[1]) ) media = models.ImageField( null=True, verbose_name="Media (1920 x 1070 px)", blank=True, upload_to="microscopy/images", validators=[validate_image], ) The idea being that all models will need a thumbnail, but within the child class I have a specific validator for each individual media type. However, when I try to make this migration, I get … -
django-registration class overriding
Because I need to add a captcha(django-recaptcha) to the registration form I want to override the RegistrationForm class from the django-registration module. I am using: django-registration==3.3 django==4.1 python(3.10) I've tried some options has shown below. forms.py from django_registration.forms import RegistrationForm class MyRegistrationForm(RegistrationForm): age = forms.IntegerField() class Meta(RegistrationForm.Meta): fields = RegistrationForm.Meta.fields + ['age'] urls.py from .forms import MyRegistrationForm from django_registration.backends.activation.views import RegistrationView path('accounts/register/', RegistrationView.as_view(form_class=MyRegistrationForm), name='registration_register') registration_form.html <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <input type="submit" value="{% trans 'Submit' %}" /> </form> Nothing overrides the form. I don't understand why. Same thing for the RegistrationView. I can't override it for some reason. I've been arround these for a while now. Probably am missing something obvious by now. Help is appreciated. Thank you. -
How to get items stacked in a row together in a column thats col-3
I am trying to stack all the items under one another if there is more than one. I am using Django and currently its reproducing a new col-3 for each new item. I have tried bootstrap d-flex flex-wrap, however this is not working. <div class="col-12 col-lg-6"> <p>Order History</p> {% for order in orders %} <div class="row"> <div class="col-3"> <p>Date:</p> </div> <div class="col-3"> <p>Grand Total:</p> </div> <div class="col-3"> <p>Order Number:</p> </div> <div class="col-3"> <p>Items:</p> </div> </div> <div> <div class="row"> <div class="col-3"> <p><strong>{{ order.date }}</strong></p> </div> <div class="col-3"> <p><strong>&euro;{{ order.grand_total | floatformat:2 }}</strong></p> </div> <div class="col-3"> <a href="{% url 'order_history' order.order_number %}" title="{{ order.order_number }}"> {{ order.order_number|truncatechars:8 }} </a> </div> {% for item in order.lineitems.all %} <div class="col-3"> <p><strong>{{ item.product.name }} x {{ item.quantity }}</strong></p> </div> {% endfor %} </div> {% endfor %} </div> </div> The picture contains the current output. What I am trying to achieve is a list of items under each other. -
Backup database from within Docker container
I have multiple Django containers running my backend. One which utilizes Celery Beat for scheduled tasks like database backups. I want to dump my database using the django-dbbackup library. The problem I was facing was that the library uses pg_dump to backup the database obviously which is not installed in my Django environment (and trying to install a new enough version has caused even more problems). Is there a way for my Django container to connect to my PostgreSQL database container, generate a backup, compress it and upload the file to my object storage? I would need the file to be available within my Django container for all that but I can't seem to find a way that would allow me to actually dump the database without having to install Postgres inside my Django container as well. I'm using Postgres 15.3-alpine for my container which is why I couldn't just use the postgres version that was already available in the apt repository. -
Django custom group permission return 401 code as Unauthorized user
I want create user permission based on user group membership. But next code return next error message "Request failed with status code 401". And for authorized user print(request.user) return next line: "AnonymousUser". permission.py: from django.contrib.auth.models import Group from rest_framework import permissions def is_in_group(user, group_name): try: return Group.objects.get(name=group_name).user_set.filter(id=user.id).exists() except Group.DoesNotExist: return False class HasGroupPermission(permissions.BasePermission): def has_permission(self, request, view): print(request.user) required_groups_mapping = getattr(view, "required_groups", {}) required_groups = required_groups_mapping.get(request.method, []) return all([is_in_group(request.user, group_name) if group_name != "__all__" else True for group_name in required_groups]) or (request.user and request.user.is_staff) views.py: from .models import AppOne from .serializers import AppOnesSerializer from rest_framework import generics from scripts.permission import HasGroupPermission class AppOneView(generics.ListAPIView): queryset = AppOne.objects.all() serializer_class = AppOnesSerializer permission_classes = [HasGroupPermission] required_groups = { 'GET': ['group1'], 'POST': ['group1'], 'PUT': ['group1'], } my User Model: class CustomUser(AbstractUser): age = models.PositiveIntegerField(blank=True, null=True) (I tried almost nothing extra, as I'm new one.) -
Confusing Django settings content using manage.py vs call_command
I have a Django command which I can run using manage.py. The command imports django.conf.settings, then I grab Songs from the database to update bits of the settings: from django.conf import settings from music.models import Song class Command(BaseCommand): def handle(self, **options): new_songs = SongSerializer(Song.objects.all(), many=True).data settings.SONGS_TO_EXPORT = new_songs print(settings.SONGS_TO_EXPORT) # ... The confusing behaviour is: When I run the command using manage.py, I can confirm I get a fresh copy of the settings and the UPDATED content of settings.SONGS_TO_EXPORT is printed out. When I run the command in another app using Django's call_command, I get an old (perhaps cached???) version of the settings and the content of settings.SONGS_TO_EXPORT is just old. Even if I run the command with manage.py first, I still get a non-updated version of the settings in the call_command version. My aim is to get the same results with call_command. -
save method or post_save signal is not being called while through model instance of a ManyToManyField is getting created
I have a Post model in my Django app. It has a many-to-many relationship with User model through the UserTag model named user_tags. class Post(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() user_tags = models.ManyToManyField(User, through=UserTag) class UserTag(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True) comment = models.ForeignKey(Comment, on_delete=models.CASCADE, null=True, blank=True) def save(self, *args, **kwargs): print("#### user tagged ##### - save method") print(self.user) return super().save(*args, **kwargs) @receiver(post_save, sender=UserTag) def user_tagged_signal(sender, instance, created, **kwargs): if not created: return print("#### user tagged ##### - post save signal") print(instance.user) When I tag a user to a post as follows: post.user_tags.set(users) or post.user_tags.add(user) UserTang model instance gets created but save method or post_save signal of the UserTag model is not getting called. I want to send notification to the user and remove the notification depending on the creation and deletion of the UserTag instance. Is there anything I'm doing wrong or please suggest me a solution? -
HttpResponseRedirect and other redirect issues
I wrote simple web application, which can allow users upload and download files and make publications. I'm using django 5.0.1 and python 3.10.2. All worked correctly on my localhost server on my pc, but when i uploaded my project to web hosting (timeweb) i noticed that i cant login into admin panel and my account system. I'm getting infinity page loading and nothing. I have redirection from view of adding publication to the view of this publication after uploading and i'm getting the same issue here (publication still creates, but i cant redirect to it). But i can redirect from here to the older publications, so i think there is something with redirection to recently updated data in database. my def add and detail in views.py def detail(request, publication_id): auth = request.user.is_authenticated grade5 = Publication.objects.get(pk=publication_id).grade5 grade6 = Publication.objects.get(pk=publication_id).grade6 grade7 = Publication.objects.get(pk=publication_id).grade7 grade8 = Publication.objects.get(pk=publication_id).grade8 grade9 = Publication.objects.get(pk=publication_id).grade9 grade10 = Publication.objects.get(pk=publication_id).grade10 grade11 = Publication.objects.get(pk=publication_id).grade11 lettera = Publication.objects.get(pk=publication_id).lettera letterb = Publication.objects.get(pk=publication_id).letterb letterv = Publication.objects.get(pk=publication_id).letterv letterg = Publication.objects.get(pk=publication_id).letterg letterd = Publication.objects.get(pk=publication_id).letterd letter = (lettera*"А") + (letterb*"Б") + (letterv*"В") + (letterg*"Г") + (letterd*"Д") grade = (grade5 * "5") + (grade6 * "6") + (grade7 * "7") + (grade8 * "8") + (grade9 * "9") … -
Django - Stripe - Updating Model Field After Successful Purchase?
I’m currently building a gaming app where logged in users purchase our digital coins to play games and unlock features. I have Stripe installed alongside the Stripe webhook and that works correctly so users can currently purchase coins. I can get successful payments and see them through the Stripe application with zero issues. What I want to do next is update the model field named bankroll after a successful payment. So when a logged in user purchases lets say 2,000 coins for $100.00 then the bankroll field gets updated. How can I do that with my current code? I can’t really get this to fully work how I want from what I’ve been testing. The UserInfo model contains basic user information. The Price and Product models are in reference to the Stripe product. The value of coins to the Stripe product is referenced in the credits field in the Price model. The price of each credits is referenced in the price field in the Price model. Screenshots below as well as my code. bankroll admin stripe-product-admin coins modal on front end Any help is gladly appreciated! Thanks! models.py class UserInfo(models.Model): bankroll = models.IntegerField(default=0) def get_display_price(self): return "{0:.2f}".format(self.bankroll / 100) class … -
Javascript Bootstrap Spinner Visible on submit
It's a Django project. I got this Bootstrap spinner in a span in a button: <form method="POST" id="pdfUploadForm" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary" type="submit" id="submitButton"> <span id="spinner-box" class="spinner-border spinner-border-sm not-visible" role="status" aria- hidden="true"></span> Submit... </button> </form> And that CSS. .not-visible { display: none; } I'm removing the class "not-visible" in javascript: document.getElementById('pdfUploadForm').addEventListener('submit', async (e) => { e.preventDefault(); console.log(document.getElementById('spinner-box').classList); document.getElementById('spinner-box').classList.remove('not-visible'); console.log(document.getElementById('spinner-box').classList); document.getElementById('submitButton').innerText = 'Processing...'; From the console log the class is successfully removed. But the spinner is still NOT displaying. And i can't get why... Thanks!! -
(admin.E202) <model> has no ForeignKey to <model> With OneToOne Field Django Admin Tool
I have a small app with these two models: class LocationSpecialNeeds(models.Model): [some fields] class Location(models.Model): [some fields] location = models.OneToOneField(LocationSpecialNeeds, on_delete=models.CASCADE) Which I want to see in the Django admin tool using this code: from django.contrib import admin from .models import Location, LocationSpecialNeeds class LocationSpecialNeedsInline(admin.StackedInline): model = LocationSpecialNeeds can_delete = False @admin.register(Location) class LocationAdmin(admin.ModelAdmin): inlines = [ LocationSpecialNeedsInline, ] Which seems straightforward enough. However, I get the error: <class 'locations.admin.LocationSpecialNeedsInline'>: (admin.E202) 'locations.LocationSpecialNeeds' has no ForeignKey to 'locations.Location'. When I start the app. Isn't a OneToOne a foreign key relationship? What am I missing? -
Choosing frameworks for creating the platform for students
I wanna create a platform as a project for my university. Here are main features: the teacher can create tests and run them at specific times students are limited in time and can pass tests (each test has got it's own time limit) there is an overall student ranking on the home page the teacher can publish the homework What should I choose? I am thinking about Django + React. What would you recommend? -
I can't receive tokens on android app from the django server
I am trying to figure out why I can not receive access tokens on my android app from the django server. The android app structure seems fine to me. Still the issue persists. I tested the server response with postman and it looks fine (I receive both, access and refresh tokens) but on my android app that does not work. I share with you some code snippets hoping someone here could help me. Thank you in advance anybody! LOGIN FUNCTION suspend fun loginUser(userService: UserService, email: String, password: String, context: Context, navController: NavController) { try { val response = userService.loginUser(UserLoginRequest(email, password)).await() if (response.isSuccessful) { val tokenResponse = response.body()!! TokenManager.saveTokens(tokenResponse.accessToken, tokenResponse.refreshToken) withContext(Dispatchers.Main) { navController.navigate(Screen.FeedScreen.route) } } else { withContext(Dispatchers.Main) { Toast.makeText(context, "Login failed: ${response.message()}", Toast.LENGTH_LONG).show() } } } catch (e: Exception) { withContext(Dispatchers.Main) { Toast.makeText(context, "An error occurred: ${e.localizedMessage}", Toast.LENGTH_LONG).show() } } } TOKEN MANAGER package com.example.events.util import android.content.SharedPreferences import android.util.Log import com.example.events.network.NetworkModule import com.example.events.network.RefreshRequestBody import com.example.events.network.RefreshTokenResponse import com.example.events.network.TokenRefreshService import com.google.gson.Gson object TokenManager { private lateinit var preferences: SharedPreferences // Initialise with SharedPreferences fun init(preferences: SharedPreferences) { this.preferences = preferences } val accessToken: String? get() = preferences.getString("access", null) fun isTokenExpired(): Boolean { val expiry = preferences.getLong("expiry", 0) return expiry < System.currentTimeMillis() } … -
How to enable dynamic custom domains
I am a developer for a SAAS web app and excel plugin. With our product, users are able to share outputs of their work with third parties via a browser link. The format of the browser link today is nameofourwebsite.io/titleofoutput. I'm looking to implement two versions of a feature: As a V1, I'd like to enable users to create a custom domain in the form of companyname.website.io/titleofspreadsheet. I am already the owner of the domain website.io. As a V2, (to be implemented at a later date), I'd like for users to be able to bring their own custom domain, similar to the implementation with Stripe (https://docs.stripe.com/payments/checkout/custom-domains). In other words, when a user shares a browser link to the output of their work instead of the link being companyname.website.io/titleofspreadsheet the browser link would be something along the lines of customprefix.companywebsite.com/titleofworkbook. I am not sure how to tackle this problem and I am looking for advice as to the steps we need to take. -
How to ensure changes to variables in .env file reflect in Django project?
I'm encountering an issue in my Django project where changes made to variables in the .env file do not seem to be reflected when I restart the server. Here are the steps I've taken: Verified that the .env file is in the correct location and its name is exactly .env. Restarted the Django development server after making changes to the .env file. Double-checked the syntax of the .env file for any errors or typos. Cleared the cache after making changes to the .env fil (using python manage.py clear_cache) -
In Django, is it possible to use reverse/redirect with a view function (not string) as a to parameter, when using namespaces?
I'm trying to get reverse (via redirect) to work in the context of namespaces and when using view functions. This fails with a NoReverseMatch, somewhat to my surprise. In principle, I'd say that it's out-figurable in an automatic way what I mean. When using this without app_name = ... this works fine. Is this a bug (or simply unsupported)? Or is there a way it could be made to work? # urls.py from django.urls import path from .views import some_other_view, some_view app_name = 'foo_app' # here the app namespace is defined urlpatterns = [ path('some_other_view/', some_other_view), path('some_view/', some_view), # ... ] # views.py from django.shortcuts import redirect def some_other_view(request): return redirect(some_view) # note that the view is simply passed as a function here, not as a string. def some_view(request): # ... actual view here -
Send data from one table to another when instantiated django
What I want is that when creating an instance of the user object the name goes to another table called profile_data but I don't know how to do it, can someone help me? -
Django and django-mssql - problem with rendering ForeignKey field in ModelForm
In my Django application I would like to use 2 databases. First (default one) - sqlite3 and second MS SQL. Since Django don't support MsSQL I'm forced to use 3rd party django-mssql package. I have model with ForeignKey and ModelForm based on this model. The problem is that I get an error "no such table: TLC_OWDP_InstructionParameters" while trying to render ForeignKey form field. It looks like django tries to find the table in wrong database. I tried use PostgreSQL instead of MS SQL and everything works fine. Could someone please help me with this issue? My code below: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'logistyka': { 'ENGINE': 'mssql', 'NAME': 'LOGISTYKA', 'HOST': 'WPLRZD0A', 'PORT': '', 'USER' : '***', 'PASSWORD' : '***', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } models.py class InstructionParameter(models.Model): id = models.AutoField(db_column='id', primary_key=True) instr_number = models.CharField(max_length=30, verbose_name='Numer instrukcji') tab_number = models.SmallIntegerField(verbose_name='Numer tabeli', validators=[MinValueValidator(1), MaxValueValidator(99)]) point_number = models.SmallIntegerField(verbose_name='Numer punktu tabeli', validators=[MinValueValidator(1), MaxValueValidator(99)]) def __str__(self): return f'{self.instr_number} tab.{self.tab_number} p.{self.point_number}' class Meta: verbose_name_plural = 'Instrukcje' managed = False db_table = 'TLC_OWDP_InstructionParameters' class PartParameter(models.Model): id = models.AutoField(primary_key=True) part_number = models.CharField(max_length=30, verbose_name='Numer części') op_number = models.CharField(max_length=4, verbose_name='Numer operacji') instruction_id = models.ForeignKey('InstructionParameter', to_field='id', db_column='instruction_id', … -
one of many python attributes not carrying over to children in GitHub class, with and without Django support
When i subclass my GitHubIssues class (see below), all the children have the expected attributes EXCEPT self.repo_object... when i redeclare it in child classes, it functions as it should... but i shouldn't need to do this if my knowledge of inheritance is correct. class GitHubIssues: class UnknownRepositoryError(UnknownObjectException): ... def __init__(self, repo_name: str, github_key_path: str, data: dict = None): # TODO: test this as standalone more. self.repo_name = repo_name self.repo_obj = None self._IsDjangoForm = None self._GitHubKeyPath = github_key_path self._GitHubKey = None self._IsInIssues = None if not self.IsDjangoForm: self.data: dict = data self.cleaned_data: dict = self.data self.errors: list = [] self.repo_obj = self.GetRepoObject() # other attributes omitted for brevity def GetRepoObject(self): try: g = Github(self.__GitHubKey) for repo in g.get_user().get_repos(): if repo.name == self.repo_name: self.repo_obj = repo return self.repo_obj except BadCredentialsException as e: self.add_error(None, e) except GithubException as e: self.add_error(None, e) except Exception as e: self.add_error(None, e) if isinstance(self.repo_obj, Repository.Repository): pass else: try: raise self.UnknownRepositoryError(404, data=self.repo_obj, message=f"Could not find {self.repo_name}") except self.UnknownRepositoryError as e: self.add_error(None, e) class BugReportForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._issue_added = None if kwargs: if 'repo_name' in kwargs: self.repo_name = kwargs['repo_name'] else: self.repo_name = 'BackflowPreventionValveCatalog' if 'GitHubKeyPath' in kwargs: self._GitHubKeyPath = kwargs['GitHubKeyPath'] else: self._GitHubKeyPath = #redacted path else: … -
I created a new model and registered it to admin.py but when I am running python manage.py makemigrations it showing that no migrations to apply
In models.py: from colorfield.fields import ColorField class colour(models.Model): color=ColorField(format="hexa") def __str__(self): return str(self.id) In admin.py: admin.site.register(colour) When I am running python manage.py makemigrations it says: System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'userauths' isn't unique. You may not be able to reverse all URLs in this namespace No changes detected And when I am running python manage.py migrate it says: System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'userauths' isn't unique. You may not be able to reverse all URLs in this namespace Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Now When I am going to admin pannel there is a table called colour but when I am clicking it there is an no such table: core_colour error