Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-admin fatal error when trying to create files
I installed django simply using pip install und want to create a file, but when I use django-admin, I get an error: Fatal error in launcher: Unable to create process using '"c:\program files\python39\python.exe" "C:\Program Files\Python39\Scripts\django-admin.exe" startproject p1': what is wrong here? All I can read here is, that it is searched for an object that has something to do with python 3.9. I used it, but deinstalled it to install version 3.8, which I am using currently. -
Install Django on puthon 3.8
I try install django on python 3.8 by command pip install django but I get ERROR: Could not find a version that satisfies the requirement django (from versions: none) what can I do? -
Cannot assign “1”: “Plugins.category” must be a “PluginsCategory” instance. Django and ForeignKey
I am trying to save a new record to the database, and an error occurred while writing to the ForeignKey Cannot assign "1": "Plugins.category" must be a "PluginsCategory" instance. What's wrong? models.py class Plugins(models.Model): title = models.CharField(max_length=150, verbose_name='Название') category = models.ForeignKey('PluginsCategory', on_delete=models.PROTECT, related_name='get_category') def get_absolute_url(self): return reverse('urls_view_current_plugins', kwargs={'pk': self.pk}) def __str__(self): return self.title class PluginsCategory(models.Model): title = models.CharField(max_length=150, db_index=True, verbose_name='Наименования категории') def __str__(self): return self.title tags.py def add_plugin_in_db(): plugin = Plugins() plugin.title = 'title' plugin.category = 1 plugin.save(force_insert=True) On the site C:\PythonProject\ServiceCRM3\venv\lib\site-packages\django\db\models\fields\related_descriptors.py, line 215, in __set__ raise ValueError( … ▼ Local vars Variable Value instance <Plugins: Заказы> self <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x000000000438DAF0> value 1 -
Login Django-project
Hello, help me figure out the logic behind the Django ezine. Each student should have many grades in different disciplines. Is there a "tuple" field type in django? -
Python get variable name instead of value
I need to get the variable name instead of the variable value. I have a situation like this: Type1 = 1 Type2 = 2 fields = [Type1, Type2] for field in fields: value = field.__name__ #or something like print(value) Expected result is Type1 Type2 Ty for helping -
Django template run {{ }} without execute
In django template I write <p>"{{sometext}}"</>p. But when it is executed it convert like <p>""</p>. How to avoid this. -
How to pass slug to request.data in list view of Django REST Framework
I have entered a slug in an URL and I want the entered slug as a request.data in some other URL. Specifically, urls.py > router = routers.DefaultRouter() > > router.register(r'courses', CollegeCourseViewSet, > basename='college_course_list') > > urlpatterns = [ > path('api/v1/colleges/<slug:slug>/', include(router.urls)), ] Here I want the college slug as request.data to filter the courses of that college in the ViewSet. views.py > class CollegeCourseViewSet(viewsets.ReadOnlyModelViewSet): > queryset = Course.objects.all() > lookup_field = 'slug' > filter_backends = (SearchFilter, DjangoFilterBackend) > search_fields = 'name' > > def list(self, request, *args, **kwargs): > try: > queryset = self.queryset > queryset = queryset.filter(courses_colleges__college__slug=request.data) > return Response(CourseSerializer(queryset, many=True).data, status=status.HTTP_200_OK) > except queryset is None: > raise Http404 But the request.data is empty when outputted. Is there any specific method to send the request.data to the list function in ViewSet? Thanks in advance. -
Django post save and overwriting not working in m2m field
This is my model : class Size(models.Model): size = models.IntegerField() price = models.FloatField() def __str__(self): return f"{self.size} - {self.price}" class ItemSold(models.Model): dimension_and_price = models.ManyToManyField(Size) and many more... and after I save the model I want to do some logic, so I tried using Django post_save and overwriting save method but they didn't work for me, as m2m field is empty. Then after reading docs and articles I learnt about m2mchange and the problem with that is that it runs function two times def calculate_price(sender, instance,action="post_add", *args, **kwargs): print("It runs two times") m2m_changed.connect(calculate_price, sender=ItemSold.dimension_and_price.through) Please help PS Sorry for bad English -
sqlalchemy relations- sqlalchemy.exc.InvalidRequestError:
I have 2 files in models directory: i want Relation between Member and Bot i cant import Bot to member.py because of Circular Dependencies member.py : from sqlalchemy import Column, String, Date, Integer, select, func, extract from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import column_property, relationship class Member(Base): __tablename__ = 'member' id = Column(Integer, primary_key=True, autoincrement=True) first_name = Column(String) last_name = Column(String) bots = relationship('Bot', back_populates='owner') and bot.py : from sqlalchemy import Column, String, Integer, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from models.member import Member class Bot(Base): __tablename__ = 'bot' id = Column(Integer, primary_key=True, autoincrement=True) title = Column(String) owner_id = Column(Integer, ForeignKey(Member.id)) owner = relationship(Member, back_populates='bots') this error: Traceback (most recent call last): File "/home/hmn/.virtualenvs/tost/lib/python3.8/site-packages/sqlalchemy/ext/declarative/clsregistry.py", line 322, in _resolve_name rval = d[token] File "/home/hmn/.virtualenvs/tost/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 729, in __missing__ self[key] = val = self.creator(key) File "/home/hmn/.virtualenvs/tost/lib/python3.8/site-packages/sqlalchemy/ext/declarative/clsregistry.py", line 301, in _access_cls return self.fallback[key] KeyError: 'Bot' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<input>", line 1, in <module> File "<string>", line 2, in __init__ File "/home/hmn/.virtualenvs/tost/lib/python3.8/site-p util.raise_( File "/home/hmn/.virtualenvs/tost/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 182, in raise_ raise exception sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Member->member, expression 'Bot' failed to locate a name ('Bot'). If … -
Django REST: How do i return SimpleJWT access and refresh tokens as HttpOnly cookies with custom claims?
I want to send the SimpleJWT access and refresh tokens through HttpOnly cookie. I have customized the claim. I have defined a post() method in the MyObtainTokenPairView(TokenObtainPairView) in which I am setting the cookie. This is my code: from .models import CustomUser class MyObtainTokenPairView(TokenObtainPairView): permission_classes = (permissions.AllowAny,) serializer_class = MyTokenObtainPairSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class() response = Response() tokens = serializer.get_token(CustomUser) access = tokens.access response.set_cookie('token', access, httponly=True) return response It's returning this error: AttributeError: 'RefreshToken' object has no attribute 'access' The serializer: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): print(type(user)) token = super().get_token(user) token['email'] = user.email return token But it's just not working. I think I should not define a post() method here like this. I think if I can only return the value of the get_token() function in the serializer, I could set it as HttpOnly cookie. But, I don't know how to do that. How do I set the access and refresh tokens in the HttpOnly cookie? -
Getting information of a model from another model in django
My project is simply a patient will upload an image of his latest medical report that includes blood pressure , hemoglobin and so on , the data will be extracted from the image using ocr . later these data should be shown in a dashboard This is the model for the image upload: models.py class ImageUpload(models.Model): imageTitle = models.CharField(max_length = 150) image = models.ImageField(upload_to=media , max_length=100) created = models.DateTimeField(auto_now=True, auto_now_add=True) and this is the model that will be created as an instance of the last model created: class ImageData(model.Model): haemoglobin = models.FloatField() bloodPressure = models.FloatField() mch = models.FloatField() where haemoglobin , bloodPressure , mch are the data to be extracted . So I have two questions: 1) how can I create an instance of ImageData model as an instance of ImageUpload is created ? 2) I have already a function for the ocr , I tested it manually , however I want to know what is the best way to put this function within this code , foe example is it better to write make this function a method in the ImageUpload class ? for example:- class ImageUpload(models.Model): --------- def get_Image_data(image):#using ocr --------- return text -
Api_key in django rest framework
I want to implement django rest framework that have connection to bot(machine that write by python ) , now I generate api key in my admin panel , but I don't know how can I use it in my bot? -
Django + ReactJS - How to get CSRF cookie for forms
I'm new to Django and ReactJS and am trying to do something fairly standard. But even after reading many blogs and stack overflow questions, I cannot figure out what I am doing differently / wrong? I have a Django server running on localhost:8000 and ReactJS on localhost:3000 The ReactJS has a simple sign-in form. The form will need a CSRF token to do a POST request. But I keep getting a CSRF Cookies not set message. I have installed CORS middleware with the following settings CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ['http://localhost:3000'] # CORS_EXPOSE_HEADERS = ['Set-Cookie'] # CSRF_TRUSTED_ORIGINS = ['localhost:3000/'] I am not using rest_framework because it seems that it is only needed to serialise objects to JSON and define routes. As I have existing methods and routes for those, I assumed that rest_framework would not be needed I ping the server initially as follows @ensure_csrf_cookie def ping(request): return JsonResponse({'ping': True}, status = 200) As a result, I see a Set-Cookie in the response header. So far, so good. But I cannot access this header - and hence the cookie in ReactJS. CORS_EXPOSE_HEADERS also doesn't seem to work. Plus, it seems Set-Cookie is one of those forbidden headers that can't be … -
Customize django-allauth social login and call back URL (redirect them through a front-end service )
When I sign up/sign in with my social account using django-allauth like http://localhost:8000/accounts/google/login/ Now after doing authentication, Google redirect us back to the below callback URL as http://localhost:8000/accounts/microsoft/login/callback/ I want to change the above URLs to be redirected to the frontend service and then redirect it from there to our backend server. Is there a way around to achieve this? Because due to security reasons I only our frontend server to interact with our back, not any other third part. -
Is there a way to update a foreign key field using an SQL Update Query in Django
I have two classes, and I am attempting to move a field from one to the other as efficiently as possible. The database is large, so it's ideal if we can use an SQL Update query within Django or a direct SQL query. My database is PostgreSQL. Class Order(models.Model): name = models.TextField(null=True, blank=True) address = models.ForeignKey(Address, on_delete=models.PROTECT) Class Address(models.Model): name = models.TextField(null=True, blank=True) I know I can do this manually, but I was hoping to be able to run an SQL Update query like so: Order.objects.all().update(address__name=F('name')) But I'm not able to update a foreign key field using the update command. Any suggestions for an alternative either in Django or directly in SQL - as opposed to just writing out the following - is appreciated. for order in Order.objects.all(): address = order.address address.name = order.name address.save() -
python flask base.html doesn't display {{user.username}
Here is my base.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> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="{{ url_for('dashboard') }}">SOM</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Dashboard</a></li> <li><a href="#">Settings</a></li> <li><a href="#">Profile</a></li> <li><a href="{{ url_for('logout') }}">Log Out</a></li> </ul> <form class="navbar-form navbar-right"> <input type="text" class="form-control" placeholder="Search..."> </form> </div> </div> </nav> </body> </html> profile.html: {% extends "base.html" %} <h3>{{user.username}}</h3> When I go to the profile page it doesn't display the username but if I type something else there like <h1> Hello </h1> I can see it. -
How to pickle sklearn in Django cache
I would like to cash a my model which comprises of sklearn and a tensorflow models. class KNN: def __init__(self, modelName, neighbors=None, metric="cosine"): self.model = NearestNeighbors(n_neighbors=self.neighbors, metric=metric) self.vg99 = tf.keras.applications.VGG19(weights='imagenet', include_top=False, input_shape=shape_img) I am using the following code to cache it in my Django app: model_name = 'knn_vg99' knn = KNN(model_name) cache_key = model_name cache.set(cache_key, knn) And I am getting the following error: File "/home/projects/searchengine/searchengineenv/lib/python3.7/site-packages/django/core/cache/backends/filebased.py", line 54, in set self._write_content(f, timeout, value) File "/home/projects/searchengine/searchengineenv/lib/python3.7/site-packages/django/core/cache/backends/filebased.py", line 44, in _write_content file.write(zlib.compress(pickle.dumps(value, self.pickle_protocol))) TypeError: can't pickle weakref objects I have tried both FileBasedCache as well as LocMemCache cache methods. Are there any solutions to pickle my model in such a way? Many thanks for your support -
In the Django project,how to rebuild the model classes by migrations file?
In the Django project, if the model folder files are deleted, is it possible to use the migrations folder files to rebuild the model classes? -
Deploying django rest and react app on aws (elastic bean / S3)
I'm trying to deploy my django rest + react app on AWS, but I have a hard time collecting info how to achieve this. Following this tutorial: https://www.newline.co/fullstack-react/articles/deploying-a-react-app-to-s3/ seems lika a good option for deploying react front. What is left for me is django and postresql DB. I've read about deplying copuled django and react on EC2 (as the simpler option), but I would like to use S3. This How to Deploy Django Rest Framework and React on AWS answer provide some info, but I'm not able to go any further. Should I separate them to different buckets, or use other AWS tools for django and database ? Any artcles, tutorials will be very much appreciated! -
What is equivalent of *Laravel Model's Global Scope* in Python or Django?
In general when data is queried using App\Models in laravel, we have a luxury to apply filters using Model Level Global scope and Local Scope. Is there any equivalent in "Python"? May be in "Django"? Or may be in models.Model ? -
Django debug_toolbar not working if DEBUG=False
I followed the installation process from the django_toolbar doc and at no point it's indicated that DEBUG must be set to True. When I have DEBUG set to True the debug_toolbar works but when it's set to False it doesn't. I'm working with Docker and I found a piece of code to make it work in the first place with DEBUG=True but not in this configuration: DEBUG = False ALLOWED_HOSTS = ["localhost", "127.0.0.1"] [...] INSTALLED_APPS.append("debug_toolbar") MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware") INTERNAL_IPS = ["127.0.0.1"] import socket ip = socket.gethostbyname(socket.gethostname()) INTERNAL_IPS += [ip[:-1] + '1'] -
Django form DateTimeField : select a valid date and a valid time
I have a form with datetimefield format : class DateTimeInput(forms.DateTimeInput): input_type = "datetime-local" class myform(forms.ModelForm): myfield= forms.DateTimeField(input_formats = ["%d/%m/%Y %H:%M"], widget=DateTimeInput(attrs={ 'class':'form-control'})) but I have still the error "select a valid date and a valid time". My input look like : 14/02/2021 15:59 -
Error: ModuleNotFoundError: No module named 'members.urls'
I tried to start a app so that I can create a Login for my blog but I came by this error. So I thought to post a question in stack over flow. I hope yu can take some time to answer my question. It says there is no module named members.urls. This is the trace back error, Traceback (most recent call last): File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\simpleblog\virt\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\simpleblog\virt\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\simpleblog\virt\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\simpleblog\virt\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\simpleblog\virt\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\simpleblog\virt\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\simpleblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\simpleblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line … -
How to get books of the the same author in Django
I am developing an online Book Store. Here is the models: class Author(models.Model): name = models.CharField(max_length=250, unique=True) class Publisher(models.Model): name = models.CharField(max_length=250, unique=True) class Book(models.Model): author = models.ManyToManyField(Author, related_name='authors') publisher = models.ForeignKey(Publisher, on_delete=models.PROTECT, blank=True, null=True) isbn13 = models.BigIntegerField(unique=True) name = models.CharField(max_length=500) ... Here is the View: class AuthorsListView(ListView): model = Author context_object_name = 'authors_list' template_name = 'authors_list.html' paginate_by = 500 class AuthorBooksListView(ListView): model = Book context_object_name = 'author_books' template_name = 'author_books.html' def get_queryset(self, **kwargs): author_id = Author.objects.get(pk = self.kwargs['pk']) qs = super().get_queryset(**kwargs) return qs.filter(author = author_id) def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet context['author'] = Author.objects.get(pk = self.kwargs['pk']) return context class PublishersListView(ListView): model = Publisher context_object_name = 'publishers_list' template_name = 'publishers_list.html' paginate_by = 500 class PublisherBooksListView(ListView): model = Book context_object_name = 'publisher_books' template_name = 'publisher_books.html' paginate_by = 20 def get_queryset(self, **kwargs): publisher_id = Publisher.objects.get(pk = self.kwargs['pk']) qs = super().get_queryset(**kwargs) return qs.filter(publisher = publisher_id) def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet context['publisher'] = Publisher.objects.get(pk = self.kwargs['pk']) return context class BooksListView(ListView): model = Book context_object_name = 'books_list' template_name = 'books_list.html' paginate_by = 100 class … -
trying to use username in urlpattern to give every user a unique link
this my approach if you know how to do it please help my views.py def profile(request, username): return render(request, 'profile.html') my urls.py from django.conf.urls import url from django.urls import path from django.contrib.auth import views as auth_views from . import views # Template Urls! app_name = 'accounts' urlpatterns = [ path('Skolar/',views.base, name= 'base'), path('Register/',views.register,name='register'), path('login/', views.my_login_view, name='login'), path('logout/',views.user_logout,name='logout'), path('<slug:username>',views.profile, name='profile'), path('EditProfile/',views.update_profile,name='editprofile'), ] error showing Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['(?P<username>[-a-zA-Z0-9_]+)$'] in my html i use <a class="dropdown-item" href="{% url 'accounts:profile' %}">My Account</a>