Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"module 'channels' has no attribute 'layers'" error in Django ASGI application
In my app, after any user logged in, send status info to other users with channels, celery and websocket. @shared_task def send_status_info(user,status): channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( "all_users", { 'type': 'send_status_info', 'message':{"user":user.username,"status":status} } ) for this, I use the following settings as shown official document. CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } The application although it is running in development environment, it does not work in production environment. As web server I try only daphne or daphne+gunicorn but I get this error on both: "module 'channels' has no attribute 'layers'". Thanks for help. -
Saving multiple records in django models
I've designed a table to fetch multiple inputs in Django. How can I save all the rows of the table at the same time in models of the app each being a different entity. -
How to implement django SSO using dj-rest-auth and django-rest-framework-simplejwt
Has anyone implemented this experimental feature JWTTokenUserAuthentication backend? So I've been trying to build a Django project that handles authentication centrally on a standalone basis using django-rest-framework-simplejwt. And other Django Rest Framework projects that use this for authentication. All projects will have their own databases. I am not quite sure what goes into the database section in settings.py of both the auth project and other projects. The documentation mentions something about JWTTokenUserAuthentication backend as an experimental feature and is quite inadequate. I have done some research and found I may have to use a remote user login or set up a proxy server. Can someone point me in the right direction? -
django model field for sets of values
I have a django model called Product. I wish to have a set of values. Specifically, each product will have different sizes (say 500 mg, 1 g, bulk order; the specific sizes will be differ for each product), along with it, I should have corresponding cost. For example, 1g - $500; 5g - $1500; bulk order - ask for quote. For another product, this could be: 500mg - $100; 1g -$170; 10g -$1000; Which django model field should I use? How can I implement this feature? Thanks! -
Django - Text Isn't Moving Down?
so I made a class and named it ">My Hero Academy<" I am trying to make it move down But its not moving down I am not sure whats the problem Image I am trying to move it lower then my title then a little left but its not moving at all <body> <div class="sidenav2"> <h5>One Piece</h5> </div> </body> </html> {% endblock %} my full home page code {% extends 'main/base.html' %} {% block title%} home {% endblock %} {% block content %} <html> <head> <style type="text/css"> .sidenav2 a { padding:6px 8px 6px 216px; left:100px; top:100px; text-decoration: none; font-size:35px; color: #818181; display:block; } </style> </head> <body> <div class="sidenav2"> <h5>My Hero Academy</h5> </div> </body> </html> {% endblock %} -
Python: TypeError: can only concatenate str (not "int") to str
This happens when I was trying to retrieve fields from a django model object ---> 52 def __str__(self): 53 return 'cpu: {%d}'.format(self.cpu_index) 54 TypeError: can only concatenate str (not "int") to str Also tried with % where cpu_index is an int and the same case happens with decimal.Decmial -
is it posible to limit objects displayed on the Admin dashboard using permissions in django?
Any way I can add permission for a whole model where only users meeting a certain condition e.g belonging to a certain country can view the objects in the Admin dashboard? I'm using Django gurdian for permissions. To be more specific, I only want the Items here https://github.com/CodeForAfrica/gmmp/blob/master/gmmp/settings.py#L244 to only be visible to users in a certain country -
Django custom user data `first_name` and `last_name` while signin
I'm not getting user first_name and last_name while i returning the data after user successfully signedin, but i'm getting other data except first_name and last_name. Any help would be appreciated. Thank you so mcuh in advance. serializers.py : class UserLoginSerializers(serializers.ModelSerializer): device_type = serializers.CharField(allow_blank=True) device_token = serializers.CharField(allow_blank=True) email = serializers.CharField(allow_blank=True) password = serializers.CharField(allow_blank=True,label='Password',style={'input_type':'password'},write_only=True) phone_number = serializers.CharField(allow_blank=True) token = serializers.CharField(allow_blank=True, read_only=True) country_code = serializers.CharField(allow_blank=True) isotp_verified = serializers.CharField(allow_blank=True,read_only=True) class Meta: model = User fields = ['phone_number','password','device_type','device_token','token','country_code','isotp_verified', 'email', ] def validate(self,data): email = data['email'] phone_number = data['phone_number'] password = data['password'] device_type = data['device_type'] device_token = data['device_token'] country_code = data['country_code'] if email: user_qs = User.objects.filter(email__iexact = email) if user_qs.exists() and user_qs.count() == 1: print('Count :',user_qs.count()) else: raise APIException400({ 'success' : 'False', 'message' : 'User with this email does not exist' }) user_obj = '' if user_qs.exists() and user_qs.count() == 1: user_obj = user_qs.first() if user_obj: if not user_obj.check_password(password): raise APIException400({ 'success' : 'False', 'message' : 'Wrong Password' }) payload = jwt_payload_handler(user_obj) token = jwt_encode_handler(payload) data['token'] = 'JWT '+str(token) data['email'] = user_obj.email data['username'] = user_obj.username data['user_id'] = user_obj.id data['phone_number'] = UserOtherInfo_obj.phone_number data['country_code'] = UserOtherInfo_obj.country_code data['isotp_verified'] = UserOtherInfo_obj.isotp_verified data['first_name'] = user_obj.first_name data['last_name'] = user_obj.last_name return data -
I want to reconstruct django view
view.py class ListDoctor(generics.ListCreateAPIView): queryset = DoctorList.objects.filter(h_code="h_0001") serializer_class = DoctorListSerializer def list(self, request): doctor = DoctorList.objects.values() return Response( { "doctor": doctor } ) data: "doctor": [ { "doctorname": "testname1", "position": "ST", "h_code_id": "h_0000", "d_code": "d_0000" }, { "doctorname": "testname2", "position": "CB", "h_code_id": "h_0000", "d_code": "d_0001" }, { "doctorname": "testname3", "position": "CM", "h_code_id": "h_0001", "d_code": "d_0002" }, { "doctorname": "testname4", "position": "GK", "h_code_id": "h_0001", "d_code": "d_0003" } ] I would like to change the above code like below. "h_0000" [ { "doctorname" : "testname1", "position" : "ST", "h_code_id: "h_0000", "d_code" : "d_0000" }, { "doctorname" : "testname2" "position" : "CB" "h_code_id: "h_0000", "d_code" : "d_0001" } "h_0001" [ { "doctorname" : "testname3", "position" : "CM", "h_code_id: "h_0001", "d_code" : "d_0002" }, { "doctorname" : "testname4" "position" : "GK", "h_code_id: "h_0001", "d_code" : "d_0003" } How can I change the data above to look like below? We sincerely appreciate those who respond. h_code_id(h_0001, h_0002, h_0003...) will increase gradually. Therefore, it cannot be manually created. -
Sharing static files in Django server with webpack-quasar
I have done a project with Django as backend and quasar as frontend. I want to publish the quasar-frontend side of the project in the Django server. So, I have build production on a quasar with webpack, and I get the necessary folders with production files such as CSS, js. And I have separated them into static files and index.html due to the Django framework structure. Django server shares the static files with extra folders like this example: '/static/somenestedfolder/'. So when the Django server shares the index.html file to the client, the client can not get the static js and CSS files with error 404 not found. For example, the client requests the address to get some js files: http://127.XX.XX.XX:8000/js/some.js, but the static files are located in http://127.XX.XX.XX:8000/static/js/some.js. So, I just want to add the '/static' (or some nested folder), when the webpack build production files. Or the sharing-static-files method is incorrect: a) Should I use the python webpack-loader module?; b) there are any methods to do it? c) Can I use it on production mode the Django too? -
'user' field keeps getting nulled
I want to create something where the current logged user can create 'posts'. Here's my codes: models.py from django.contrib.auth.models import User # Posts class Post(models.Model): user = models.ForeignKey(User) date = models.DateField(auto_now_add=True) content = models.TextField(max_length=500, blank=False) forms.py class PostForm(forms.ModelForm): class Meta: model = models.Post labels = { 'content': '' } widgets = { 'user': forms.HiddenInput() } fields = '__all__' # exclude = ('user',) views.py def my_profile(request): user = request.user profile_info = request.user.userprofileinfo if request.method == 'POST': post = forms.PostForm(data=request.POST) if post.is_valid(): post.save(commit=False) post.user = user post.save(commit=True) return HttpResponseRedirect(reverse('td_app:index')) else: print(post.errors) return HttpResponseRedirect(reverse('td_app:my_profile')) else: form = forms.PostForm data = { 'user': user, 'profile_info': profile_info, 'form': form } return render(request, 'td_app/my_profile.html', context=data) I have declared the 'user' field to be 'hidden' since we don't want users pretending to be someone else when they post - the 'user' field should automatically register the current logged user. However it keeps giving me this error: <ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required.</li></ul></li></ul> When I do this instead: class PostForm(forms.ModelForm): class Meta: model = models.Post labels = { 'content': '' } # widgets = { # 'user': forms.HiddenInput() # } fields = '__all__' exclude = ('user',) It will now give me a null error: The above exception (null … -
Finding unique query values when using Django/Python
Hey guys I'm trying to print out a page with all the available categories of an auction site on it. Right now it's printing out every instance of whats in the table. For instance, there are multiple print outs of Animals as a category - but I just want it to show one. What's the best way to do this? I tried the "distinct" method but it doesn't seem to be doing anything. Below is my relevant code: views.py: def categories(request): query = NewPost.objects.all().distinct() return render(request, "auctions/categories.html", { "queries": query }) categories.html: {% extends "auctions/layout.html" %} {% block body %} <h2>Categories</h2> {% for query in queries %} <li><a href="/categories/{{ query.category }}">{{ query.category }}</a></li> {% endfor %} {% endblock %} -
'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
I'm trying to mock an image for the test case scenario where a user uploads a photo. Upon trying to create it, I'm getting the error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte I have followed the following topics to do the very such thing but I'm still getting this error. Unit Testing a Django Form with a FileField Django testing model with ImageField. How can remedy this so that I get a working mock image for my test? class RedundantImageUpload(TestCase): @classmethod def setUpTestData(cls): f = BytesIO() image = Image.new("RGB", (100, 100)) image.save(f, 'png') f.seek(0) test_image = SimpleUploadedFile( "test_image.png", content=open(f.read(), 'rb'), content_type="image/png" ) user = User.objects.create_user("User") import pdb; pdb.set_trace() form = PhotoForm({'title': "Image Title"}, {'source': test_image}) instance = form.save(commit=False) instance.photographer = user instance.save() cls.submitted_form = PhotoForm( {'title': "Image Title"}, {'source': test_image} ) def test_image_upload_path_exists(self): print(self.submitted_form.errors) -
Django redirect to external link with parrameters
everyone. I have problem with redirection. I have urls: path('some/<int:pk>/', RedirectView.as_view(), name='redirect'), My target is: in RedirectView I have to get pk, take it and pass to 'url' variable inside view: class RedirectView(RedirectView): ? any_url = Model2.objects.filter(name='something') ? link = any_url.name ? any_url.save() ? url = link + <int:pk> ? redirect to url I mean, I have to take pk from url and attach it to external link, that I got from db. pk is id from Model_1. external url is any_url I take from Model_2, it was saved like CharField. Also, when I take url address from db I need resave this instance. I understand how it works if I make redirect inside project (thru pattern_name). Could you help me? -
Why DB dont save comment(Django)
The entered comments in the form are not saved in the database, and are not displayed anywhere. After clicking the save button, it simply redirects to another page and the comments are not displayed. I'm trying to make a form for entering comments directly from the site page, I have already configured it from the administration panel. Thanks! models.py class BarbersPage(ListView): model = Post template_name = 'main/barbers.html' context_object_name = 'posts' def post_new(request): post = get_object_or_404(Post) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): form.save() return redirect('barbers') else: form = CommentForm() return render(request, 'main/post_detail.html', {'form': form}) views.py class BarbersPage(ListView): model = Post template_name = 'main/barbers.html' context_object_name = 'posts' def post_new(request): post = get_object_or_404(Post) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): form.save() return redirect('barbers') else: form = CommentForm() return render(request, 'main/post_detail.html', {'form': form}) barbers.html {% for post in posts %} <img src="{{MEDIA_URL}}{{post.photo.url}}" width="800" /> <h3> {{ post.name_barber}} </h3> <p>{{ post.description}}</p> <h3> Comments.. </h3> {% if not post.comments.all %} no comments yet...<a href = "#">Add one</a> {% else %} {% for comment in post.comments.all %} <strong> {{ comment.name }} {{ comment.add_date }} </strong> <p>{{comment.body }}</p> {% endfor %} {% endif %} {% endfor %} post_detail.html <h1>New comment</h1> <form method="POST" class="post-form">{% … -
How to avoid the COUNT query Django's paginator does?
Paginator.page() causes the evaluation of the cached property count, which performs a COUNT query on the database. My problem is that the average query execution time for that COUNT is 1.06 seconds while the average time of the main query is 1.04 seconds. In effect I have a duplicated query. Is there a way to avoid that COUNT query? -
How can I include a python module in order to run a server on django?
I'm very new to coding python, and I'm following a tutorial on django for creating a simple website: < https://docs.djangoproject.com/en/3.1/intro/tutorial01/ > The problem I'm encountering is when I attempt to execute 'manage.py runserver'. I receive a "Module not found" error for my 'urls.py' file. This sort of makes sense as I created the file myself because I needed to, whereas the rest were automatically generated. Does anyone know of any way I can fix this error, and get the 'urls.py' file on the path or make it accessible? If any extra information is needed I can try to provide it. -
Comments aren't printing out on my Django Python site
Hey guys I'm making an auction site and I'm having trouble with the comments for some reason. I'm not getting an error when I add a new comment but when I try to print out the results, I'm getting nothing - no errors - just nothing. When I do a query in my view for Comments.objects.all() and try to print it to the terminal, I'm getting nothing printed out. I'm thinking perhaps it's something to do with the action in the form? Or the urls.py? Anyone see why? I provided relevant code - please let me know if you need any more. Thanks! urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("auction", views.auction, name="auction"), path("watchlist/<str:username>", views.watchlist, name="watchlist"), path("categories", views.categories, name="categories"), path("post/<str:title><str:description><int:price><str:category>", views.post, name="post"), path("bid/<str:username>", views.bid, name="bid"), path("comment", views.post, name="comment"), path("closeAuction", views.closeAuction, name="closeAuction") ] views.py: def comment(request): username = request.POST.get("username") itemID = request.POST.get("itemID") comment = request.POST.get("comment") new = Comment.objects.create(username = username, comment = comment, itemID = itemID) new.save() commentQuery = Comment.objects.all() print(commentQuery) return render(request, "auctions/post.html", { "commentQuery": commentQuery}) models.py: class Comment(models.Model): username = models.CharField(max_length=64) comment = models.CharField(max_length=64) itemID = models.CharField(max_length=64) post.html: <form name="comment" action="/post/{{p.title}}{{p.price}}" method="post"> … -
Pythin Django - Disply result in html page one after each other
Python - Django def integration(request): 1. pushing config to the device 2. checking the config 3. update database with new status The function above run three tasks. How can I display the result in the html page after each result done. Now it work perfectly but I need to wait until all tasks done to see the result in the html page. Thanks, -
Adding a Condition in Payment System to include PayPal
I am trying to integrate PayPal to my E-commerce Project, so the flow of the checkout process is as following after adding items to cart: In the checkout page the user types the address and select the payment option through a radio button Now when the user selects the stripe it directs to core:payment in this template I am trying to add a condition so that if the selected payment option is paypal the paypal icons is appearing instead of the stripe payment form. Here is the models.py class Payment(models.Model): stripe_charge_id = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username Here is the views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } -----------------Shipping address codes----------------------------- payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') else: messages.warning( self.request, "Invalid payment option selected") return redirect('core:checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("core:order-summary") here is the url.py urlpatterns = [ path('payment/<payment_option>/', PaymentView.as_view(), name='payment'), here is the template <!------------Add an if statmenet if the … -
django-compressor Uncaught SyntaxError: import declarations may only appear at top level of a module
This is my JS structure: This is the beginning index.js import { elements } from './views/base'; const state = {}; const controlRandomPhrasal = async () => {} My base.js: export const elements = { searchFrom: document.querySelector('.search'), } I invoke the compressor like this: {% compress js %} <script src="{% static "phrasals/js/jquery.js" %}"></script> <script src="{% static "phrasals/js/index.js" %}"></script> {% endcompress %} How can I configure my project to avoid that error? Or can you suggest me an easier/better bundler? -
With Django, how do you update a value with the click of a button in a template?
In my app, "employees" can be assigned to different "supervisors". The html template for an individual employee page contains a list of all available supervisors. I want to put a button next to each supervisor in the list so that when you click the button, the employee.assigned_supervisor value is updated. Even once a supervisor is assigned, I'd like to be able to change which supervisor is assigned by clicking a button next to a different supervisor in the list. I've combed through the documentation and lots of other sites/examples, and all I've been able to find is examples of forms where you visit a separate page, complete/update the form, and submit. I want to update the value just by clicking the button. I'm using Django 3.1. models.py class Supervisor(models.Model): name = models.CharField(max_length=30) class Employee(models.Model): name = models.CharField(max_length=30) assigned_supervisor = models.ForeignKey(Supervisor) forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['name', 'assigned_supervisor'] views.py def new_employee(request): if request.method != 'POST': form = EmployeeForm() else: form = EmployeeForm(data=request.POST) if form.is_valid(): form.save() return redirect('my_app:employees') context = {'form': form} return render(request, 'schedules/new_employee.html', context) employee.html <p>Employee: {{ employee }}</p> <p>Available Supervisors:</p> <li> {% for supervisor in supervisors %} <li>{{ supervisor }}</li> <!-- Insert "Assign" button … -
AttributeError at / 'list' object has no attribute 'values'
I am new to django and trying to build social network system. Here in my view I am importing my friend list using profile variable. Now I want to show post only from my friends. but cant make the logic for how to filter through all the post. this is the view: @login_required def post_comment_create_and_list_view(request): profile = Profile.objects.select_related('user').get(user=request.user).get_all_friends_list() #profile contains list of the friends i have queryset = Post.objects.all_posts().filter(author__icontains=profile.values()) #post form post_form = PostModelForm() if 'submit_p_form' in request.POST: post_form = PostModelForm(request.POST or None, request.FILES or None) if post_form.is_valid(): instance = post_form.save(commit=False) instance.author = profile instance.save() post_form = PostModelForm() messages.success(request, 'Post published') return redirect('posts:main_post_list') #comment form comment_form = CommentModelForm() if 'submit_c_form' in request.POST: comment_form = CommentModelForm(request.POST or None) if comment_form.is_valid(): instance = comment_form.save(commit=False) instance.user = profile post_id = request.POST.get('post_id') instance.post = Post.objects.get(id=post_id) instance.save() comment_form = CommentModelForm() return redirect('posts:main_post_list') context = { 'queryset': queryset, 'profile': profile, 'post_form': post_form, 'comment_form': comment_form, } return render(request, 'posts/main.html', context) this is the post model: class PostManager(models.Manager): def all_posts(self): posts = Post.objects.prefetch_related('author',"comment_posted__user", "comment_posted__user__user",'likes') return posts class Post(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, db_index=True) content = models.TextField(db_index=True) image = models.ImageField(upload_to='posts', validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])], blank=True) likes = models.ManyToManyField(Profile, blank=True, related_name='profile_liked') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE, … -
Django: Integrating PayPal to payment options
Helloo, I need guidance on how to integrate PayPal radio buttons to replace my Django Radio buttons for the found in the below link https://developer.paypal.com/demo/checkout/#/pattern/radio I have set my payment options in the forms.py and I am stuck and don't know how to proceed The stripe payment method is working perfectly fine I just want to add the PayPal payment option. This is how my project is arranged: Forms.py PAYMENT_CHOICES = ( ('S', 'Stripe'), ('P', 'Paypal') ) class CheckoutForm(forms.Form): ----address related forms----------------------------------- payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES) Here is the checokout template <h3>Payment option</h3> <div class="d-block my-3"> {% for value, name in form.fields.payment_option.choices %} <div class="custom-control custom-radio"> <input id="{{ name }}" name="payment_option" value="{{ value }}" type="radio" class="custom-control-input" required> <label class="custom-control-label" for="{{ name }}">{{ name }}</label> </div> {% endfor %} </div> here is the views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } -----------------Shipping address codes----------------------------- payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') else: messages.warning( self.request, "Invalid payment option selected") return redirect('core:checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return … -
Django (Password_change) doesn't work url
I'm learning Django book named by (Django for beginners) I have a problem with password _change Below my code from urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('',include('pages.urls')), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/',include('django.contrib.auth.urls')), ] Next is password_change_form.html {% extends 'base.html' %} {% block title %} Password Change {% endblock %} {% block content %} <h1>Password change</h1> <p>Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly.</p> <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" class="btn btn-success" value="Change my password"> </form> {% endblock %} my content does'nt linking to password_change_form.html Via versa linking to password_change from Django adminstration