Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Default user model TypeError at /auth/users/ create_user() missing 1 required positional argument: 'username'
When I request to create a user using djoser Endpoint /user/. But it says create_user() missing 1 required positional argument: 'username' I am using postman to post the request and I am passing the username as you can see below: I don't know where the problem lies. I have also changed "username" to "name" but it did not work. Any help would be highly appreciated .Thank you very much 😊❤️❤️❤️. I will show you what you will ask me to show. -
Unknown error while retrieving django queryset objects from redis
In the below code snippet, I am trying to bring the cached objects from redis , while doing it facing the below error The use case is caching the top 30 comment objects at the 1st API call , so the when the API is called for 2 nd time, the cached objects will be passed to serialzers , avoiding the querysets Caching the comments objects featured=StockUserComments.objects.filter(some condition) qs=StockUserComments.objects.filter(some condition) latest=StockUserComments.objects.filter(some condition) all =list(chain(featured,qs,latest)) redis_client.set("feeds:top_comments", str(all[:30]),ex=1800) retrieving the objects top_comments = redis_client.get("feeds:top_comments") if top_comments: print("from cache") all = ast.literal_eval(top_comments.decode("utf-8")) error Traceback (most recent call last): File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "E:\stocktalk-api-platform\apps\stock_dashboard\views.py", line 748, in get all = ast.literal_eval(top_comments.decode("utf-8")) File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\ast.py", line 59, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\ast.py", … -
Django queryset filter by 6 hour interval
I have a model class TestRequest(models.Model): created_at = models.DateTimeField(auto_now_add=True) is_accepted = models.BooleanField(default=False) What i want is to send an email to admin if the TestRequest is not accepted in every 6 hours once request created. How can i query the data in the cron function (which is running every minute) where i can fetch all the TestRequest which fall in the 6 hour interval and email to admin. -
Store Auto Generated Username into Database DJango
I am creating a registration form that accepts the end-user's Firstname, Lastname, email, and password. the program is designed to auto-generate a username. I have created a function that auto generates a unique username; however, I am new to Django and unsure how to get my auto-generated username to store into the database along with the user's info. Currently, the program is storing the user's manually input info. -
display data in multiple columns with for loop
I'm sure this is a simple answer but for the life of me I cant figure / find out how to go about this. I want to display blog posts from my data base in three equal columns. When I start looking into the bootstrap docs this is the code given. <div class="container"> <div class="row"> <div class="col-sm"> One of three columns </div> <div class="col-sm"> One of three columns </div> <div class="col-sm"> One of three columns </div> </div> </div> However If I go to implement it I dont understand how i would be able to put the for loop on it without it repeating everything 3 times. IE: {% for post in posts.all %} <div class="row"> <div class="col-sm"> <img class="post-image" src="{{ post.image.url }}" /> </div> <div class="col-sm"> <img class="post-image" src="{{ post.image.url }}" /> </div> <div class="col-sm"> <img class="post-image" src="{{ post.image.url }}" /> </div> </div> {% endfor %} If you could please point me in the right direction on how to go about this it would be very much appreciated bootstrap is not a requirement. -
Django deployment Failed to load resource: the server responded with a status of 404 (Not Found)
I have some product pictures uploaded in media folder that displays fine in development server, but after deployment I receive the 404 ressource not found error. In settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'node_modules')] STATIC_ROOT = os.path.join(BASE_DIR, 'productionStatic') STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' In urls.py from django.contrib import admin from django.urls import path from index import views from index.views import indexPage, hdnytorv from webshopRestaurant.views import hd2900_webshop_Main, AddressCheckForDeliverability, ChangeItemQuantity from webshopCustomer.views import TakeawayCheckout, totalPriceDeliveryPossible, DeliveryForm, PickUpForm, localDeliveryCheckoutAddressCheck, Payment, PaymentComplete from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), path('', indexPage.as_view(), name = 'index'), path('hdnytorv', hdnytorv.as_view(), name='hdnytorv'), path('hd2900', views.hd2900.as_view(), name='hd2900'), path('hd2900_takeaway_webshop', hd2900_webshop_Main.as_view(), name="hd2900_takeaway_webshop"), path('check-address-for-deliverable', AddressCheckForDeliverability.as_view()), path('changeItemQuantityInBasket', ChangeItemQuantity.as_view()), path('isPriceAboveDeliveryLimit', totalPriceDeliveryPossible.as_view()), path('hdbynight', views.hdbynight.as_view(), name='hdbynight'), path('takeawayCheckout', TakeawayCheckout.as_view()), path('deliveryFormCheckout', DeliveryForm.as_view()), path('pickupFormCheckout', PickUpForm.as_view()), path('local_delivery_checkout_is_address_deliverable', localDeliveryCheckoutAddressCheck.as_view()), path('localDeliveryPayment', Payment.as_view()), path('paymentComplete', PaymentComplete.as_view()), ] #When in production medida url must always be added to urlpatterns #if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) To display the product in view I have in my html template <img class="card-img embed-responsive-item" src="{% get_media_prefix %}{{ item.product.image_path }}" alt="{{item.meta_description}}"> The pictures are uploaded to this location django_project_folder/media/productImages. I have assured that it is owned by www-data group and also media and all … -
function create_user in CustomUserManager didn't work
I create a custom user model and manager but the create_user function in manager doesn't work. what is my fault? this is my model: class User(AbstractUser): email = models.EmailField(null = True, blank = True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True) is_owner = models.BooleanField(default=False) is_advisor = models.BooleanField(default=False) name = models.CharField(max_length=40, null = True, blank = True) image = models.ImageField(blank = True, null=True) data_join = models.DateTimeField(default = timezone.now) code_agency = models.IntegerField(null=True, blank=True, default=0) opt = models.IntegerField(null = True, blank = True) is_verified = models.BooleanField(default = False) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] objects = UserCustomManager() def __str__(self): return str(self.phone_number) class Meta: verbose_name = 'user' verbose_name_plural = 'users' and this is my manager: class UserCustomManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone_number, **extra_fields): if not phone_number: raise ValueError('The given phonenumber must be set') print(""" ======================== ======================== ======================== """) user = self.model(phone_number=phone_number, username=phone_number, **extra_fields) user.set_password("green") # Token.objects.create(user=user) user.save(using=self._db) return user def create_user(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) digits = "0123456789" print(""" ======================== ======================== ======================== """) OTP = "" for i in range(4) : OTP += digits[math.floor(random.random() * 10)] extra_fields.setdefault('opt', OTP) return self._create_user(phone_number, **extra_fields) def create_superuser(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser … -
Angular app keeps saying _user is not defined
I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/ However, I'm trying to run the app to test the join page but it keeps saying property not defined in the constructor which is from the state.service.ts file. import { Injectable } from '@angular/core'; export declare interface User { token: string; apiKey: string; username: string; } @Injectable({ providedIn: 'root', }) export class StateService { constructor() {} private _user: User; get user(): User { return this._user; } set user(user: User) { this._user = user; } } -
i got an error stating that === Cannot assign "'12'": "Cart.product" must be a "Product" instance. please do help me out in solving the issue
I have attached an image of my code where you can find the add-to-cart function and the error is on line===23 -
Django google books API totalItems is changing
I am creating an application that retrieves data from the google books API. At the very beginning I download a number of books from JSON ["totalItems"] and iterate through the for loop, calling the API in order to get another 40 items. The problem is that the number of books increases and decreases during iteration, so when, for example, on a 550 book, I get a list index out of range error. Anyone please help me download all the books? My request looks like this: requests.get(f'https://www.googleapis.com/books/v1/volumes?q={search}\ &maxResults=40&startIndex={end_range}') end_range is increased by 40 each time data is downloaded. -
Go import from specific branch github in the same repository where it is hosted
I have a repository with a golang project in github, I need to import in a module a specific branch, to make relevant modifications. It looks like this: package events_entity import ( "github.com/repository/utils/date_utils" "github.com/repository/utils/utils/error_utils" "github.com/repository/utils/utils/hour_utils" "strconv" "strings" ) The importation is always done directly from the master. I just need this module to import from a different branch. Thanks!!! -
Unable to lookup 'placedorder' on Restaurants or RestrauntsAdmin
My error : Unable to lookup 'placedorder' on Restaurants or RestrauntsAdmin i am getting this error in admin panel, i havent entered any data in placed order yet and neither in restaurants class Restaurants(models.Model): name = models.CharField(max_length=50, blank=False) address = models.CharField(max_length=50, blank=False) city = models.ForeignKey(City, on_delete=models.CASCADE) mob_no = models.IntegerField() opening_time = models.TimeField() closing_time = models.TimeField() website = models.URLField(blank=True) cover = models.ImageField(upload_to='restraunts/cover') # Create your models here. class PlacedOrder(models.Model): order_id= models.CharField(max_length=255) restraunt = models.ForeignKey(to='restaurants.Restaurants', on_delete=models.CASCADE) order_time = models.TimeField( auto_now_add=True) estimated_delivery_time = models.TimeField() actual_delivery_time = models.TimeField() food_ready_time = models.TimeField() total_price = models.DecimalField(max_digits=12, decimal_places=2) -
Custom User Primary Key - Django
I have a Django website and a format similar to google sheets in which people can add data and it shows up in a row. To the left is the number associated with that row of data. Normally I used pk which worked great because when one data row was deleted no other ones changed. Now I have 2 users and I'm separating the data based on ForeignKey fields in all of my models. The problem with this is, for example, User1 adds 1 row of data then User2 adds one row of data then User1 adds another row of data, then when User1's data is being displayed it will show 2 rows labeled 1 and 3. I need them to be specific to the user and in numerical order. It is as if I need a separate pk for each user in the same model. I temporarily fixed this by {{ forloop.revcounter }} in the forloops of the rows. This now keeps the row number in numerical order and specific to the user. The problem is that if User1 now deletes the first data row labeled #1 then now the table only shows 1 row and the data row … -
Ordering by multiple fields
I'm wanting to order a queryset based on a couple of different related fields Models.py class Appointment(models.Model): start_time = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) class Event(models.Model): start_time = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) class Job(models.Model): event = models.ForeignKey(Event, on_delete=models.SET_NULL) appointment = models.ForeignKey(appointment, on_delete=models.SET_NULL) views.py qs = Job.objects.all().order_by('event__start_time','appointment__start_time') Is this the correct way to do this? Will this always order all of the jobs in the correct order based on the associated star time? Thanks! -
The view basket.views.basket_remove didn't return an HttpResponse object. It returned None instead
Can someone explain me why am i getting this error? I am creating online store in which basket functionality depends on sessionid in cookies. Look, I have a function basked_add on every product in store, which adds specified product to basket and it works correctly without any issues. I have also a function basket_delete in basket to remove specified product from basket, and somehow it doesn't work correctly. And this is the main reason why i made this question. Function basket_delete is called by JQuery like that (equal to basked_add): 1. basket.html $(document).on('click', '#remove-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "basket:basket_delete" %}', data: { productid: $('#add-button').val(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post', }, success: function (json) { }, error: function (xhr, errmsg, err) {} }); }) 2. basket > urls.py app_name = 'basket' urlpatterns = [ path('', views.basket, name='basket'), path('add/', views.basket_add, name='basket_add'), path('delete/', views.basket_delete, name='basket_delete'), ] 3. Then function is getting executed basket > views.py from django.http.response import JsonResponse from basket.basket import Basket def basket_delete(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) basket.delete(product=product_id) response = JsonResponse({'Success': True}) return response basket > context_processors.py from .basket import Basket def basket(request): return {'basket': Basket(request)} basket > basket.py class … -
GET http://localhost:3000/product/[object%20Object] 404 (Not Found) [object%20Object]:1
I am trying to fetch image data from django using api calls, redux state is updated successfully with api call data's But the image is not loading on the page Its giving below error in console and in python terminal Not Found: /product/[object Object] [31/Jul/2021 14:44:36] "GET /api/products/image/7 HTTP/1.1" 301 0 [31/Jul/2021 14:44:36] "GET /product/[object%20Object] HTTP/1.1" 404 2724 productAction.js export const listProductImage = (id) => async (dispatch) => { try{ dispatch({ type: PRODUCT_IMAGE_REQUEST }) const {data} = await axios.get(`http://127.0.0.1:8000/api/products/image/${id}`) dispatch({type: PRODUCT_IMAGE_SUCCESS, payload: data}) }catch(error){ dispatch({ type: PRODUCT_IMAGE_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } } productReducers.js export const productImagesReducers = (state={pImage:[]}, action) => { switch(action.type) { case PRODUCT_IMAGE_REQUEST: return {loading:true, pImage:[] } case PRODUCT_IMAGE_SUCCESS: return {loading:false, pImage:action.payload } case PRODUCT_IMAGE_FAIL: return {loading:false, error: action.payload } default: return state } } ProductImageGallery.js (Template) Dispatching Code const dispatch = useDispatch() const ProductImageGallery = ({ match, productID }) => { const dispatch = useDispatch() const productImage = useSelector(state => state.productImage) const {pImage} = productImage useEffect(()=>{ dispatch(listProductImage(productID)) }, [dispatch, productID]) } models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200,null=True,blank=True) image = models.ImageField(null=True,blank=True) brand = models.CharField(max_length=200,null=True,blank=True) category = models.CharField(max_length=200,null=True,blank=True) description = models.TextField(null=True,blank=True) rating = models.DecimalField(max_digits=7, decimal_places=2,null=True, blank=True) numReviews = … -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/hello only admin/ path is defined
i am following the django instructions to build a web application hello i have done everthing after the document but this happens Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/hello Using the URLconf defined in PythonWeb.urls, Django tried these URL patterns, in this order: admin/ The current path, hello, didn’t match any of these. there must be another path as hello/ this is my code: views.py/hello: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello.") urls.py/pythonweb(my app): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include('hello.urls')) ] urls.py/hello: from django.urls import path from . import views urlpatterns = [ path('', views.index, name =('index')) ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello/', ] -
create user function doesn't work in UserCustomManager django
I write a custom user and UserCustomManager but my user don't create. this is my code of models and UserCustomManager: class UserCustomManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone_number, **extra_fields): if not phone_number: raise ValueError('The given phonenumber must be set') user = self.model(phone_number=phone_number, username=phone_number, **extra_fields) user.set_password("default") Token.objects.create(user=user) user.save(using=self._db) return user def create_user(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) digits = "0123456789" OTP = "" for i in range(4) : OTP += digits[math.floor(random.random() * 10)] extra_fields.setdefault('otp', OTP) return self._create_user(phone_number, **extra_fields) def create_superuser(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(phone_number, **extra_fields) class User(AbstractUser): email = models.EmailField(null = True, blank = True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True) is_owner = models.BooleanField(default=False) is_advisor = models.BooleanField(default=False) name = models.CharField(max_length=40) image = models.ImageField(blank = True, null=True) data_join = models.DateTimeField(default = timezone.now) code_agency = models.IntegerField(null=True, blank=True, default=0) otp = models.IntegerField(null = True, blank = True) is_verified = models.BooleanField(default = False) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] objects = UserCustomManager() def __str__(self): return str(self.phone_number) class Meta: verbose_name = 'user' verbose_name_plural = 'users' about user.set_password("default") it is ok and I wanna my custom … -
customize django model meta ordering option
I want to set ordering according to condition something like this. if self.name_format == "First name Last name": class Meta: ordering = ['first_name', 'last_name'] elif self.name_format == "Last name First name": class Meta: ordering = ["last_name","first_name"] elif self.name_format == "Last name, First name": class Meta: ordering = ["last_name","first_name"] else: class Meta: ordering = ["first_name","last_name"] How can i achieve that? -
I am trying to create a signin page but after sign in a file with 0 kb is getting downloaded and getting CSRF verification failed
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Signup Page</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'login/signuppage.css' %}"> </head> <body> <div class="login"> <div class ="form"> <h3>Sign in</h3> <form class="registration-form" method="POST"> {% csrf_token %} {% for field in form %} <p>{{ field.label_tag }} {{ field }} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <!--<input type="text" placeholder="Username"/> <input type="email" placeholder="Email ID"/> <input type="password" placeholder="Password"/> <input type="password" placeholder="Confirm Password"/>--> <button>Sign in</button> <p><a href ="#">Login</a></p> </form> </div> </div> </body> </html> Sign in page views views.py: def SignupPage(request): form = UserSigninForm() if request.method=='POST': form=UserSigninForm(request.POST) if form.is_valid(): user=form.save() auth_login(request, user) return redirect('/home/') else: form = UserSigninForm() context = {'form': form} return render(request,'login/signuppage.html',context) signin page forms forms.py: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from django.forms import ModelForm class UserSigninForm(UserCreationForm): class Meta: model = User fields=['username','email','password1','password2'] I am trying to create a signin page but after sign in a file with 0 kb is getting downloaded and getting CSRF verification failed. Request aborted as an error. I am trying not to exempt csrf token in code. What needs to be done here to resolve the issue? -
RabbitMQ, Celery and Django - connection to broker lost. Trying to re-establish the connection
Celery disconnects each time a task is passed to rabbitMQ, however the task does eventually succeed: My questions are: How can I solve this issue? What improvements can you suggest for my celery/rabbitmq configuration? Celery version: 5.1.2 RabbitMQ version: 3.9.0 Erlang version: 24.0.4 RabbitMQ error (sorry for the length of the log: ** Generic server <0.11908.0> terminating ** Last message in was {'$gen_cast', {method,{'basic.ack',1,false},none,noflow}} ** When Server state == {ch, {conf,running,rabbit_framing_amqp_0_9_1,1, <0.11899.0>,<0.11906.0>,<0.11899.0>, <<"someIPAddress:45610 -> someIPAddress:5672">>, undefined, {user,<<"someadmin">>, [administrator], [{rabbit_auth_backend_internal,none}]}, <<"backoffice">>,<<"celery">>,<0.11900.0>, [{<<"consumer_cancel_notify">>,bool,true}, {<<"connection.blocked">>,bool,true}, {<<"authentication_failure_close">>,bool,true}], none,0,134217728,1800000,#{},1000000000}, {lstate,<0.11907.0>,true}, none,2, {1, {[{pending_ack,1,<<"None4">>,1627738474140, {resource,<<"backoffice">>,queue,<<"celery">>}, 2097}], []}}, {state,#{},erlang}, #{<<"None4">> => {{amqqueue, {resource,<<"backoffice">>,queue,<<"celery">>}, true,false,none,[],<0.471.0>,[],[],[],undefined, undefined,[],[],live,0,[],<<"backoffice">>, #{user => <<"someadmin">>}, rabbit_classic_queue,#{}}, {false,0,false,[]}}}, #{{resource,<<"backoffice">>,queue,<<"celery">>} => {1,{<<"None4">>,nil,nil}}}, {state,none,5000,undefined}, false,1, {rabbit_confirms,undefined,#{}}, [],[],none,flow,[], {rabbit_queue_type, #{{resource,<<"backoffice">>,queue,<<"celery">>} => {ctx,rabbit_classic_queue, {resource,<<"backoffice">>,queue,<<"celery">>}, {rabbit_classic_queue,<0.471.0>, {resource,<<"backoffice">>,queue,<<"celery">>}, #{}}}}, #{<0.471.0> => {resource,<<"backoffice">>,queue,<<"celery">>}}}, #Ref<0.4203289403.2328100865.106387>,false} ** Reason for termination == ** {function_clause, [{rabbit_channel,'-notify_limiter/2-fun-0-', [{pending_ack,1,<<"None4">>,1627738474140, {resource,<<"backoffice">>,queue,<<"celery">>}, 2097}, 0], [{file,"src/rabbit_channel.erl"},{line,2124}]}, {lists,foldl,3,[{file,"lists.erl"},{line,1267}]}, {rabbit_channel,notify_limiter,2, [{file,"src/rabbit_channel.erl"},{line,2124}]}, {rabbit_channel,ack,2,[{file,"src/rabbit_channel.erl"},{line,2057}]}, {rabbit_channel,handle_method,3, [{file,"src/rabbit_channel.erl"},{line,1343}]}, {rabbit_channel,handle_cast,2, [{file,"src/rabbit_channel.erl"},{line,644}]}, {gen_server2,handle_msg,2,[{file,"src/gen_server2.erl"},{line,1067}]}, {proc_lib,wake_up,3,[{file,"proc_lib.erl"},{line,236}]}]} crasher: initial call: rabbit_channel:init/1 pid: <0.11908.0> registered_name: [] exception exit: {function_clause, [{rabbit_channel,'-notify_limiter/2-fun-0-', [{pending_ack,1,<<"None4">>,1627738474140, {resource,<<"backoffice">>,queue, <<"celery">>}, 2097}, 0], [{file,"src/rabbit_channel.erl"},{line,2124}]}, {lists,foldl,3,[{file,"lists.erl"},{line,1267}]}, {rabbit_channel,notify_limiter,2, [{file,"src/rabbit_channel.erl"},{line,2124}]}, {rabbit_channel,ack,2, [{file,"src/rabbit_channel.erl"},{line,2057}]}, {rabbit_channel,handle_method,3, [{file,"src/rabbit_channel.erl"},{line,1343}]}, {rabbit_channel,handle_cast,2, [{file,"src/rabbit_channel.erl"},{line,644}]}, {gen_server2,handle_msg,2, [{file,"src/gen_server2.erl"},{line,1067}]}, {proc_lib,wake_up,3, [{file,"proc_lib.erl"},{line,236}]}]} in function gen_server2:terminate/3 (src/gen_server2.erl, line 1183) ancestors: [<0.11905.0>,<0.11903.0>,<0.11898.0>,<0.11897.0>,<0.508.0>, <0.507.0>,<0.506.0>,<0.504.0>,<0.503.0>,rabbit_sup, <0.224.0>] message_queue_len: 0 messages: [] links: [<0.11905.0>] dictionary: [{channel_operation_timeout,15000}, {process_name, {rabbit_channel, {<<"someIPAddress:45610 -> someIPAddress:5672">>, 1}}}, … -
generator expression must be parenthesized
I'm using Python 3.8 and I'm adding a model in my models file, when I did the makemigration it gave me this reply enter image description here -
show error message for any incorrect path in Django
how can I show an error message for any incorrect slug in Django? URLs.py from django.urls import path, re_path from register import views urlpatterns = [ path('', views.index, name='home'), path('singup', views.Register_user, name='singup'), path('singin', views.login_user, name='singin'), path('registration/success/<slug:user_slug>', views.success_message, name='success_message'), path('registration/failed', views.failed_message, name='failed_message'), path('profile/<slug:user_slug>', views.user_detail, name='profile'), path('profile/<slug:user_slug>/new-blog', views.blog_post, name='new_blog'), path('<str:user_slug>', views.wrong_slug, name='error_msg') ] I trying "path('<str:user_slug>', views.wrong_slug, name='error_msg')" this but it not work after Slash('/'). -
how to create and show a task with POST method in django
i have a model that name is Task it have just name field from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import Task @csrf_exempt def list_create_tasks(request): if request.method == 'POST': name = request.POST.get("name") Task.objects.create(name=name) task = Task.objects.filter("name") return HttpResponse("Task Created: "+"'"+str(task)+"'") -
How to make form html for updateview
I was making my own forms for CreateView and UpdateView with my html file because I don't want to display the form like this {{form.as_p}}. forms.py from django import forms from .models import Post class PostCreationForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'cover', 'text',) widgets = { 'title': forms.TextInput(attrs={'class': 'title'}), 'cover': forms.FileInput(attrs={'class': 'image'}), 'text': forms.TextInput(attrs={'class': 'text'}) } class PostDeleteForm(forms.ModelForm): class Meta: model = Post fields = ('__all__') views.py from django.shortcuts import reverse from django.http import HttpResponseRedirect from django.views import generic from .models import Post from .forms import PostCreationForm, PostDeleteForm class PostListView(generic.ListView): model = Post context_object_view = 'post_list' template_name = 'forum/post_list.html' class PostDetailView(generic.DetailView): model = Post context_object_view = 'post' template_name = 'forum/post_detail.html' class PostCreateView(generic.CreateView): model = Post form_class = PostCreationForm template_name = 'forum/post_create.html' def form_valid(self, form): if form.is_valid(): response = form.save(commit = False) response.author = self.request.user response.save() return HttpResponseRedirect(reverse('post_detail', args=[str(response.id)])) class PostUpdateView(generic.UpdateView): model = Post context_object_view = 'post' form_class = PostCreationForm template_name = 'forum/post_edit.html' def get_post(self, pk): return get_object_or_404(Post, pk=pk) def form_valid(self, form): if form.is_valid(): response = form.save(commit = False) response.save() return HttpResponseRedirect(reverse('post_detail', args=[str(response.id)])) class PostDeleteView(generic.DeleteView): model = Post context_object_view = 'post' form_class = PostDeleteForm template_name = 'forum/post_delete.html' success_url = '/' def get_post(self, pk): return get_object_or_404(Post, pk=pk) post_create.html {% …