Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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" … -
Custom js is not working with Django DTL format
I have used multiple custom js in my project. It is working perfectly in simple HTML but when I tried to use that custom js in the Django DTL format for example {% for data in data %} 'custom js' {% endfor %} then it is not working. Can anyone help? I am stuck here for so long now. I am not able to find any solution regarding this. -
plot using pandas dataframe in django
I want to display the results of pandas dataframe on the webpage.How do I do it? This is what I am trying. input code import requests import pandas as pd import json import urllib3 def index(request) my_headers = {'Authorization' : 'Basic '} response = requests.get('http://172.24.105.27:8092', headers=my_headers) s = response.json() #print(s['Result']) df = pd.DataFrame(s['Result']['LS']) df1 = df.groupby(pd.to_datetime(df.MeterReading_DateTime).dt.date).agg({'AT': 'sum'}).reset_index() ax = df1.plot(kind='bar') print(ax) output AxesSubplot(0.125,0.11;0.775x0.77) -
Django Rest Framework GET request returning desired Response only on first Request
I am using Django Rest Framework and OpenStack (DevStack deployed on a Virtual Machine on my local PC) to create APIs which will run methods provided by OpenStack SDK and return the response in JSON format. However, while fetching(GET Request) a list of Servers created on OpenStack Cloud Platform, the Response for the first time after starting the Django Server is proper and desired, but after first GET Request, all GET requests sent are returning an empty List as the Response. It must be noted that I have not changed anything in the code or in the Endpoint(URL), the same scenario keeps on repeating when I restart the Django Server, desired GET Response on first Request and Empty List for all the GET Requests onward. I do not have any models of my own in models.py. First GET Request Response:- HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "name": "test_shell", "image": "openstack.image.v2.image.Image(id=b6019f25-6f6d-4fd2-9fb8-14d50a07d2c0, properties={'links': [{'rel': 'bookmark', 'href': 'http://192.168.56.101/compute/images/b6019f25-6f6d-4fd2-9fb8-14d50a07d2c0'}]})", "flavor": "openstack.compute.v2.flavor.Flavor(vcpus=1, ram=128, disk=1, OS-FLV-EXT-DATA:ephemeral=0, swap=0, original_name=m1.nano, extra_specs={'hw_rng:allowed': 'True'})", "networks": null, "status": "ACTIVE", "power_state": "1" }, { "name": "ins_code_4", "image": "openstack.image.v2.image.Image(id=b6019f25-6f6d-4fd2-9fb8-14d50a07d2c0, properties={'links': [{'rel': 'bookmark', 'href': 'http://192.168.56.101/compute/images/b6019f25-6f6d-4fd2-9fb8-14d50a07d2c0'}]})", "flavor": "openstack.compute.v2.flavor.Flavor(vcpus=1, ram=128, disk=1, OS-FLV-EXT-DATA:ephemeral=0, swap=0, original_name=m1.nano, extra_specs={'hw_rng:allowed': 'True'})", "networks": null, … -
How to connect Docker database container to any database GUI application?
When I view my tables from container bash on terminal its shows like this So is there any way to connect my database container to any database GUI? -
How to learn Django Framework efficiently?
I've been learning the Django framework for the last 6 months I saw a bunch of video tutorials, read the documentation, and practiced some small projects but still, I do not understand the basics of Django. Please help me to clear the concepts of the Django Web Framework. -
How to deploy Django + React project to hosting platform?
I used Django as backend and React as frontend. I want to know how to deploy this project to hosting platform such as heroku, netlify, etc. Can I deploy this project to one domain? Or should I have to use two doamins - one for Django and one for React? -
Django app via heroku is returning 500 error when only on mobile
I have just deployed an ecommerce site via heroku. I have a product review form which works fine on desktop devices however when i test this on my mobile phone - iphone i get a 500 error. These are the only logs i can see from heroku 2022-07-28T05:56:07.424841+00:00 heroku[router]: at=info method=POST path="/products/2" host=thecoffeeco.herokuapp.com request_id=37ea67d2-0989-41a5-9e34-25166c2649be fwd="151.224.165.76" dyno=web.1 connect=0ms service=584ms status=500 bytes=403 protocol=https 2022-07-28T05:56:07.425962+00:00 app[web.1]: 10.1.16.25 [28/Jul/2022:05:56:07 +0000] "POST /products/2 HTTP/1.1" 500 145 "https://thecoffeeco.herokuapp.com/products/2" "Mozilla/5.0 (iPhone; CPU iPhone OS 14_8_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1" -
git push heroku main
Processing /D:/bld/astroid_1640971040574/work remote: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/D:/bld/astroid_1640971040574/work' I am having the error above when trying to upload to heroku using git push heroku main. Please what's the way forward? -
How can we integrate ory kratos with django+react website
I am having a project to integrate ory kratos for auth. I don't find much of documentation on the implementation of ory with django+react website. I have worked with jwt previously. Does anyone know the complete working process of integrating ory with django+react application. -
I am creating a shopping todo list, it contains multiple shops and each shop have items in it. I want to share a shop with another user (DJANGO)
Like on clicking a share button that specific shop and its items should be transferred to another user and a receiver user can add that shop in its shopping list. I tried Django channels but I failed. I was unable to understand how to send object from a model using channel. Every YouTube Video is sending a text using Django channel. -
Inserting a new instance to a foreign key model in django
Im new at django and new at posting so pardon my mistakes, anyways What I have is a QR login system that will creates a new instance or record of a person scanning their qr code the problem is that Field 'id' expected a number but got Field 'id' expected a number but got "(insert name here) here is the relevant code models.py name = models.CharField(verbose_name='Name', max_length=30,) Truck_Assigned= models.ForeignKey(Truck, on_delete=models.CASCADE) def str(self): return self.name class Attendance(models.Model): name=models.ForeignKey(Helper, on_delete=models.CASCADE) attendace_time=models.DateTimeField(auto_now_add=True)```` views.py ````def qrcodelogin(request): attendance=Attendance.objects.all() attendacecounter=attendanceCounter.objects.all() if not request.user.is_staff: messages.error(request, 'You are not allowed to view this page') return redirect('userProfile') if request.method == 'POST': try: with transaction.atomic(): name = request.POST.get('decodedText') helper=Helper.objects.get(name=name) attendance_log = Attendance(name=helper) attendance_log.save() if attendanceCounter.objects.filter(name=name).exists(): attendanceCounter.objects.filter(name=name).update(counter=F('counter')+1) else: counter_log=attendanceCounter(name=name) counter_log.save() attendanceCounter.objects.filter(name=name).update(counter=F('counter')+1) except Exception as e: print(e) messages.success(request, 'something went wrong')```` -
TestCase for Loginview using ModelViewSet or GenericViewset
I am trying to write a testcase for my login in django rest framework. I tried browsing through net where I tried with APIClient, django-Client, Factory but didn't get the result. I getting the following response: {'non_field_errors': [ErrorDetail(string='Unable to log in with provided credentials.', code='authorization')]} even after supply the correct credentials Here is my test case file: """ Test cases for Login """ import json from django.urls import reverse from django.test import TestCase from rest_framework.test import APIClient class LoginTest(TestCase): """ Login test cases """ def setUp(self): """ Setup data for the login test cases """ self.valid_payload = json.dumps( {"username": "admin@ksbsgroup.com", "password": "dell@123"} ) self.url = reverse("users:login-list") def test_valid_login(self): """ Test login with a valid login """ client = APIClient() response = client.post( self.url, data=self.valid_payload, content_type="application/json" ) print(response.data) self.assertEqual(response.status_code, 200) My Login view is as follows: """ Login view """ import logging from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from common import messages log = logging.getLogger(__name__) class LoginViewSet(ObtainAuthToken, viewsets.GenericViewSet): """ Login view set for login """ def create(self, request): """ Login the user with the specified email and password. parameters: -------------------- email(str): Email address to login password(str): Password of the user …