Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 . -
Rescalling image that isn't called specifically as an image in HTML
This is going to be a very novice question. I am working with a Django application and for the first time I am having to edit the HTML, something I haven't worked on in years and even when I did I was not a high level. The current code has something like the following written: <div class="x"> %(image)s </div> I have never seen this '%(image)s' syntax before and anything I google appears to refer to string substitution and things like this. The class also has a max width of 16.6667% but the image does not rescale to this width. I have tried to add in widths to the div but with no luck and I believe it may be due to the way the image is being fed through to the html. Any insight on what an earth is happening here so I can find where the image is defined and potentially generate a smaller one at that stage would be much appreciated. -
Wagtail - how to make user management work with User.is_active being a @property?
Making the User.is_active flag a python @property instead of a read database field results in the following error: django.core.exceptions.FieldError: Unknown field(s) (is_active) specified for User class User(AbstractBaseUser, PermissionsMixin): @property def is_active(self): return .... This is because wagtail.users.forms.UserEditForm included "is_active" in the fields: class UserEditForm(UserForm): class Meta: model = User fields = {User.USERNAME_FIELD, "is_active"} | standard_fields | custom_fields This error occurs as long "wagtail.users" is included in settings.INSTALLED_APPS, even when overriding the default forms as described in the documentation. WAGTAIL_USER_EDIT_FORM = 'users.forms.CustomUserEditForm' WAGTAIL_USER_CREATION_FORM = 'users.forms.CustomUserCreationForm' I tried to disable the wagtail user management entirely, but this does not seem to be possible. https://github.com/wagtail/wagtail/issues/3657 Any ideas how to make this work? -
Get Information About Citys from Google Using Django
i want to GET location information (distance,Travel Time) From Google With Api To My Search Form. is there any method to do this With Django -
how to configure Django to new Elatisc cloud deployment service
we have a Django application running for users, using Elasticsearch with a local setup, and everything is working fine. We need to scale up and move Elasticsearch from our local deployment to Elastic Cloud Deployment. Current Hystack configuration: HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', 'TIMEOUT': 60, 'INCLUDE_SPELLING': True, }, } We created our new Elastic Deployment on Elastic Cloud But I'm not familiar with it, How to update the current configuration with new cloud configurations. Note that new credentials are provided from the Cloud Deployment server: cloud_id cluster_id endpoint deployment_name My question is how to merge these new credentials to HAYSTACK_CONNECTIONS on my settings.py? Also, any helpful reference is appreciated. Thanks in advance. -
How to encrypt id in urls at login?
I have two views for logging in. The login window appears. I type the login and then it takes me to the second view where I can see the user id in the urls. And I don't know how to hide it. This can be seen in this urls 'log_pass/int:pk/' == views.py == def LoNew(request): if request.method == 'POST': username = request.POST['username'] usr = User.objects.filter(username=username).first() if usr != None: pk = usr.pk return redirect(reverse('login_pass', args=[pk])) else: messages.error(request, 'Some message') return redirect(reverse('login')) else: form = AuthenticationForm() return render(request, 'login.html', {'form': form}) def PaView(request, pk): usr_model = get_object_or_404(User, id=pk) if request.method == 'POST': password = request.POST['password'] user = authenticate(username=usr_model.username, password=password) if user: if user.is_active: login(request, user) return redirect(reverse('start_pages')) else: messages.error(request, 'Some message') return redirect(reverse('login')) else: form = AuthenticationForm() return render(request, 'pass.html', {'form': form}) == urls.py == path('login', views.LoNew, name='login'), path('log_pass/<int:pk>/', views.PaView, name='log_pass'), -
Django. Filter_vertical change size
I have an issue with a filter_vertical for my model in admin panel. Availble entries has leght about 170 symbols. Standsrt width of filter_vertical is less then I need. It's possible to set new value for weidth or not and how? -
Django-Template based navigation and project structure
I am working on a Django project that is based on some common data structure but the data needs to be populated through different forms. For example WebForm_1 is based on Template_1 layout and logic, while WebForm_2 is based on Template_2 layout and logic. Yet data will be saved to the same database table. This concept applies to all forms that will be a part of the web application. So in order to achieve this, I am thinking of having a landing page which will have some brief information for each template. The navigation, home page and subsequent pages will be based on this template choice. 1) Is this the correct way of designing the project? 2) What would be the best and secure way of passing the template choice to ensure all CRUD is for that template only? Thanks -
How can I access object in Mixin via dispatch?
So I am trying to use Mixin, and the aim is to check if the requester is the owner of the object (owner is a field in my model). However, I am unable to do such a thing, with a result of 'TweetsUpdateView' object has no attribute 'object', what is wrong in my code? My models class Tweets(models.Model): description = models.TextField(blank=True, null=False, default="", max_length=255) createdAt = models.DateTimeField(auto_now_add=True, null=True, blank=True) updatedAt = models.DateTimeField(auto_now=True) owner = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, related_name="owner_tweets_set", ) user_likes = models.ManyToManyField(settings.AUTH_USER_MODEL) My view class OwnerRequiredMixin(UserPassesTestMixin): def dispatch(self, request, *args, **kwargs): if self.object.owner != self.request.user: return HttpResponseForbidden() return super(OwnerRequiredMixin, self).dispatch(request, *args, **kwargs) class TweetsUpdateView( LoginRequiredMixin, OwnerRequiredMixin, UpdateView, ): model = Tweets # fields = ["description"] # template_name = "tweets_form.html" template_name_suffix = "_form" form_class = TweetForm def form_invalid(self, form): print("form is invalid") return HttpResponse("form is invalid.. this is just an HttpResponse object") # slug_field = "id" # slug_url_kwarg = "tweet_id" # success_url = reverse_lazy("tweets:twitter") success_url = reverse_lazy("tweets:twitter") -
How can I handle the data of post requests in Django
I want to receive a request by adding several inputs to the form by the user. I want to know how to control the received data separately. in html file, {% for i in request.POST.items %} it works. but in views.py, it doesn't work like this views.py def debate_create(request): if request.method == "POST": content = request.POST for k,v in content.items: if k == 'sup_title': sup_title = SuperTitle() sup_title.author = request.user sup_title.super_title = v sup_title.save() elif 'img' not in k and 'section' in k: sub_title = Subtitle() sub_title.super_title = sup_title.super_title.id sub_title.sub_title = v sub_title.save() elif 'img' in k: stg = Images() imgs = request.FILES stg.images = imgs stg.sub_title = sub_title.sub_title.id stg.save() elif 'section' in k and 'opt' in k: opt = SelectOption() opt.sub_title = sub_title.sub_title.id opt.option = v return render(request, 'polls/test.html') models.py class SuperTitle(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='debate_author') super_title = models.CharField(max_length=100) liker = models.ManyToManyField(User, related_name='debate_liker') class Subtitle(models.Model): super_title = models.ForeignKey(SuperTitle, on_delete=models.CASCADE) sub_title = models.TextField(blank=True) class Images(models.Model): sub_title = models.ForeignKey(Subtitle, on_delete=models.CASCADE) images = models.ImageField(null=True) class SelectOption(models.Model): sub_title = models.ForeignKey(Subtitle, on_delete=models.CASCADE) option = models.CharField(max_length=20) option_voter = models.ManyToManyField(User) html <form method="POST" id="debate_form" action="{% url 'polls:debate_create' %}"> {% csrf_token %} <input type='text' name='sup_title' placeholder='제목'> <div id="form_container"> <section id='section_1'> <input type="text" name="section_1"> <input type="file" name="img_section_1" …