Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django FieldError: Unsupported lookup 'kategorie' for IntegerField or join on the field not permitted
I have a Django Table with Crispy Filter and I would like to filter in Data table based on Category. But I am getting FieldError. I tried to define my filter field by this way in filters.py: kategorie = django_filters.CharFilter(label="Kategorie", field_name="ucet__cislo__kategorie__jmeno", lookup_expr='icontains') And I have following structure of models in models.py: class Data(models.Model): ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE, null=True, blank=True) class Ucty(models.Model): cislo = models.IntegerField("Účet", blank=True, null=True) class Mustek(models.Model): ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE) kategorie = models.ForeignKey(Kategorie, on_delete=models.CASCADE) class Kategorie(models.Model): jmeno = models.CharField("Kategorie", max_length=20, blank=True, null=True) Any idea how to correct field_name definition in filter? -
Field value is not displayed for editing in the form Django?
views.py dicfacultets = DicFacultets.objects.all() disfacultetsedit = DicFacultets.objects.get(id=id) form = FacultetsForm(request.POST, instance=disfacultetsedit) if request.method == 'GET': return render(request, 'tao/dicfacultetsedit.html', {'dicfacultets': dicfacultets, 'form': FacultetsForm(), }) else: try: if form.is_valid(): disfacultetsedit = form.save(commit=False) title = request.POST.get('title') disfacultetsedit.title = title disfacultetsedit.save() return redirect('dicfacultets') except TypeError: return render(request, 'tao/dicfacultets.html', {'dicfacultets': dicfacultets, 'error': 'error', 'form': form, }) return render(request, 'tao/dicfacultets.html', {'dicfacultets': dicfacultets, }) html {% for fac in dicfacultets %} ... # *call modal window for editing* <a href="facultetsedit/{{ fac.id }}" class="on-default edit-row" data-toggle="modal" data-target="#facultetsedit{{fac.id}}"><i class="fa fa-pencil"></i></a> # next call form method="POST" action="{% url 'facultetsedit' id=fac.id %}"> {{ form }} form in modal window when a modal window is called, the field is empty, but editing and saving work -
reverse lazy error NoReverseMatch at django DeleteView
I'm trying to return back to patient analyses list after deleting 1 analysis. But can't manage proper success url So this is my model: class PatientAnalysis(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) analysis_date = models.DateTimeField(help_text = "Разделяйте даты точками! Используйте '/' или '-'") # analysis_type = models.IntegerField(choices = ANALYSIS_CHOICES) #перевести в таблицу analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1) analysis_data = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return f"{self.patient}" def get_analysis_type(self): return f"{self.analysis_type}" def get_absolute_url(self): return reverse('journal:patient_analysis', kwargs={'hist_num_slug':self.patient.pk}) class Meta: unique_together = ('analysis_date','analysis_type',) Here's the class for list all analyses per patient class PatientAnalysisListView(ListView): model = PatientAnalysis template_name = 'journal/patient_analysis.html' context_object_name = 'analysis' def get_context_data(self, *, object_list=None, **kwargs): <...> return context def get_queryset(self): return PatientAnalysis.objects.filter(patient__hist_num=self.kwargs['hist_num_slug']).order_by('-analysis_date') And here i stuck with next code: lass PatientAnalysisDeleteView(DeleteView): # Form --> Confirm Delete Button # model_confirm_delete.html model = PatientAnalysis success_url = reverse_lazy('journal:patient_analysis', kwargs={'key': model.patient}) And getting error: `NoReverseMatch at /journal/patientanalysis_delete/49 Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_]+)\Z'] Request Method: POST Request URL: http://127.0.0.1:8000/journal/patientanalysis_delete/49 Django Version: 4.1.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_]+)\Z'] Exception Location: /home/verts/.local/lib/python3.10/site-packages/django/urls/resolvers.py, line 828, in _reverse_with_prefix Raised during: journal.views.PatientAnalysisDeleteView Python Executable: … -
Add menu items in wagtail ModelAdminGroup
I want to add non ModelAdmin items in a ModelAdminGroup as for example a MenuItem, like this: MenuItem('A title', '/some_url/', icon_name='doc-full-inverse', order=1) But I could not found any hints neither in Wagtail documentation nor on stackoverflow. My ModelAdminGroup looks like this class MyModelAdminGroup(ModelAdminGroup): menu_label = "Some stuff" menu_icon = "fa-suitcase" menu_order = 1 items = (Model1Admin, Model2Admin) I try to do this: class MyModelAdminGroup(ModelAdminGroup): menu_label = "Some stuff" menu_icon = "fa-suitcase" menu_order = 1 items = (Model1Admin, Model2Admin, MenuItem('A title', '/some_url/', icon_name='doc-full-inverse', order=1)) Ad some other idiotic stuff But all all crashed ... I finally found an easy solution. I just write it bellow just in case it could help the community other people -
Responding with a custom non simple object from a Django/Python API to the front
I'm a newbie building APIs with django/python I built a dictionary object (it has lists in it), and I want to send it to the front through one of the responses: JsonResponse, HttpResponse, etc. What could be the way to do it? I tried with several of them without a good response, or I get an error, or a bad response Thanks in advance Rafael -
how can I response to the front a custom-built object in Django/Pyton
I’m newbie in building APIs with Django/Python I built an object in the server side, and I want to send it to the front. I built it on the fly, without a class. it's a dictionary object with arrays in it def whole_menu(request, restaurant_id): menu = {} menu["restaurant"] = Restaurant.objects.get(id=restaurant_id) menu["categories"] = [] category_serializer = Category.objects.filter(restaurant=restaurant_id) category_index = 0 for category in category_serializer: menu["categories"].append({}) menu["categories"][category_index]["name"] = category.name menu["categories"][category_index]["description"] = category.description menu["categories"][category_index]["image_url"] = category.image_url menu["categories"][category_index]["dishes"] = [] dish_serializer = Dish.objects.filter(category=category.id) dish_index = 0 for dish in dish_serializer: menu["categories"][category_index]["dishes"].append({}) menu["categories"][category_index]["dishes"][dish_index]["name"] = dish.name menu["categories"][category_index]["dishes"][dish_index][ "description" ] = dish.description menu["categories"][category_index]["dishes"][dish_index][ "price" ] = dish.price menu["categories"][category_index]["dishes"][dish_index][ "image_url" ] = dish.image_url dish_index = dish_index + 1 category_index = category_index + 1 print(menu) return HttpResponse(menu) I tried sending the object with JsonResponse, HttpResponse and even rest_framework.response.Response, but it won’t work Whit this approach I get restaurantcategories (???) What could be the way to send a custom-built object to the front? -
on_delete oprator in Django framework
i want to build a ModelViewSet class that recive an id from url for instance localhost/id and based on that id i can either show the object with matching id or delete the object but im having trouble passing the id in the url my view is like this: class delete_or_show_View(viewsets.ModelViewSet): serializer_class = ObjectSerializer permission_classes = [permissions.IsAuthenticated] http_method_names = ['get', 'delete'] def get_queryset(self,mid): #Show the object def destroy(self, mid=None): #delete the object and my url is like this router.register('(?P<object_id>\d+)', views.delete_or_show_View, basename='do_stuff') Im getting errors for missing aruguments or that the delete method is not allowed please if someone can guide me how i can do this properly and explain it will be great thank you -
what does .models mean in djagno?
I am trying to import a class named 'Questions' from my models.py to admin.py from .models import Questions I don't understand why we have to use a period in '.models', what does it mean and what exactly is it pin pointing to? I tried this combinations but it was no avail from models import Questions from Model.models import Questions -
How to save all incoming emails to a model
I want to save all incoming emails to a django model. django-mailbox has an email table but is inactive. django-anymail's AnymailInboundMessage looks like it would work well but it is not a django model class, just a generic python object for processing incoming emails, not storing them. I know I could cut and paste the source from AnymailInboundMessage into a django model class and then turn the members into Django fields, but I am wondering if there is a way to wrap or subclass a python class such as AnymailInboundMessage into a django model. TIA -
Is there a way to run a discord bot and django code through heroku?
Everything seems to work until i get to the build part on heroku, -----> $ python manage.py collectstatic --noinput Starting up None shards... 130 static files copied to '/tmp/build_a4988370/staticfiles', 8 unmodified, 361 post-processed. Connected to shard 0 Shard 0 ready -----> Timed out running buildpack Python ! Push failed This is what happens it runs the website code and it starts by bot (shard-ed bot), and then it wont continue the build and it just fails, does anyone have any ideas, here is some of my code #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import asyncio from threading import Thread def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': from discordbot.main import _main loop = asyncio.new_event_loop() loop.create_task(_main()) Thread(target=loop.run_forever).start() ^manage.py def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? … -
Django show loading indicator if no validation errors
Im doing a webapp with Django and I want to display a loading indicator while I wait for my Python function to do its calculations. However, the loading indicator gets displayed (forever) if there are input validation errors. How do I check if there are validation on submit and avoid the loading indicator displaying if there are input errors? My code below. HTML template: <div class="loader" style="display:none"></div> <form method="POST" id="content" ...> ... <div>{{ form.visible_fields.0 }} </div> <div class="form-errors errorlist"> {% for error in form.visible_fields.0.errors %} <div>{{error}}</div> {% endfor %} </div> ... <button type="submit" onclick="loading()">Submit</button> JS function in template: function loading(){ $(".loader").show(); $("#content").hide(); } -
Select from a dropdown list of users to assign them to a certain Room
I'm trying to create a dropdown list of users that can be changed and updated if the admin user desires. I am able to see the dropdown list of users but when I go to create the Room and try to select a user, it doesn't get saved and that field remains blank. I used a ModelChoiceField in my forms.py file to create the dropdown list of users. I think its because I didn't call it correctly in the views.py but I'm not sure how to proceed. Any help is much appreciated Here is my code so far forms.py class RoomForm(ModelForm): userList = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: model = Room fields = '__all__' exclude = ['host', 'participants'] views.py @login_required(login_url='login') def createRoom(request): form = RoomForm() topics = Topic.objects.all() if request.method == 'POST': topic_name = request.POST.get('topic') topic, created = Topic.objects.get_or_create(name=topic_name) Room.objects.create( host=request.user, topic=topic, userList = request.POST.get('userList'), name=request.POST.get('name'), status=request.POST.get('status'), priority=request.POST.get('priority'), type=request.POST.get('type'), description=request.POST.get('description'), ) return redirect('home') context = {'form': form, 'topics': topics} return render(request, 'room/room_form.html', context) @login_required(login_url='login') def updateRoom(request, pk): room = Room.objects.get(id=pk) form = RoomForm(instance=room) topics = Topic.objects.all() if request.user != room.host: return HttpResponse('You are not allowed here!!') if request.method == 'POST': topic_name = request.POST.get('topic') topic, created = Topic.objects.get_or_create(name=topic_name) room.name = request.POST.get('name') room.topic = … -
Django ORM. Check that sum of additional field of m2m relation model equals 100
I want to implement a check on this relation, to ensure that all ticket's weight in sum gives me 100. class PortfolioTicker(models.Model): """ Helper model for M2M relationship between Tickers and Portfolios """ portfolio = models.ForeignKey(Portfolio, models.PROTECT, related_name="tickers") ticker = models.ForeignKey(Ticker, models.PROTECT) weight = models.FloatField(null=False) def __str__(self) -> str: return f"{self.portfolio} {self.ticker} {self.weight}" -
Django on Railway
I have fully tested on localhost Django app. When hosted on Railway I cannot login to app or admin. It is showing all migration ok, no database configuration errors, but when trying to login it is showing wrong user/password. Any ideas, please? Checked for errors but it is not showing any. -
Calculating functions with python / django
I'm building a python / django portfolio and i'm having a very hard time with one of my Gym / BMI calculator. I'm trying to have a user input their current Weight and Height, so they can have a BMI result that will be visible from the frontend, and then POST and saved from the Backend models. I just don't know how to include a .py class that i created that will allow the user to input those details from the models and have calculation done in the frontend from the input textfield. Please help...:-) ` from django.db import models # Create your models here. (<-- This is my Model, where i'll save the calculation) class BMI(models.Model): Name = models.CharField(max_length=50) Surname = models.CharField(max_length=50) Weight = models.IntegerField() Height = models.IntegerField() def __str__(self): return self.Name # Create your forms here. (<-- This is my form, where user will be inputting their Weight and Height) from django import forms from django.forms import ModelForm from . models import BMI class BMIForm(ModelForm): class Meta: model = BMI fields = ['Weight', 'Height'] ` from django.shortcuts import render from . models import BMI from . forms import BMIForm # Create your views here. def Home(request): BMIOutcome = … -
How can I acces to my AWS S3 bucket in django?
I am working for the first time with aws s3, where I have images to upload from the django admin, everything works perfect on localhost, but once deployed the images are uploaded but not displayed on the web My setting.py AWS_ACCESS_KEY_ID = 'my acceskey' AWS_SECRET_ACCESS_KEY = 'my secret key' AWS_STORAGE_BUCKET_NAME = 'mybucketname' AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} STATIC_LOCATION = 'static' PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'portfolio.storages.MediaStore' My models class Project(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) link = models.CharField(max_length=250) another_link= models.CharField(max_length=250, null= True, blank=True) image = models.ImageField(upload_to='media/') My views def project(request): projects = Project.objects.all().order_by('-id').values() return render(request, "works.html", {"projects": projects}) My template {% for project in projects %} {% csrf_token %} <div class="row"> <div class="col-md-12 col-md-offset-1"> <div class="row"> <div class="col-xs-12 col-md-6"> <h3>{{project.name}}</h3> <p style=> {{project.description}} </p> <a href="{{project.link}}" target="_blank" class="btn btn-default">Source Code</a> <a href="{{project.another_link}}" target="_blank" class="btn btn-default">See Live</a> </div> <div class="col-xs-6 col-md-4"> <img src="{{project.image.url}}" width="360" height="200" > </div> </div> </div> </div> {% endfor %} In the Html not return a asw link, return this <img src="" width="360" height="200"> Images are loaded perfectly in the S3 bucket but are not displayed in the HTML. -
How to convert excel file to json in specific format
I need a specific JSON output from excel in order to insert data to my database. Right now, the input must come from an Excel table. This is the output I want [ { "model": "client.Restaurant", "pk": 1, "fields": { "name": "KOPITAN CLASSIC WHITE COFFEE", "description": "An ideal place for students and employees to release stress.", "location_lon": 100.481, "location_lat": 5.17818, "operating_hours_start": "10AM", "operating_hours_end": "10PM", "owner_id": 18, "image_url": "kopitanClassic.jpg" } } ] This is the output that I get from using online excel to json converter. [ { "name": "KOPITAN CLASSIC WHITE COFFEE", "description": "An ideal place for students and employees to release stress.", "location_lon": 100.481, "location_lat": 5.17818, "operating_hours_start": "10AM", "operating_hours_end": "10PM", "owner_id": 18, "image_url": "kopitanClassic.jpg" } ] -
how to set foreign by post method in django?
models.py class Courses(models.Model): course_name=models.CharField(max_length=50) course_price=models.IntegerField() class Exam(models.Model): exam_name=models.CharField(max_length=101) course=models.ForeignKey(Courses,on_delete=models.CASCADE,default='python') exam_time=models.DateTimeField() views.py def Examadd(request): mycourses = Courses.objects.all() context = {'mycourses': mycourses} if request.method == 'POST': newexam = request.POST.get('examname') course = request.POST.get('courses') examtime = request.POST.get('time') new = Exam.objects.create(exam_name=newexam,course=course,exam_time=examtime) new.save() messages.success(request, "Course created successfully") return redirect('Courselist') return render(request,'addexam.html',context addexam.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Add New Exam</h1> <form method="post"> {% csrf_token %} <label>Examname:</label> <input type="text" name="examname"> <label>Course:</label> <select name="courses"> {% for i in mycourses %} <option value={{i.id}}>{{i.course_name}}</option> {% endfor %} </select> <label>Exam time and date:</label> <input type="text" name="examtime"> <button type="submit">Add</button> </form> </body> </html> I am doing a project elearning.I want a dropdown list with courses and pass its ids to Exam table.course id is a foreign key.I want to pass the courseid to course column in Exam table.By this code I gets error as,Cannot assign "'1'": "Exam.course" must be a "Courses" instance. -
How to save a wish icon checked after page refresh -Django
Trying to keep selected icon in product cards active after page refresh when the user refresh the page I want that the icon to remain a full heart and not an empty heart. How could I do that? views.py @login_required def add_wishlist (request): if request.is_ajax() and request.POST and 'attr_id' in request.POST: if request.user.is_authenticated: data = Wishlist.objects.filter(customer = request.user,product_id= int(request.POST['attr_id'])) if data.exists(): data.delete() else: Wishlist.objects.create(customer= request.user,product_id = request.POST['attr_id']) else: print("No Product is Found") return redirect("products:product_all") product_all.html <div id='alCarrito'class="like-container"> {% if product in wishlisted_list %} <span class="like heart " id="id" attr_id="{{product.id}}" action_url="{% url 'products:add_wishlist' %}"> <i class="fas fa-heart"></i> </span> {% else %} <span class="like" id="id" attr_id="{{product.id}}" action_url="{% url 'products:add_wishlist' %}"><i class="far fa-heart"></i></span> {% endif %} </div> wishlist.js $(document).ready(function(){ $(".like").click(function(){ var attr_id = $(this).attr('attr_id') var action_url = $(this).attr('action_url') var that = $(this) $.ajax({ url: action_url, type: "POST", data: {'attr_id': attr_id }, headers: { "X-CSRFToken": $.cookie("csrftoken") }, success: function (response) { console.log("Success") that.toggleClass("heart"); }, }); }); }); -
Django get_queryset has different signature for Admin and Generic views, how to prevent code duplication
I would like to write simple code to filter records in view based on request information (eg. organization the user belongs to). I started to implemented it as Mixin for Admin views. class OrganizationPermissionMixin: def get_queryset(self, request): query = super().get_queryset(request) if request.user.is_superuser: return query return query.filter( organization__in=request.user.organization_set.all() ) This works fine but when I tried to apply this Mixin on Generic views, I have a signature error as there is no request parameter passed to the get_queryset method: TypeError: OrganizationPermissionMixin.get_queryset() missing 1 required positional argument: 'request' If I adapt the Mixin to: class OrganizationPermissionMixin: def get_queryset(self): query = super().get_queryset() if self.request.user.is_superuser: return query return query.filter( organization__in=self.request.user.organization_set.all() ) It works for generic views such as ListView but now it indeed breaks for ModelAdmin view: OrganizationPermissionMixin.get_queryset() takes 1 positional argument but 2 were given This inconsistency in signature is somehow very frustrating because it requires to duplicate code simply because request passing mechanism is different between Generic and Admin views. My question is: how can I make this Mixin works both for Generic and Admin views. Is there something ready for that in Django? Is it normal it behaves like this or is it an unfortunate design choice? -
I am getting following error when try to upload Django project to Heroku
When I try to upload my Django project to Heroku I am getting following error Heroku Push error Could you please tell me what is the problem and how to resolve this Thank in advance tried to run push command multiple time change the python runtime in runtime.txt file switch to different Heroku instance -
nginx: [emerg] "http" directive is not allowed here in /etc/nginx/sites-enabled/default:22
whenever I tried to enter the code above in the Nginx config file I found this error.which is nginx: [emerg] "http" directive is not allowed here in /etc/nginx/sites-enabled/default:22. I tried in HTTP tag but can't solve it enter image description here -
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable what you said in the previous question doesn't work
I can not run the project, I did what I was told in README.md as directed, but still gives an error. The Output is: Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\environ\environ.py", line 403, in get_value value = self.ENVIRON[var_name] ~~~~~~~~~~~~^^^^^^^^^^ File "<frozen os>", line 678, in __getitem__ KeyError: 'SECRET_KEY' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\new-folder\manage.py", line 21, in <module> main() File "C:\new-folder\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\base.py", line 93, in wrapped saved_locale = translation.get_language() ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\utils\translation\__init__.py", line 210, in get_language return _trans.get_language() ^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\utils\translation\__init__.py", line 65, in __getattr__ if settings.USE_I18N: ^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\conf\__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File … -
Django unique slug field for two or more models
I have such structure: class Category(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE ) slug = models.SlugField(max_length=255, null=False, unique=True) class Product(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) to_category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True, ) slug = models.SlugField(max_length=255, null=False, unique=True) I have created one category with slug "test". When I try to create new category with slug "test" I got warning message and it is Ok. But If I try to create product with slug "test" I dont have warning and this is not good in my case. Is there a solution or method to validate slug field for uniqueness with Product and Category model? -
PyCharm 2022.1.2 does not hit the debug breakpoint with Django
I can't get Python debugger to work on PyCharm 2022.1.2 with Django 4. When I set the breakpoint inside the view function and then call this view in the browser, nothing happens when started in debug mode... breakpoint_selected However breakpoint is hit when I set it for import. breakpoint_hit I have 2 configurations, one for Python and one for Django Server, both don't work. config1 config2 Went through numerous JetBrains tickets with people reporting similar problem but didn't find the solution there. Also tried creating second run configuration, for Python instead Django Server, but this also didn't help.