Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
asynchronus form submission django
I'm using ajax to submit a form, and it's working. But it's not working asynchronously. When I'm trying to upload files it uploaded successfully and then the page loads again. I want it to make asynchronously. In addition, I want to make a progress bar too. But things not working as I expected. my forms.py from django import forms from .models import Comment from .models import post class UploadForm(forms.ModelForm): class Meta: model = post fields = ('image', 'video', 'content',) my views.py def django_image_and_file_upload_ajax(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.instance.author = request.user form.save() return JsonResponse({'error': False, 'message': 'Uploaded Successfully'}) else: return JsonResponse({'error': True, 'errors': form.errors}) else: form = UploadForm() return render(request, 'blog/upload.html', {'form': form}) and my upload.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <main> <div class="container"> <div class="row"> <div class="col-md-8 my-5"> <div class="content-section" style="padding:10px 20px"> <form enctype="multipart/form-data" id="id_ajax_upload_form" method="POST" novalidate=""> <fieldset class="form-group"> {% csrf_token %} <legend class="border-bottom mb-4"><i class="fas fa-feather-alt text-muted mr-2"></i>Create a post</legend> {{ form.as_p }} </fieldset> <div class="form-group"> <input type="submit" /> </div> </form> </div> </div> </div> </div> </main> {% endblock content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> // form upload $('#id_ajax_upload_form').submit(function(e){ e.preventDefault(); $form = $(this) var formData = new … -
Windows IIS Server stops Django processes after 2 minutes
I have django project that provides a IP Camera streaming and recording system that is using Python OpenCV so it needs to run processes for a long time, maybe one hour or more. However, the Windows IIS Server stops the processes after about 2 minutes. Is There any way to prevent IIS from doing that? -
How To Put Javascript In A Django View
I have a small piece of javascript that I want to put in my django view (to be ran in the web server, not the client's computer). I know how to put in into a template, but I don't know how to have it run on the server's (in this case heroku). -
Why do I get heroku error : App not compatible with buildpack
So I'm trying to deploy my Django project with heroku. I have created an app and connected by git repo. However when I try to deploy, I get this error : App not compatible with buildpack. So the possible cause is that the git repo that is connected is not exactly the root folder of my Django project, since I have both React (for FE) and Django (for BE). Hence the repo contains two directories inside. Please see the repo itself (link) Now I think the reason why I'm getting the error above is because I've connected repo "/bookcake", not "bookcake/synergy_django" which is the exact root folder of my Django project. How so I deal with this error? Thank you very much. -
Django Template System
I want to create beautiful modern Front-end UIs for my web app. I have a small exposure to Django. Django is perfect for the backend I am building so that's confirmed. The issue is that whether the Django template system flexible enough to create front-end UIs like below? -
Django TypeError while trying to list objects in html
I want to make manually create form for a model but when I try to call object.all() method it gives me TypeError error in return. def addPatient(request): con = Intensivecare_Form.objects.all() context = {'items': con, 'title': 'Items'} if request.method == 'POST': patient = Patient(name=request.POST.get("fname"), data=request.POST.get( "lname"), Intensivecare_Form=request.POST.get("cform")) try: patient.full_clean() patient.save() except ValidationError as e: # Do something based on the errors contained in e.message_dict. # Display them to a user, or handle them programmatically. return HttpResponse("Your form is wrong, try again") return render(request, context, 'AddPatient.html') I couldn't do to return model data for html. -
Unhash encrypted text in Python [duplicate]
I have these codes to hash a string. import hashlib test = "TESSTTT HASHHHING STRING" test1 = hashlib.sha256(test.encode('utf-8')) hashed = test1.hexdigest() result: dba883d794567f6fb740abe0e4abb2fe3e3a960b47e8b66f2aa7902a2d5b2960 the result will be inserted in the database so I am trying to get it there and then decrypt it but I dunno how to decrypt it. -
Django sqlite to postgres database migration
I have a quite large db of 750MB which I need to migrate from sqlite to postgres. As, the db is quite large I am facing some issues that some of the previous questions on the same topic did not had. Few days ago, I have migrated one sqlite db of size 30MB without any issues with loaddata and dumpdata commands. But for this large db, one of my app throws Database image is malformed error when running command dumpdata. Another of my app dumps successfully but does not load. I have seen the with -v 3 verbose flag that the objects are not even processed. To be precise, while running the loaddata command data from json file is processed first to check duplicate primary key and other model constraints then those data are used to create model objects. But for this app, data are not processed in the first place. Apart from this two commands there are some other methods that does the migration. But, the schema is completely changed in those way which I don't desire to do. Moreover I have faced issue DurationField becomes a string after migration and I couldn't typecast those fields. Bigint becomes int … -
Django - How to display user's profile picture with a message after its sent?
I have a live chat application and I'm trying to display a profile picture with the message after its sent with Javascript. Here is my code... Models.py - here is my Message and Profile model class Message(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) room = models.CharField(max_length = 255) content = models.TextField() date_added = models.DateTimeField(auto_now_add = True) class Meta: ordering = ('date_added', ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) Consumers.py class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print(self.room_group_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] room = text_data_json['room'] await self.save_message(username, room, message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatroom_message', 'message': message, 'username': username, } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, })) @sync_to_async def save_message(self, username, room, message): user = User.objects.get(username = username) Message.objects.create(author = user, room = room, content = message) pass And … -
Only the last item has the text in an ajax call
I'm having a hard time solving this problem. here's the code: const postBox = document.querySelector('#posts') const getUser = function(id, val) { $.ajax({ type: 'GET', url: `/api/user/${id}`, success: function(response){ val.innerHTML = `Posted by: ${response.username}` }, error: function(error){ console.log(error) } }) } const getPosts = () => { $.ajax({ type: 'GET', url: '/api/posts/', success: function(response){ console.log(response) response.forEach(el => { postBox.innerHTML += ` <div class="card mb-2"> <div class="card-body"> <h5 class="card-title">${el.title}</h5> <p class="card-text">${el.body}</p> <p class="card-text">${el.date}</p> </div> <div class="card-footer"> <p class="card-text" id='author${el.id}'></p> </div> </div> ` const authorBox = document.querySelector(`#author${el.id}`) console.log(authorBox) getUser(el.author, authorBox) }) }, error: function(error){ console.log('error') }, }) } getPosts() Only the last item has the "Posted by author" I can't seem to figure out why only the last item has it. Even when I inspect it, it has the "Posted by author" inner html and inner text but it's not showing it. here's the output: Test 1 Test 1 2021-07-12 Test 2 Test 2 2021-07-12 Test 3 Test 3 2021-07-12 Test 4 Test 4 2021-07-12 Posted by: kyrios How do I make sure that all of the authorBox has their inner html changed? -
Django MultipleChoiceField rendering each item without li tag / or render them with bootstrap
i have this code on my forms.py to create multiple choice field but it always render as ul/li someinput = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple( attrs={'class': 'form-check-input'}), choices=Courtintroductiondetail.TypeOfCourt.choices) but when i render them with bootstrap classes it do nothing somehow i think it is because the li tag the form.someinput in template creates so how i render them without li tag or render them like bootstrap checkbox -
users can not login by custom login model django
i am going to use a dual authentication system (email, username). when i create users by "createsuperuser" users can login but when i create users inside admin panel of django user can not login and also i noticed the user's password which is made in admin panel is not hashed in DB! backend.py: class EmailBackend(backends.ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username)) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user return super().authenticate(request, username, password, **kwargs) models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): email = models.EmailField(_('email address'), unique=True, null=False, blank=False) def __str__(self): return self.email -
How to solve Django custom admin site NoReverseMatch when registering models?
I want to create a custom Admin site for one of the apps in my Django project. This app has a couple of models that I want to register on the admin site. The thing is that if I register all the models of the app in this custom Admin site, I get the following error: NoReverseMatch at /admin/auto-harvest/ Reverse for 'app_list' with keyword arguments '{'app_label': 'my_app'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|django_mfa|axes)/$'] However, if I register all models but except the last one, I don't get the error, and the admin site loads successfully with the exception that one of the models is not registered. I found this behavior very peculiar and can't figure out the reason. Below is my admin.py and the urls.py class MyAdminSite(AdminSite): site_header = "My Admin" site_title = "My Admin Site" my_admin_site = MyAdminSite(name='auto_harvest') Registering models: @admin.register(MyModel1, site=my_admin_site) class MyModel1Admin(VersionAdmin): ... @admin.register(MyModel2, site=my_admin_site) class MyModel2Admin(VersionAdmin): ... In the project urls I have: urlpatterns = [ path('admin/my-site/', include(myapp.urls)), ] In myapp.urls I have: urlpatterns = [ path('', my_admin_site.urls), ] -
Multiple like feature in django
I want to create a like feature for the posts and comments in which the number of likes increases each time when a user hits the end point. I have used the Generic Foreign Key for linking and want to override the create function as post request is not idempotent and does not allow to create an identical request for the like from the same user. here, it's the create method in my Like serializer: def create(self, validated_data): like = validated_data.get("like") if user: main_user = user else: main_user = User.objects.all().first() model_type = self.model_type like = Like.objects.create_by_model_type( model_type,obj_id, like, main_user, ) return like views.py: class LikeCreateAPIView(CreateAPIView): queryset = Like.objects.all() permission_classes = [IsAuthenticated] def get_serializer_class(self): model_type = self.request.GET.get("type") obj_id = self.request.GET.get("obj_id") return create_like_serializer( model_type=model_type, obj_id=obj_id, user=self.request.user ) -
How to match field of different table in Django
I'm using Django as backend, PostgresSQL as DB, and HTML, CSS, and Javascript as frontend. I got stuck to match the field and retrieve specific data in Django. class Motor(models.Model): . . code = models.CharField(max_length=100) . . class Drum(models.Model): . . code = models.CharField(max_length=100) . . class Cart(models.Model): . . motor = models.ForeignKey(Motor, on_delete=models.CASCADE,null=True, blank=True) drum = models.ForeignKey(Drum, on_delete=models.CASCADE,null=True, blank=True) . . Now in the Above model, there is the cart Model which saves the data of the Motor Model or else saves the data of the Drum Model or both. So for example If the user saves the data of the Motor Model in the Cart Model. The data which is saved in the Cart model should match the code field with model Drum and should filter the data accordingly. So, I have done something like this. views.py def Drum(request): drum_filter = Drum.objects.filter(code__in=Cart.objects.all().values_list('code', flat = True)) return render(request, 'list/drum.html', {'drum_filter':drum_filter} ) But now the problem is: The code field in Cart goes as child table and my parent table is Motor. something like this: [ { "id": 4, "quantity": 1, "user": { "id": 4, }, "motor": { "id": 9, "name": "...", "title": "....", . . . "code": "DD1" }, … -
Is it possible to store some HTML code in "context" and then make it work on one of the templates?
My goal is to get this table's code from another website using selenium, store it in the context dictionary to then place it in one of the templates in a way that it won't show the code as text but it will make it part of the page's code itself. tab = driver.find_element_by_class_name("table-responsive") tab = tab.get_attribute("outerHTML") context = {'tab': tab, } This way I already managed to store the code in the context dictionary and then I used the Django built-in function to pass the context keys to templates {{ tab }}. I'm trying to understand if it's possible to make it work as proper HTML code in a template even if it's just a key in a dictionary. -
Functions inside a Django model
Is it possible to write custom functions inside a Django model? And if it is, how can I do it properly. I'm currently doing a practice project of an ecommerce, and I want to change a boolean field value based on the value of an integer field. I currently have this: class Product(Model): name = CharField(max_length=64) desc = CharField(max_length=256) price = DecimalField(decimal_places=2, max_digits=6) available = BooleanField(default=True) quantity = IntegerField() category = ManyToManyField(Category) def availability(self): if self.quantity == 0: self.available = False self.save() return self.available def __str__(self): return self.name I know that I'm not calling the function, but I want that to be called once the product is updated even on the admin panel, is that possible to do? And I'm not really confident about that return in the function, I don't feel like that is correct. Thanks in advance. -
Tailwindcss LSP for Neovim root_dir issue
I am having an issue with the Tailwind LSP in Neovim 0.5 where the language server running however I get no intellisense when defining a class. I am working on a django project and tailwind is all setup with the following structure. . ├── .git/ ├── .venv/ ├── node_modules/ ├── src/ └── static/ ├── package.json ├── postcss.config.js └── tailwind.config.js I have set the "root_dir" setting in the tailwind lsp setup to: lsp.util.root_pattern('tailwind.config.js') orlsp.util.root_pattern('tailwind.config.js', '.git', 'postcss.config.js')etc, but with no success. The only way I can get intellisense is if I place a html file right in the root next to the tailwind.config.js and edit it. Has anyone else come across this and might know where I am going wrong. Appreciate any help, thanks -
How to cache class based view and objects separately in django
Currently i am caching the django class based view as shown below. views.py @method_decorator([vary_on_cookie, cache_page(86400)], name='dispatch') class itemviewset(viewsets.ModelViewSet): serializer_class = ItemtSerializer # is a ModelSerializer def get_queryset(self): if self.request.method=="GET": cart_name=self.request.query_params.get('cart') return item.objects.filter(cart_name=cart_name).order_by("-created_at") else: return item.objects.all().order_by("-created_at") @auth def dispatch(self,request,*args,**kwargs): return super(itemviewset,self).dispatch(request,*args,**kwargs) settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'product_cache', } } There are other views cached as well. The above cache configuration impacts /item and /item/{id}/ paths. Below are the implementation i'm looking for : cache to be impacting only /item and for every items (objects) in path /item/{id}/ new cache has to be created changes to individual item i.e /item/{id}/ should not alter the /item path cache if new item is added or old item is deleted i.e post,delete call to /item/, it should update or (delete and set) the /item cache. whole cache should not be deleted as i have other views cached as well. Is it possible to do the above operation in django? could some one help me out to implement this? -
Django Efficiency For Data Manipulation
I am doing some data changes in a django app with a large amount of data and would like to know if there is a way to make this more efficient. It's currently taking a really long time. I have a model that used to look like this (simplified and changed names): class Thing(models.Model): ... some fields... stuff = models.JSONField(encoder=DjangoJSONEncoder, default=list, blank=True) I need to split the list up based on a new model. class Tag(models.Model): name = models.CharField(max_length=200) class Thing(models.Model): .... some fields ... stuff = models.JSONField(encoder=DjangoJSONEncoder, default=list, blank=True) other_stuff = models.JSONField(encoder=DjangoJSONEncoder, default=list, blank=True) tags = models.Many2ManyField(Tag) What I need to do is take the list that is currently in stuff, and split it up. For items that have a tag in the Tag model, add it to the Many2Many. For things that don't have a Tag, I add it to other_stuff. Then in the end, the stuff field should contain of the items that were saved in tags. I start by looping through the Tags to make a dict that maps the string version that would be in the stuff list to the tag object so I don't have to keep querying the Tag model. Then I loop … -
Django: Browser button for accessing previous web page is not working
I have a Django view A and a Django view B. A button is displayed on A so that you can go to B. Then when you are viewing B, the previous-web-page browser button does not do anything at all. Do you know about any configuration so as to check what the URL is when using browser buttons? Or in general, is there any way to set to where the previous-web-page browser button is going to redirect the user? -
Django filling dropdown in html from database
I am learning Django. I want to make manual add form for person model but this person model has relations with 2 another model. I couldn't figure out how to solve when I want to add person how to fill another related fields from other models. This is my person model class Patient (models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=256) data = models.JSONField() intensivecare_forms_data_id = models.OneToOneField( Intensivecare_Forms_Data, on_delete=models.CASCADE) Intensivecare_form = models.ManyToManyField(Intensivecare_Form) def __str__(self): return f'Id = {self.id}, name = {self.name}' I want to make a form that has name field, data field, icformsdataid field and i.._form field but those related fields must be dropdown. This is my view def addPatient(request): if request.method == 'POST': icareform = Intensivecare_Form.objects.filter() patient = Patient(name=request.POST.get("fname"), data=request.POST.get("lname"), Intensivecare_Form=request.POST.get("cform")) try: patient.full_clean() patient.save() except ValidationError as e: # Do something based on the errors contained in e.message_dict. # Display them to a user, or handle them programmatically. return HttpResponse("Your form is wrong, try again") return render(request, {'item':icareform}, 'index.html') And this is html page. <form action="" method="post"> {% csrf_token %} <label for="fname">First nddame:</label><br> <input type="text" id="fname" name="fname"><br> <label for="lname">Data:</label><br> <input type="text" id="lname" name="lname" value='{"test":"test"}'><br><br> <label for="care-form">Care Form:</label><br> <input type="text" id="care-form" name="cfrom"><br><br> {{item}} <input type="submit" value="Submit"> </form> -
Unit testing error in django rest frameframework
I am getting following error while running unit test but while posting from postman it works fine. {'users': [ErrorDetail(string='This field is required.', code='required')]} My serializer.py: class UserSerializer(serializers.Serializer): first_name = serializers.CharField(max_length=60, allow_blank=False) last_name = serializers.CharField(max_length=60, allow_blank=False) email = serializers.EmailField(max_length=100, allow_blank=False) class CompanySerializer(serializers.Serializer): users = UserSerializer(many=True, write_only=True) class Meta: model = Company fields = '__all__' extra_kwargs = { 'tech_tags': {'required': False} } Here is my unit test. tech_tags is not required in serializer but it shows tech_tags required error during test.Users data also shows required error even though users data is sent in request payload. def test_create_company(self): request_data = { "name": "Test Company", "users": [ { "first_name": "Test Name.", "last_name": "Test Name.", "email": "email", } ] } request = self.factory.post('/api/company', request_data) view = CompanyViewSet.as_view({'post':'create'}) force_authenticate(request, user=self.admin_user) response = view(request) self.assertEqual(response.status_code, 201) Here even though users is sent in payload but it show error: {'users': [ErrorDetail(string='This field is required.', code='required')]} -
How to send email when save method is triggered in django admin panel
I have used the default Django admin panel as my backend. I have a Blogpost model. What I am trying to do is whenever an admin user saves a blogpost object on Django admin, I need to send an email to the newsletter subscribers notifying them that there is a new blog on the website. Since Django admin automatically saves the blog by calling the save function, I don't know where to write send email api logic. Hope I have explained it well. My Blogpost: class BlogPost(models.Model): author = models.CharField(max_length=64, default='Admin') CATEGORY_CHOICES = ( ('travel_news', 'Travel News',), ('travel_tips', 'Travel Tips',), ('things_to_do', 'Things to Do',), ('places_to_go', 'Places to Go'), ) image = models.ImageField(blank=True, null=True) title = models.CharField(max_length=255) categories = models.CharField(max_length=64, choices=CATEGORY_CHOICES, default='travel_news') caption = models.CharField(max_length=500) content = RichTextUploadingField() # todo support for tags # tags = models.CharField(max_length=255, default='travel') #todo tag = models.ManyToManyField(Tag) date_created = models.DateField() I have overwritten the Django admin form by my model form like this. class BlogForm(forms.ModelForm): CATEGORY_CHOICES = ( ('travel_news', 'Travel News',), ('travel_tips', 'Travel Tips',), ('things_to_do', 'Things to Do',), ('places_to_go', 'Places to Go'), ) # categories = forms.MultipleChoiceField(choices = CATEGORY_CHOICES) class Meta: model = BlogPost fields = ['author','image', 'title','categories', 'caption','content','tag','date_created'] @register(BlogPost) class BlogPostAdmin(ModelAdmin): # autocomplete_fields = ['author'] … -
How to achieve row num functionality in Django?
I need only 5th and 30th record (from top) in the below query set? qs=Posts.objects.filter().orderby('-date') is there any rownum functionality available in django to achieve this in a single query like rownum=5 ??. Note: I am using Postgres