Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to reflect DB migrations from django application to DB in docker container running postgres DB
I have tried to do makemigrations and then migrate changes that I have made in models.py, to be accurate, I have made changes in the field type of a table, from docker interactive environment but changes are not reflected in the database. Even if I delete a table from a database and again try to migrate, the table does not appear. Is there some best practice or methods that is need to done for DB migrations for django in a docker container. -
Build Django URL for export_selected_objects. Example function out of the official django documentation
I am trying to build an URL that matches the redirect out of this function: def export_selected_objects(modeladmin, request, queryset): selected = queryset.values_list('pk', flat=True) ct = ContentType.objects.get_for_model(queryset.model) return HttpResponseRedirect('/export/?ct=%s&ids=%s' % ( ct.pk, ','.join(str(pk) for pk in selected), )) That is what I have tried: from django.urls import path, re_path from . import views urlpatterns = [ re_path(r'^export/(?P<ct>[0-9]{2})/(?P<ids>[0-9]{4})/$', views.test), path('export/<int:ct><int:ids>/', views.test), path('export/<int:ct>/<int:ids>/', views.test), path('export/<ct><ids>/', views.test), ] But none of these match. Error Message Could someone give me a hint about what I'm missing here? Thanks a lot! Sebastian -
Adding a custom header 'FOO' to Django Rest Framework APIClient
For an application that uses SSO for login I have implemented a AuthBackend with Django Rest Framework. This custom AuthBackend class checks for the X-USERID present in the headers and based on that returns the user instance. I have added permission classes to the views for verifying the authenticated users. In order to add unit tests to the code the APIClient must enable us to add custom header like {'FOO': 'BAR'} The default class seems to be APIClient I have tried the following but none of them work: class AccountsTests(APITestCase): def test_user_is_authenticated(self): ... headers = {'USERID': 'john.doe', 'FOO': 'BAR' } self.client.get(url, headers) # Doesn't work self.client.get(url, **headers) # Doesn't work self.client.headers.update(headers) # Doesn't work ... -
Hy folks! Can anyone help me out how to remove text from pdf in python
I have tried to extract text using pdf miner but not able to remove the text from pdf -
Cannot assign "<built-in function cmp_to_key>": "Foo.content_type" must be a "ContentType" instance
I am using Django 4.0.6 I have a model like this: class AnonymousInteractionMonitor(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_content_types', related_query_name='%(app_label)s_%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') interaction_type = models.PositiveSmallIntegerField(choices=Engagement.ENGAGEMENT_TYPES, null=False) visitor_ip = models.GenericIPAddressField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) In one of my views, I have the following code: ct, object_id = self._get_content_info() ip_address = get_client_ip(request_object) # expensive function, call only when needed last_visit = AnonymousInteractionMonitor.objects.filter(visitor_ip=ip_address, content_type=ct, interaction_type=interaction_type, object_id=object_id).last() I am checking the type of the variable ct before filtering - and it is indeed, an instance of a ContentType - so why is the error: Cannot assign "": "AnonymousInteractionMonitor.content_type" must be a "ContentType" instance being raised? How do I fix this? -
Avoid redirection on model
I'm fairly new in django and im building a simple web with 2 date pickers that are then used as a variable to ping the DB and populate a charfield with the result of the query. So far I've managed to render nicely the page and when the user submits the request, the query is triggered nicely and the value is fetched. The problem comes that after that, the model expects a url to redirect to but instead i want to stay on the same page and populate the result of the query into a charfield. So far this is what I got (I erased sensitive data): from django.db import models from django.forms import ValidationError import psycopg2 from django.utils import timezone class Event(models.Model): location = models.CharField(max_length=30, choices=[("us","US"), ("global","Global")]) start = models.DateTimeField(default=timezone.now) end = models.DateTimeField(default=timezone.now) # This is the field I want to fill with the output of the query. result = models.CharField(max_length=20, default=0) # def get_absolute_url(self): # I have tried just comenting this but it throws and exception # return bytes(str(self.pk), encoding='utf-8') def _do_insert(self, manager, using, fields, returning_fields, raw): query = """ """ location_value = getattr(self, fields[0].name) start_date = getattr(self, fields[1].name) end_date = getattr(self, fields[2].name) if start_date >= end_date: # … -
How to add an object field in a Django model
I would like to have a field that works as an object for one of my models, but without needing to reference it using a ForeignKey. What I'm looking for is something the field pressure here: { "professional": "d83876a6-69eb-4946-a0f7-56fd39cbd6a8", "observations": "Update", "date": "2022-03-22T21:45:37Z", "pressure": { "systolic_pressure": 0, "diastolic_pressure": 0 } I have searched a lot, but haven't found how to add a field like that one, and how to configure the model/serializer/view to be able to create/read/update/delete it. -
I have a problemem. With int 23 to convert Ienumeabable
So the quastion is about hwo two collaplse the my value of 32 integer to the ineumabable system generic. What cind of operasion can I use to get quality good result of achieving hue saturaiton faction in my Java net sharp project? -
Epoch time and daylight savings in Python/Django
I'm using a BigIntegerField to save dates (Epoch time) in a Django application. We can create single classes or courses, but let me explain the later. When creating a course, we must select the the start and end dates,the days of the week on which the event will occur and at what time. For example, we can say that a course will be from 01/09/2022 to 01/12/2022, happening on Wednesdays and Fridays at 10am. The backend receives the days and schedule of the first week. To those initial timestamps, we add milliseconds in one week to create all of the course classes. The problem is that epoch time is not aware of daylight savings, and in the example I just gave, classes until to 29/10/2022 will be schedule to 10am, but classes after 30/09/2022 will be schedule to 9am. Is there any way to be aware of the user's timezone, to detect that they have daylight savings and adjust the timestamp accordingly? -
Como mostro variantes do produto no template Django
Não estou conseguido ter acesso ao product.variants_set.color e nem o .size, Mas se eu utilizo o .all funciona! E eu preciso fazer a verificação com if para saber se existe o color e o size. Alguém sabe o que estou fazenro errado? {% if product.variants_set.color %} <div class="section"> <div> {% for variant in product.variants_set.color %} <div style="background:{{ variant.color.code }};"></div> {% endfor %} </div> </div> {% endif %} {% if product.variants_set.size %} <div class="section"> {% for variant in product.variants_set.size %} <div>{{ variant.size }}</div> {% endfor %} </div> {% endif %} -
Cannot display foreign key in Django list view
I'm trying to display the foreign key information in my list view for the primary key and it's just not displaying and I cannot for the life of me figure out why. Models: Primary class LightHouse(models.Model): customer = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, related_name='lighthouse_group') context_object_name = 'lighthouse' lighthouseName = models.CharField(max_length=35, default="Not a lighthouse") Foreign class Endpoint(models.Model): lighthouse = models.ForeignKey(LightHouse, on_delete=models.CASCADE, related_name='LHName') device = models.CharField(max_length=50, unique=True) Django Template for the PK <tbody> {% for endpoint in lighthouse.endpoint_set.all%} <ul> <td>{{ endpoint.device }}</td> <td>{{ endpoint.endpointIPv4 }}</td> <td> Online </td> </ul> {% endfor %} </tbody> What am I missing that it won't display the FK? -
Docker build error on django application with numpy
I am trying to docker build my django application but i am getting this error when it install the requirements.txt: Running from numpy source directory. #7 83.21 setup.py:480: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates #7 83.21 run_build = parse_setuppy_commands() This is my requirement.txt: -f https://download.pytorch.org/whl/torch_stable.html Django==4.0.6 fastbook==0.0.26 gunicorn==20.1.0 Pillow==9.2.0 torch==1.12.0+cpu torchvision==0.13.0+cpu And this is my dockerfile: #Python and Linux Version FROM python:3.9-alpine3.15 COPY requirements.txt /app/requirements.txt #Configure server RUN set -ex \ && pip install --upgrade pip \ && pip install --no-cache-dir -r /app/requirements.txt #Working directory WORKDIR /app ADD . . EXPOSE 8000 CMD ["gunicorn", "--bind", ":8000","--workers", "3", "hongOS_project.wsgi:application"] -
Call a function without calling function's wrapper function
Let's say I have a function: @some_authorization def to_call(): pass Now, I want to call this to_call() function, but don't want that wrapper function @some_authorization get executed. How to achieve this scenario? -
HTMX: How to update hx-delete url dynamically?
In order to build a modal to confirm a delete action, I'm trying to dynamically set a delete url, using hyperscript. Here is the (partial) code: <!-- open the modal and set the (Django) delete url --> <button _="on click set @hx-delete of #confirm_delete_button to '{% url view_name record.pk %}'"> <!-- the delete confirmation button --> <button id="confirm_delete_button" hx-delete="to_be_set_later_by_hyperscript" hx-trigger="click" hx-target="body" {# TODO: change #} hx-swap="delete"> Delete </button> At first, everything seems to work as expected, since I can see the right delete url in the inspector: However, when clicking the button, I got a Not Found: /to_be_set_later_by_hyperscript error, showing that even if the attribute has been set, the "old" url is used by HTMX. What should I do? Thanks. -
query to django model to find best company sale in the month
I have two django model one "company" and the other is "MonthlyReport" of the company I want to find out what company sale in current month is more than 20% of previous month class Company(models.Model): name = models.CharField(max_length=50) class MonthlyReport(models.Model): company = models.ForeignKey(Company,on_delete=models.CASCADE) sale = models.IntegerField() date = models.DateField() How can i figure out this issu -
Google OAuth 2 authorization - custom User model. Error: User has no field named 'username'
Im trying to make the authorization via Google. I use a custom user model with an email as a username field. Once I login, I choose the email I want to login with. Then Ive got yellow screen with an error "FieldDoesNotExist at /accounts/google/login/callback/ User has no field named 'username'". If anyone can help me, I will appreciate it very much. My models: # users/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) first_name = models.CharField(max_length=30, help_text="Ваше имя") last_name = models.CharField(blank=True, null=True, max_length=30, help_text="Ваша фамилия") mobile = models.CharField(max_length=30, help_text='Ваш телефон') status = models.CharField(blank=True, null=True, max_length=3, choices=TYPE_OF_CLIENT, default=POTENTIAL) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] My settings: INSTALLED_APPS = [ ... 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] SITE_ID = 1 ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = None AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } URL PATTERNS urlpatterns = [ ... path('accounts/', include('allauth.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My Google URI settings enter image description here Error enter image description here -
how do change the position of the cards when click the any button
when I have to click the make admin button it will change as admin and as well as change the position it will goes to the first place -
when set up reload-on-rss in uwsgi server , how to avoid all processes reload/respawn at the same time?
I'm encoutering a situation that using reload-on-rss/reload-on-as = 256 to avoid memor leak, it works for almost all scenes. however, by setting up these params, there's a extremely small probability that all processes are running out of memory which been set. so they'll all respawn at the same time, and I found out rest requests responded in 502. So I wanna ask if there is a way to keep at least one worker running to process requests even its memory usage's exceeded (it should not reload untill another worker started)? I've tried searching for the settings to make it but cannot found anything. does anyone can help? thank you so much! (and I'm not sure whether I make myself clear. sorry about that) here is my uwsgi.ini: http = :28888 touch-reload = true reload-on-as = 256 reload-on-rss = 256 procname-prefix-spaced=service_name module = service_name.wsgi:application chdir = ./ pidfile = uwsgi.pid socket = uwsgi.sock master = true vacuum = true thunder-lock = true enable-threads = true harakiri = 600 processes = 20 threads = 10 py-autoreload = 1 chmod-socket = 664 post-buffering = 10240 socket-timeout = 3600 http-timeout = 3600 uwsgi_read_timeout = 3600 listen = 10000 -
Is it possible to use the left join and annotate function in django?
SELECT A.username ,COUNT(B.*) FROM users_user A LEFT JOIN post B ON B.user_id = A.id GROUP BY A.id users_user model is default django user model I want to change query to orm I tried both "post" and "post_set" using select_related, but I couldn't. -
name 'post' is not defined
Why this error is shown in my code. I think code is very well My models.py from django.db import models from tinymce.models import HTMLField from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Post(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) content = HTMLField() author = models.CharField(max_length=50) slug = models.CharField(max_length=130) date_and_time = models.DateTimeField(blank=True) def __str__(self): return self.title class PostComment(models.Model): comment_id = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) date_and_time = models.DateTimeField(default=now) What is the problem in views.py? my views.py from django.shortcuts import render, redirect from blog.models import Post, PostComment def index(request): post = Post.objects.all() context = {'post':post} return render(request, 'blog/bloghome.html', context) def blogpost(request, slug): blog_post = Post.objects.get(slug=slug) comments= PostComment.objects.filter(blog_post=post) context = {'blog_post':blog_post, 'comments':comments} return render(request, 'blog/blogpost.html', context) def post_comment(request): if request.method == 'POST': comment = request.POST.get('comment') user = request.user post_Id = request.POST.get('post_Id') post = Post.objects.get(post_id=post_Id) comment = BlogComment(comment=comment, user=user, post=post) comment.save() return redirect(f'/blog/{blogpost.slug}') my urls.py urlpatterns = [ path('', views.index, name='Blog_home'), path('<str:slug>', views.blogpost, name='blogpost'), path('postcomment', views.post_comment, name='post_comment'), ] Error NameError: name 'post' is not defined Error at views.py, line 11 comments= PostComment.objects.filter(blog_post=post) Please any developer help me to solve this question. -
Registering a function in Django
I have a very simple python script that runs Tanimoto similarity index between a molecule sample and a molecule database: from openbabel import pybel targetmol = next(pybel.readfile("smi", "/path/to/sample.smi")) targetfp = targetmol.calcfp() <--- calculate fingerprints of the sample for mol in pybel.readfile("smi", "/path/to/db.smi"): fp = mol.calcfp() <--- calculate fingerprints of the db tan = fp | targetfp <--- calculate the Tanimoto index via the "|" operator if tan[0] >= 0.8: print(tan) My goal here is to add this function to a website that I am developing with Django. Ideally, users will submit their own molecule and receive a list of the most similar ones present in my database on a new page, as an on-click function. What I need to do here is to let the script use the users's molecule as a sample but, most importantly, I do not know how to deploy this function in the Django framework. Since I know that this is not a code shop, I simply would love to receive a clear explanation on how to register my function, how to call it as an on-click function and what I have to change in order to let the script use the users's molecule instead of … -
Pagination in Django ListView when using get_context_data
I am currently facing this problem with Django ListView. Basically, I need to filter some questions per topic and I would like to paginate the results. My code is working perfectly about the queryset part (the results are showed correctly) but I am facing a problem with pagination. Let's say I have so far 8 items in my query, if I choose to paginate_by = 10, it shows me just one page. If, otherwise, I choose to paginate by, let's say, 3, it shows me 3 pages to choose in the template (which is correct) but it shows me ALL the results of the query in my page. I post some code to be more clear models.py: class Tag(models.Model): name = models.CharField(max_length=300, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def clean(self): self.name = self.name.capitalize() def __str__(self): return self.name class Question(models.Model): post_owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=5000, default='') body = tinymce_models.HTMLField() tags = models.ManyToManyField( Tag, related_name='tags') viewers = models.ManyToManyField( User, related_name='viewed_posts', blank=True) views.py: class TagQuestionsListView(ListView): template_name = 'main/tag_questions.html' paginate_by = 20 def get_queryset(self, **kwargs): tag = Tag.objects.get(name=self.kwargs['name']) questions = Question.objects.filter(tags=tag) return questions def get_contextdata(self, **kwargs): context = super().get_context_data(**kwargs) context['tag'] = Tag.objects.get(name=self.kwargs['name']) context['questions'] = Question.objects.filter( tags=context['tag'], is_deleted=False) return context template: {% … -
Curious about where to set up the Python path
This is a problem I encountered while using django I learned from Google that we need to set an absolute path to solve this problem By the way, can I use the absolute path to use from* import*? If possible, should I write the absolute route at the top? If anyone knows about this, I'd appreciate it if you could let me know ---------my code------------- from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path from myapp import views from . import views urlpatterns = [ path('', 'views.index'), path('create/', 'views.index') ] -----------error message------------- from myapp import views ModuleNotFoundError: No module named 'myapp' -
Update array of object in a JSON field in drf model
I'm stuck at something. I've a model: class DummyModel(BaseModel): status = { 'Key1': None, 'Key2': None, 'Key3': None, 'Key4': None, 'key5': None } user = models.ForeignKey(user, on_delete=models.CASCADE, blank=True, null=True) comments = models.TextField(blank=True, null=True) order = models.JSONField(default=status) I'm getting data from frontend like this: { "user": "a225e17c-153d-21b0-bde3-a32d41ac1d30", "status":[ {"Key1": "Dummy"}, {"Key2": "Dummy"} ] } The question is, I need to save this data(update the existing Json) into my model. How can I do this? Thanks in advance! -
Is it necessary to create another django application for authentification and registration?
I want to work on all aspects of my django project in one application that combines them all (registration,authentification.......) , but I m afraid that it's a bad approach .