Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pylint is not recognizing some objects in VSCode
I'm new to Django 3, and just started a project using Python 3.7, Django 3.0.8 in a Debian WSL2. Running VS Code in Win10, Python extensions installed, Pylint chosen as linter. Codehint works fine with almost all objects All my code is working fine, but I can't get object/type info on create_user(). Could this be a pylint issue or am I messing with these object types? Any help is apreciated, thanks in advance! -
when i click on submit forms then i got this error
I am getting attribute error in Django in forms, I got stuck after this please help me with this one my views.py file tasks=['sleep','drink','code'] class newforms(forms.Form): task=forms.CharField(label='new_task',max_length=100) def add(request): if request.method=='POST': form=newforms(request.method) if form.is_valid(): task=form.cleaned_data['task'] tasks.append(task) else: return render(request,'add.html',{ 'form':form }) return render(request,'add.html',{ 'form':newforms() }) and the error shows attribute error -
showing content of an HTTP response in the browser without refreshing
I am new to Django and I don't know if what I want is achievable this way. I have a simple c++ client that has to send a char* array containing Json data using an HTTP request (post method) to my Django server(I use cpp-httplib to send HTTP request in c++). The data is sent successfully the problem is I want to see the Json data in my browser as well but I have failed to do so. Both client and server are running on the same machine and server is on localhost. here is my **views.py** def PostFunc(request): if request.method == 'POST': print(request.POST) print(request.body) result = request.body print(result) return HttpResponse(result) my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',PostFunc), ] and this is my client code int main(){ Client cli("127.0.0.1",8000); char* testJson = {"[{\"name\":\"Visual Studio Enterprise 2017\",\"version\":\"15.0.26228.4\"}]"}; auto res = cli.Post("/", testJson, "application/json"); cout << res->status; system("pause"); return 0; } Django version 3.0.8 Python 3.8.4rc1 Thank you for taking time to answer my question and let me know if any other information is needed. -
How to automatically add a value to a hidden model object in a Django ModelForm?
How do you save default values in a Django's 3.0 ModelForm ? I have multiple Childs models (Child1 and Child2) that all inherits from the same abstract model Parent. I would like to hide the created_by field from the ModelForm, but autoadd the request.user and save it. from django.contrib.auth.models import User from django.db import models class Parent(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) class Meta: abstract = True class Child1(Parent): # Some code ... class Child2(Parent): # Some code ... I created a ModelFrom from django import forms from models import Parent, Child class ParentForm(forms.ModelForm): class Meta: exclude = ["created_by"] def form_valid(self, form): self.object = form.save(commit=False) self.object.created_by = self.request.user self.object.save() return super().form_valid(form) class Child1Form(ParentForm): class Meta(Parent.Meta): model = Child1 class Child2Form(ParentForm): class Meta(Parent.Meta): model = Child2 Can someone give me a solution and explain me what I misunderstood ? Thank you. -
Use HTML element and {{user.userprofile.image.url}} on Submit button Crispy Form
I hope you're doing well. Do you know how I can add this to my button: <img src="{{user.userprofile.image.url}}" width="22px" height="22px" style="border-radius: 90px;background: #ffffff38;"> I've tried but it's always translated as " Comment" on my page. class CreateCommentForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(CreateCommentForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method="post" self.helper.layout = Layout( Field("content",css_class="form-control",style="margin-bottom:10px",rows="1"), ) self.helper.add_input(Submit('submit','<img src="{{user.userprofile.image.url}}" width="22px" height="22px" style="border-radius: 90px;background: #ffffff38;"> Comment',css_class="btn btn-sm",style="background-color: #0d6ec5;border-color: #0d6ec5;")) Here too, I tried to add <img src="{{user.userprofile.image.url}}" width="22px" height="22px" style="border-radius: 90px;background: #ffffff38;"> but nothing worked even if I used HTML (""" """) class Meta: model = Comment fields = [ 'content' ] -
Cannot request json in javascript to django server
I have some python logic(with pandas and Keras) here in views.py that returns a json: def recommend(request): #get user with ip user_ip = get_client_ip(request) user = Custumer.objects.get(ip=user_ip) #using keras to predict what user would like pred = keras_model.predict( pd.np.array([user.products]) ) #transforming into series to return sorted dict pred = pd.Series(pred[0], index=prods_asin) pred = pred.sort_values(ascending=False) #transforming into json pred = pred.to_json() return HttpResponse(pred) in url.py: urlpatterns = [ path('', home), path('recommend',recommend) ] when i go to the route of recommend(localhost:8000/recommend), it returns the JSON that i want without any problem. But, when i try to do this with javascript: <script> let recs; ///servers requests to recommendations function recommend(){ const req = new XMLHttpRequest() req.open('GET','/recommend') req.onload = () =>{ recs = JSON.parse(req.response) console.log(recs) } } window.onload = ()=>{ recommend() console.log('window.load') } </script> it gives me an error, the browser says me this: Failed to load resource: the server responded with a status of 404 (Not Found) and django says: Using the URLconf defined in V_store.urls, Django tried these URL patterns, in this order: recommend The current path, favicon.ico, didn't match any of these. How can i get this json response with javascript and transform it into an object ? -
how to retrieve avatar with django-allauth from templates
I have the following configuration in my settings.py: # Provider specific settings SOCIALACCOUNT_PROVIDERS = { 'linkedin_oauth2': { # For each OAuth based provider, either add a ``SocialApp`` # (``socialaccount`` app) containing the required client # credentials, or list them here: 'APP': { 'client_id': '', 'secret': '', 'key': '' }, 'SCOPE': [ 'r_liteprofile', 'r_emailaddress' ], 'PROFILE_FIELDS': [ 'id', 'firstName', 'lastName', 'emailAddress', 'profilePicture', ] } } I am trying to call the get_avatar_url function from a template. I am using the following line but it is not working: <img src="{{request.user.socialaccount_set.all.0.get_avatar_url}}" width="50" height="50" alt="no-image"> Any suggestions? -
Javascript not rendering conditional statements - Django Project
Currently am building a file that is based on older Django version of Blueimp's jQuery File Upload. Working multiple bugs as I 1.) learn and 2.) bring it up to Django version 3.0.8. I can click on "Add Files", choose my file and then it will show some information on the screen as shown. The only item that renders correctly is the file size and the "open_tv" and "close_tv" variables. The rest of the javascript is verbatim from the code. I am unable to determine the fix for this. Output ${name} 11.66 KB Error: {{if error === 'maxFileSize'}}File is too big {{else error === 'minFileSize'}}File is too small {{else error === 'acceptFileTypes'}}Filetype is not allowed {{else error === 'maxNumberOfFiles'}}Max number of files exceeded {{else}}${error} {{/if}} views.py from django.shortcuts import render, redirect from .models import RequestAttachment, ServiceRequest from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest from django.conf import settings import os def esr_submit(request): # used to generate random unique id import uuid # settings for the file upload # you can define other parameters here and check validity late in the code options = { # maximum file size (must be in bytes) "maxfilesize": 10 * 2 ** 20, # 10 mb # … -
Django password reset issue
I saw a tutorial and I implemented a password resetter through email. The email sending part works fine and I get the email after clicking it I get redirected to reset password page. But after I give the new password and click Submit it gets redirected to the same page. urls.py path('password-reset/',auth_views.PasswordResetView.as_view(template_name='password_reset.html'),name='password_reset'), path('password-reset/done/',auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'),name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'),name='password_reset_confirm'), path('password-reset-complete/',auth_views.PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'),name='password_reset_complete'), password_reset_confirm.py {% extends "base.html" %} {% load static %} {% block head_block %} <link rel="stylesheet" type="text/css" href="{% static 'index.css' %}"> {% endblock head_block %} {% block body_block %} {% csrf_token %} <form method="post"> {% csrf_token %} <input type="password" name="" id=""> <input type="submit" value="Reset"> </form> {% endblock %} Any idea where the problem is? -
Django and CK editor
I am using CKEditor as my rich-text editor in my blogging website. But the issue I am facing is that while I add images the resizing of the images is very difficult for new users and also I can't move my images to some other positions, unlike TinyMCE. But in a recent poll, I saw people preferring CKeditor over TinyMCE. So I assume my code lacks something. Help me add new functionalities to the ck-editor. models.py: from django.db import models from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): body = RichTextUploadingField() views.py from django.views.generic import DetailView from .forms import * from .models import Post class PostDetailView(DetailView): model = Post template_name = "home.html" forms.py: from django.forms import ModelForm from django import forms from .models import * class PostForm(ModelForm): class Meta: model = Post fields = '__all__' settings.py: INSTALLED_APPS = [ ...... "editor", "ckeditor", "ckeditor_uploader", ] CKEDITOR_UPLOAD_PATH = 'uploads/' urls.py: urlpatterns = [ path("admin/", admin.site.urls), path("", include("editor.urls")), # path("ckeditor/", include("ckeditor_uploader.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML file: <p>{{ post.body|safe }}</p> -
Executing custom SQL directly does not work but shows no error
I have a funtion in my views.py that execute a sql query directly in the database, like this cursor.execute("INSERT INTO table1(field1,field2,field3) VALUES(%s,%s,%s)",[value1,value2,value3]) cursor.execute("UPDATE table1 SET field1=%s,field2=%s,field3=%s WHERE field4=%s",[value1,value2,value3,value4]) The problem is when the function run not show me errors and in the debug mode returns "POST /something/20/ HTTP/1.1" 200 but in the database the data it is not saved. I use django 1.8.19, django-pyodbc-azure 1.8.17 and the database is on sql server 2016. Any help is really appreciated. -
How to list all favourite posts of a user in django rest framework
Hey guys I have been trying to implement to list all favourite posts of a user using django rest framework and it is only showing me an empty dictionary. I am quite new to this and doesn't understand the problem is with my view or serializer. Do have a look at the codes class PostSerializer(serializers.ModelSerializer): user = UserSerializer(many=True) post_date = serializers.ReadOnlyField() # image = serializers.SerializerMethodField('validate_image_url') postimage_set = PostImageSerializer(many=True) class Meta: model = Post fields = ['id','title', 'post_date', 'favourite', 'user', 'image', 'postimage_set',] class PostFavouriteListSerializer(serializers.ModelSerializer): favourite = PostSerializer(many=True, read_only=True) class Meta: model = Post fields = ['favourite',] view class FavouritePostAPIView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, *args, **kwargs): user = self.request.user favourite_posts = user.post_favourite.all() #post_favourite is related_name, #favourite is in post model serializer = PostFavouriteListSerializer(favourite_posts) #print(serializer.data) return Response(serializer.data, status=status.HTTP_200_OK) Thanks -
how to access more than one filed from one model to another model
I want to use the two variables asset_name and asset_image from the model asset_details class asset_details(models.Model): asset_name = models.CharField(max_length = 100 ) asset_image = models.ImageField(upload_to = 'media/assets',verbose_name='Asset Images',) def __str__(self): return self.asset_name to another model 'test' in the same app class test (models.Model): signal_title = models.CharField(max_length = 100) asset = models.ForeignKey(asset_details,related_name="_name", on_delete=models.CASCADE) asset_image = models.ForeignKey(asset_details,related_name="_image", on_delete=models.CASCADE) i am not able to use the asset_image from asset_details model , all what i am getting is the asset_name from the model asset_details .i want to use the asset_image as well, what are the changes required in the above models ? -
How to send a message though a django signal?
In Django 3.0, is it possible to send a message with django.contrib.messages from a Signal ? Because I try to send a message each time a user has been added or removed from a new group using this kind of signal: @receiver(m2m_changed) def user_group_changed(action, instance, model, **kwargs): if model == Group and action == 'post_add': # Do some stuff messages.warning(request, "Message text") But I obviously need the request argument to call the function, which I don't have with the signal. Any simple solution ? -
Error: Reverse for 'article-detail' not found. 'article-detail' is not a valid view function or pattern name
I'm trying to use reverse in one of my model functions, but when I put the name of the url in the reverse, it shows the error of the title, and I'm not sure why this is happening, here's the code of the urls and the models. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length= 255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('article-detail', args =(str(self.id))) app/urls.py from django.urls import path from app1 import views from .views import PostView, ArticleDetailView, AddPostView app_name = 'app1' urlpatterns = [ path('register/', views.register, name = 'register'), path('user_login/', views.user_login, name = 'user_login'), path('post/', PostView.as_view(), name = 'Post'), path('article/<int:pk>', ArticleDetailView.as_view(), name = 'article-detail'), path('add_post/',AddPostView.as_view(), name='addpost') ] urls.py from django.contrib import admin from django.urls import path, include from app1 import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name = "index"), path('app1/', include('app1.urls')), path('logout/', views.user_logout, name='logout') ] I would appreciate a lot if someone could tell me why this error is showing, I'm sure that it is in the last line of models.py, but I don't understand why it's … -
Saving Upvotes and Downvotes to a Comment model in through a view in django
Currently I have an Upvote and Downvote field in my Comment model and I want to adjust their values through a clickable url linked to the comments. (Later Im planning on implementing AJAX) Right now though the Links Ive implemented add upvotes and downvotes but they don't save to the db so when I refresh the post the upvote or downvote is gone. I basically want to know how to save the changes to the model through a view. models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.ForeignKey(User, on_delete=models.SET_NULL,null=True) title = models.CharField(max_length = 1999, default='1') slug = models.SlugField(max_length = 300,unique=True) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) Upvote = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='comment_upvotes') Downvote = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='comment_downvotes') class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on {self.post}' pre_save.connect(slug_generator, sender=Comment) views.py def Upvote_comment(request, year, month, day, post, comment_id = None ): post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day) comments = post.comments.filter(active=True) comment = Comment.objects.get(id=comment_id) comment_form = CommentForm(data=request.POST) user = request.user if (user != None): if user in comment.Upvote.all(): comment.Upvote.remove(user) comment.save() else: comment.Upvote.add(user) if user in comment.Downvote.all(): comment.Downvote.remove(user) comment.save() comment_form = CommentForm() return render(request,'posts/post/detail.html', {'post':post , 'comments': comments,'comment_form': comment_form }) def Downvote_comment(request, year, … -
What's the default encoding for Sha1 in Python 2?
I have an Api code from Python 2 is as below: dataStr = request.POST['data'] data = json.loads(dataStr) key_string = data.get('key') seed = data.get('seed') guid = data.get('guid') sha1 = hashlib.sha1() yesStr = seed + 'yes' + key_string + 'ke.yp.ad' + guid sha1.update(yesStr) yesValue = sha1.hexdigest() resp = { 'data': yesValue, 'place_id': str(record.GroupNumber) } return HttpResponse(resp) now I am upgrading it to python 3, but sha1.update must use an encoded string. but I don't know what the encoding format was. so far I tried sha1.udpate(yesStr.encode("utf-8")) sha1.udpate(yesStr.encode("ascii")) sha1.udpate(yesStr.encode("latin1")) but none of them is matching the old string. Can anyone help? thanks. -
ModuleNotFoundError: No module named 'wagtail'
I am using wagtail with Django, so far the installation has been succesful.Django is runing and Wagtail too when I go the admin url. but I can't login as an admin cause I can't createsuper with the command python manage.py createsuperuser.It displays ModuleNotFoundError: No module named 'wagtail' I am using python 3.7,any help will be appreciated -
how to fetch table field in other field
I have a cart and subcategory model. I want to fetch the price of the service. How I fetch the price of service in the price field. Here is my models.py class SubCategory(models.Model): name = models.CharField(max_length=254, unique=True) id_parent = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) price = models.IntegerField() status = models.BooleanField(default=True) def __str__(self): return self.name class Cart(models.Model): user = models.ForeignKey('accounts.User', related_name="carts", null=True, on_delete=models.SET_NULL) quantity = models.IntegerField(default=1) service = models.ForeignKey('accounts.SubCategory',null=True, on_delete=models.SET_NULL) price = models.ForeignKey('accounts.SubCategory', on_delete=models.CASCADE, default=None, blank=True, related_name='subprice') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.price.price) -
Loading a resource only once in django
I need to load an object (stored in a pickle) and that resource will be used to respond to most of my API calls (it is an AI model). I am trying to find how can I load that pickle file only once in my django app and not every time I respond to a request. I would love if anyone can provide me some pointers... -
Adding multiple signals to User model creates record in forst table but not the second
I am using the standard django.contrib.auth.models User model and have extended it to create a Profile model with a one to one relationship with User to hold the profile picture. The signal for this is working fine. I since added another model, Roles, which needs a regular foreign key to User as a user can have multiple roles. The latter gives consistent errors no matter how I try to configure it including giving the fields different related_name in case it was confused which was which as well as having the Role model with a relationship to Profile rather than User but no matter how I seem to tackle it, I can't get the signal to work. relevant models.py file code is as follows: models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... class Role(TimeStampedModel): user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.IntegerField('Roles',choices=Roles.choices, default=0) ... signals.py: from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from core.models import Profile, Role @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Role.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() instance.role.save() The debug error I am getting is as follows: AttributeError at /login/ 'User' object has no attribute 'role' Request Method: POST … -
Django Rest Framework with Django Integration
I have an API hosted at api.myproj.com which was built in Django. I want to know the best options to connect a frontend. To be specific, I want to build a frontend dashboard that implements api.myproj.com. I was thinking I could make a new Django project that just GET and POST to api.myproj.com. Is this the best way to connect an external frontend? Thanks! -
Is there an automatic way to delete many rows matching a given condition from many tables?
I have a Postgres database containing many tables, each containing many rows, with many relations of all types between these different tables. If I add a new column should_delete to all of these tables, is there some automatic way I can have all rows WHERE should_delete = true deleted, without having to manually specify each table that rows should be deleted from, or manually order queries so that rows are deleted before other rows referencing them (and so avoid errors due to constraints failing, e.g. by deleting a row referenced by a foreign key before the row containing the foreign key, even if both rows contain should_delete = true and so should be deleted)? This should ultimately result in all rows marked should_delete = true being deleted, and no rows marked should_delete = false being deleted, but should only result in an error if there's no way to delete only rows marked should_delete = true without violating a constraint. If there's no pure Postgres way to achieve this, I am also using Python and Django to access this database, and so it would also be acceptable if there is a Python package that could be used to do this. -
ajax test returns false even though the http request does contain the XMLHttpRequest parameter
I have a function view. I want it to test whether the request received is an AJAX request or not, and do different things based on the result of this check. The function is really unimportant. I've actually replaced it with a three line-function just to check if the request comes out to be AJAX, but the result is still false. According to the django website, request.is_ajax(): Returns True if the request was made via an XMLHttpRequest, by checking the HTTP_X_REQUESTED_WITH header for the string 'XMLHttpRequest'. Most modern JavaScript libraries send this header. If you write your own XMLHttpRequest call (on the browser side), you’ll have to set this header manually if you want is_ajax() to work. So in my javascript code I made sure to set the header (after creating and opening the XHTML connection): request.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest'); Finally, I fired up tshark to look at the http header of the packets, and sure enough, the header field is there: Hypertext Transfer Protocol GET /?&sort_options=most-comments HTTP/1.1\r\n ..... Request Method: GET Request URI: /?&sort_options=most-comments Request URI Path: / Request URI Query: &sort_options=most-comments Request URI Query Parameter: sort_options=most-comments ....... **HTTP_X_REQUESTED_WITH: XMLHttpRequest\r\n** ...... So it's clearly there. In my view, I cut everything … -
How to validate or restrict some files like ".exe" while uploading using django-ckeditor or CKEditor?
I am using django-ckedior, and wants to restrict some files or wants to allow some extension files only to upload using the same editor. Any help is appreciated. Thanks