Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
permission based on the action/url in Django rest framewrok
I have a Modelviewset class that has several functions inside it like list(), destroy, partial_update() and also other custom functions like def get_examples(self,request). The thing is different functions have different permissions based on the user types. I have a separate permission class inside a permission file. Now I need to access the action inside the has_permission function. I know it can be done inside the get_permission function inside modelviewset class. But how can we do it inside has_permission function?? My View: class ExampleView(viewsets.ModelViewSet): queryset = Example.objects.all().order_by("-created_at") serializer_class = ExampleSerializer pagination_class = ExampleNumberPagination def list(self, request, *args, **kwargs): def partial_update(self, request, *args, **kwargs): def custom_fuctin_1(self,request,*args,**kwargs): def custom_fuctin_2(self,request,*args,**kwargs): def destroy(self, request, *args, **kwargs): Now permission file: class ExampleClassPermission(BasePermission): def has_permission(self, request, view): user =request.user if request.method == 'GET' or request.method == 'POST': return True elif request.method == 'DELETE' and (user.role == 'manager' or user.role == 'admin'): return True elif request.method == 'PUT': return True else: return False Here in this permission class, I want to set permission for custom function_1 and 2 in the view class. I cant do self.action == ''? just like in the get_permission.Can I?? -
How do I render json data from an API into a Django template?
I just want to display a few specific parameters of each object, like author and title and description, not the entire dataset. So far, it renders the top 10 first objects from the API into my template but i'm having trouble figuring out how to call only specific keys. views.py template -
TypeError: subcategory() got an unexpected keyword argument 'cslug'
I have a URL path like this: www.example.com/caetegory/mens/mens-shoes As you can see, the URL path includes 3 slugs in this example. I have 3 different class for these categories. And slug is included inside each of them separately. What do I need to do in order to be able to render the product accordingly to the subcategory Every single help or thought is highly appreciated. I can't find any source for that. URLS.py models.py Class Category(models.Model): cat_name= models.CharField(max_length=200) slug = models.SlugField(max_length=200) description = models.TextField() cat_image = models.ImageField(upload_to ='media/category', blank=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('product_by_category', args=[self.slug]) def __str__(self): return self.cat_name class SubCategory(models.Model): cat_name = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) subcat_name =models.CharField(max_length = 200) slug = models.SlugField(max_length=200) description = models.TextField(blank=True) subcat_image = models.ImageField(upload_to ='media/subcategory', blank=True) def __str__(self): return self.subcat_name class SubSubCategory(models.Model): subcat_name = models.ForeignKey(SubCategory, on_delete=models.CASCADE, null = True) subsubcat_name = models.CharField(max_length=200) slug = models.SlugField(max_length=200) description = models.TextField(blank=True) subsubcat_image = models.ImageField(upload_to = 'media/subsubcategory', blank=True) class Meta: verbose_name = 'subsubcategory' verbose_name_plural = 'subsubcategories' def __str__(self): return self.subsubcat_name class Products(models.Model): product_name = models.CharField(max_length=200) slug = models.SlugField(max_length=200) price = models.DecimalField(max_digits=50, decimal_places=3) images = models.ImageField(upload_to ='media/products', blank=True) is_available = models.BooleanField(default=True) category = models.ForeignKey(SubSubCategory, on_delete=models.SET_NULL, null=True) description = models.TextField(default='abc') subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, … -
elastic search in django
i try to use elastic search in django and i use django_elasticsearch_dsl for it i run elastic with docker services: esearch: container_name: elasticsearch build: context: . dockerfile: elastic.Dockerfile environment: - discovery.type=single-node ports: - "9200:9200" network_mode: bridge dockerfile FROM elasticsearch:8.1.2 ENV discovery.type=single-node write a test code like @registry.register_document class AnomalyDocument(Document): class Index: name = 'anomaly' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Anomaly fields = [ 'title', 'description', ] and run command python manage.py search_index --rebuild and got timeout err elasticsearch.exceptions.ConnectionTimeout: ConnectionTimeout caused by - ReadTimeoutError(HTTPConnectionPool(host='localhost', port=9200): Read timed out. (read timeout=30)) any body know why timout happen and how to fix it thanks -
DJANGO How to update model value +1 in database JSON on a click of a button
Clicking on update i get a Rest Api Page instead of Updating results in database. Thank You ALL Views.py @admin_only @api_view(['GET','POST']) def subs(request, pk): sw = get_object_or_404(Swimmers,id=pk).sessions sw_list = sw sw_lists = sw + 1 serializer = SubSerializer(instance=sw, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) Urls.py path('vswimmer/<int:pk>', views.VWmore.as_view(), name='view_swimmer'), path('deletes/<int:pk>', views.SWGDelete.as_view(), name='deletes_sessions'), path('subt/<int:pk>', views.subs, name='subt'), -
Django bulk create with foreign key to another field
I want to bulk create objects, when they have a foreign key and their foreign key is not id field. (When to_field value is id you can reference it with model_id in creation but I haven't found a way to do id with another field.) I have a model named Credit: class Credit(models.Model): account = models.ForeignKey('finance.Account', to_field='account_id', on_delete=models.PROTECT) amount = models.PositiveBigIntegerField() and a model named Account: class Account(models.Model): account_id = models.UUIDField( verbose_name=_("account id"), db_index=True, null=True, unique=True, ) and I tried to create objects with: accounts = [] # list of uuids credits = [ Credit( account__account_id=a, amount=amount, ) for a in accounts] created_objects = Credit.objects.bulk_create( credits, ignore_conflicts=True ) and I get the following error: TypeError: Credit() got an unexpected keyword argument 'account__account_id' -
Azure web app deployment have error "Error: Oops... An unexpected error has occurred."
I am deploying an web app and It give me an error like: Command: oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform python --platform-version 3.8 -i /tmp/8da2073577e7c44 --compress-destination-dir -p virtualenv_name=antenv --log-file /tmp/build-debug.log Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx You can report issues at https://github.com/Microsoft/Oryx/issues Oryx Version: 0.2.20211207.1, Commit: 46633df49cc8fbe9718772a3c894df221273b2af, ReleaseTagName: 20211207.1 Build Operation ID: |k0MN7QhgbkY=.5fbefdfd_ Repository Commit : 6bc0cf64-6a80-4b53-a94d-605798c20ce9 Detecting platforms... Error: Oops... An unexpected error has occurred. Error: Oops... An unexpected error has occurred.\n/opt/Kudu/Scripts/starter.sh oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform python --platform-version 3.8 -i /tmp/8da2073577e7c44 --compress-destination-dir -p virtualenv_name=antenv --log-file /tmp/build-debug.log Can anybody tell me how do I solve this problem -
django custom user model need password2 for login form
i have custome user model and login form to log in user but in form.is_valid() i have error: password2This field is required. my user model: class MyAccountManager(BaseUserManager): def create_user(self, email,username,password=None): if not email: raise ValueError('لطفا ایمیل را وارد کنید') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save() user.save(using=self._db) return user def create_superuser(self, email,username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin= True user.is_active=True user.is_staff=True user.is_superuser=True user.save() user.save(using=self._db) return user class User(AbstractBaseUser,PermissionsMixin): username = models.CharField(max_length=100 , null=True) mobile = models.CharField(max_length=100, null=False, verbose_name="موبایل") email = models.CharField(max_length=180, verbose_name='ایمیل', unique=True, default=None, blank=True, null=True) type = models.ForeignKey("userType.mUsertype", on_delete=models.CASCADE, verbose_name="نوع کاربری", null=True) addressmain = models.TextField(verbose_name="آدرس") website = models.CharField(max_length=100 , null=True) logo_url = models.CharField(max_length=100 , null=True) facebook_id = models.CharField(max_length=100 , null=True) instagram_id = models.CharField(max_length=100, null=True) telegram_id = models.CharField(max_length=100 , null=True) whatsapp_id = models.CharField(max_length=100, null=True, verbose_name="واتس آپ") twitter_id = models.CharField(max_length=100 , null=True) description = models.TextField(verbose_name="توضیحات") plan_expiry_date = models.DateTimeField(null=True) plan_count = models.IntegerField(default=0) country = models.CharField(max_length=100 , null=True) city = models.CharField(max_length=100 , null=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def tokens(self): return 'token' def __str__(self): return self.username.__str__() my form: class SigninForm(UserCreationForm): def __init__(self, *args, **kwargs): super(SigninForm, self).__init__(*args, **kwargs) class Meta: model = User widgets={ … -
How check the user how much time spend on a video in
I am using django framework. I embed the youtube video link in html, I want to know that the user spend how much time on the video and save the time in database with his deatils. the details of the user is stored in cookies. like email. here is my code. <div id="request" class="modal fade" {% if request.session.email %} data-backdrop="static" {% endif %} role="dialog"> {% if 'email' not in request.session %} <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <span class="close" data-dismiss="modal" aria-label="Close">&times;</span> <h2 class="modal-title">Get start</h2> </div> <div class="modal-body text-center"> <form class="form-request" action="" method="post"> {% csrf_token %} <div class="row-fields row"> <div class="form-group col-field"> <input type="text" class="form-control" name="name" required placeholder="Name *" id="name"> </div> <div class="form-group col-field"> <input type="email" class="form-control" name="email" required placeholder="Email *" id="email"> </div> <div class="form-group col-field"> <input type="number" class="form-control" name="phone" required placeholder="Phone *" id="phone"> </div> <div class="col-sm-12 buttons"> <button type="submit" class="bttn-hover color-1" data-text-hover="Submit">Send request</button> </div> </div> </form> </div> </div> </div> {% elif request.session.email %} {% comment %} <a href="http://www.youtube.com/watch?v=ANwf8AE3_d0"> {% endcomment %} <iframe class="embed-responsive-item set-style-of-iframe" src="https://www.youtube.com/embed/tgbNymZ7vqY/?autoplay=1;enablejsapi=1" allowfullscreen style="height:50%; width:65%" id="myvideo-iframe"></iframe> <button class="btn btn-close button-closing-style" aria-label="Close" onclick="my_video_pause();" class="close" data-dismiss="modal">close</button> <a href="http://cdn.onlinewebfonts.com/svg/img_414950.png" class="button-closing-style" onclick="my_video_pause();" data-dismiss="modal"> </a> {% endif %} </div> </div> -
Is there a way to group annotated values into another groupings in Django
I have a model that stores hourly data. class HourlyData(models.Model): value = models.FloatField() record_time = models.DateTimeField() This data has been collected over 3 months and I want to be able to group this data into monthly data and have it in this format. data = [{ month:'2022-01', days_count: 25, total_value=1000 }, { month:'2022-02', days_count: 28, total_value=6000 }] days_count: number of days recording was done that month, total_value: sum of all the readings that month I have tried using django annotate for this by trying this HourlyData.objects.filter( record_time__gte=start_date, record_time__lte=end_date, ) .annotate( day=Trunc('record_time', 'day', output_field=models.DateField()) ).values('day') .annotate(total_sum= models.Sum('value')) .values( 'total_sum', 'day') .order_by('day') The query above sums up the total value for each day. in this format <QuerySet [{'day': datetime.date(2020, 10, 6), 'total_sum': 126.28489942032}, {'day': datetime.date(2020, 10, 7), 'total_sum': 304.358586463236}, {'day': datetime.date(2020, 10, 8), 'total_sum': 304.140234726139}, {'day': datetime.date(2020, 10, 9), 'total_sum': 303.430313325472}, {'day': datetime.date(2020, 10, 10), 'total_sum': 303.156103881001}, {'day': datetime.date(2020, 10, 11), 'total_sum': 302.564397818492}, {'day': datetime.date(2020, 10, 12), 'total_sum': 301.924853438771}, {'day': datetime.date(2020, 10, 13), 'total_sum': 301.730580133637}]> However, I need this data to be grouped into monthly data and count the number of days in each month that recording was made. I have tried to annotate this result and calculate a monthly_count by doing … -
I have problem in django e-commerece project when i increase and decrease quantity
I have problem when i click on plus button then value increase automaticallu one to direct 3 mean skip one value like ist default value 1 then i click plus button then value show 3 Please help me Bootstrap code : """ <div> <h5>{{ cart.product.title }}</h5> <p class="mb-2 text-muted small">{{ cart.product.description }}</p> <div class="my-3"> <label for="quantity">Quantity:</label> <a class="minus-cart btn" pid="{{ cart.product.id }}"><i class="fas fa-minus-square fa-lg"></i></a> <span id="quantity">{{ cart.quantity }}</span> <a class="plus-cart btn" pid="{{ cart.product.id }}"><i class="fas fa-plus-square fa-lg"></i></a> </div> """ Ajax code: """ $('.plus-cart').click(function () { var id = $(this).attr("pid").toString(); var eml = this.parentNode.children[2] $.ajax({ type: "GET", url: "/pluscart", data:{ prod_id: id }, success: function (data){ eml.innerText = data.quantity document.getElementById("amount").innerText = data.amount document.getElementById("totalamount").innerText = data.totalamount } }) }) $('.minus-cart').click(function () { var id = $(this).attr("pid").toString(); var eml = this.parentNode.children[2] $.ajax({ type: "GET", url: "/minuscart", data:{ prod_id: id }, success: function (data){ eml.innerText = data.quantity document.getElementById("amount").innerText = data.amount document.getElementById("totalamount").innerText = data.totalamount } }) }) """ Views.py Code: """ def plus_cart(request): if request.method == 'GET': prod_id = request.GET['prod_id'] c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user)) c.quantity += 1 c.save() amount = 0.0 shipping_amount = 70.0 cart_product = [p for p in Cart.objects.all() if p.user == request.user] for p in cart_product: tempamount = (p.quantity * … -
Django - Change the status of the order in models
Good day, everyone. I am working on some legacy code that is written very bad. It is an e-commerce site for artworks and it has no admin panel to track orders. Instead, we have to use Django Admin Panel! Yeah, that's really awful but let's skip that part. I have model for orders: class Order(models.Model): user = models.ForeignKey( AuthUsers, verbose_name=_("Пользователь"), related_name="orders", on_delete=models.DO_NOTHING, ) status = models.CharField( _("Статус"), max_length=100, choices=OrderStatusChoices.choices) sub_total = models.FloatField(_("Под итог")) discount = models.FloatField(_("Скидки"), null=True, blank=True) total = models.FloatField(_("Итого")) created_at = models.DateTimeField(_("Оформлено"), auto_now_add=True) updated_at = models.DateTimeField(_("Обновлено"), auto_now=True) works = models.ManyToManyField( "OrderItems", verbose_name=_("Произведения"), related_name="orders" ) Model for artwork itself: class Works(models.Model): u_id = models.CharField( _("Уникальный артикль (генерируется автоматически)"), blank=True, null=True, max_length=100, ) section = models.ForeignKey(Sections, verbose_name=_( 'Oтдел'), related_name='work_section', null=True, on_delete=models.DO_NOTHING) slug = models.SlugField( "Дополнение к названию ссылки (генерируется автоматически)", default="no-slug", blank=True, max_length=255 ) author = models.ForeignKey( Authors, verbose_name=_("Автор"), related_name="work_author", on_delete=models.DO_NOTHING, ) genre = models.ManyToManyField( Categories, verbose_name=_("жанр"), related_name="art_works" ) # category = models.ForeignKey(Categorization, verbose_name=_( # "Категория"), related_name="work_category", null=True, on_delete=models.CASCADE) name = models.CharField(_("Название"), max_length=255) description = models.TextField(_('Описание'), null=True, blank=True) type = models.ForeignKey(WorkType, verbose_name=_( 'Bид'), related_name="work_type", blank=True, null=True, on_delete=models.DO_NOTHING) period = models.ForeignKey(Period, verbose_name=_('период'), related_name="work_period", blank=True, null=True, on_delete=models.DO_NOTHING) flow = models.ForeignKey(Flow, verbose_name=_('течение'), related_name="work_flow", blank=True, null=True, on_delete=models.DO_NOTHING) show_in_service = models.ManyToManyField(Services, verbose_name=_('сервисы'), related_name="artworks", blank=True, null=True) … -
how to integrate ireport with Django App (python) ? any other simliar libraries?
I'm currently developing a Django App (python) and i want to use iReport with my app, i tried to use pyreportjasper but it's impossible to install it. are there any other python library or something to fix this problem ? -
Download Image file and upload to database
I'm trying to download the profile image from Twitter and then upload it into my database so that it can be served as media on other screens. username = 'someUser' consumer_key = "######..." consumer_secret = "######..." access_token = "######..." access_token_secret = "######..." auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) user = api.get_user(user_id = username ,screen_name = username) url = user.profile_image_url url = url.replace('_normal.jpg','.jpg') remote_url = url local_file = 'profile.jpg' request.urlretrieve(remote_url, local_file) os.remove(local_file) This allows me to download the file and store it on a local disk which won't work once in production. My Model profile_image = ResizedImageField(size=[400, 400],crop=['middle', 'center'],quality=100,upload_to='images/profiles/', blank=True) I could maybe save it to images/profiles/<something>.jpg and then within my view, i reference this file and delete it after? Is there a better way Thanks -
When saving an object from the django admin panel, I get error 400
When I create an object in django admin when I click save, nothing happens, I get an error. Request URL: /api/admin/advertisements/advertisements/add/ Request Method: POST Status Code: 400 Bad Request Request sent to a non existent address, I didn't redefine anything, no validation happens. Everything is fine with the other models. There is nothing wrong with the venv environment. The code of this model is standard. class Advertisements(models.Model): user = models.ForeignKey(Users, verbose_name="User", null=True, blank=True, on_delete=models.CASCADE) category = models.ForeignKey(Categories, verbose_name="Category", on_delete=models.CASCADE) subcategory = models.ForeignKey(Subcategories, verbose_name="Subcategory", on_delete=models.CASCADE) name = models.CharField("Name", max_length=100) def __str__(self): return self.name class Meta: verbose_name = "advertisement" verbose_name_plural = "dvertisements" -
Django runserver error "TypeError: __init__() takes 1 positional argument but 2 were given"
I understand that somewhere 2 parameters are passed when 1 is needed only, but I can't seem to figure out where. I was in the process of updating Django from 1.9 to 1.11. Most answers relate to views, but all my views are class based and had as_view already. the exact traceback is: Traceback (most recent call last): File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mezzanine/core/management/commands/runserver.py", line 163, in inner_run super(Command, self).inner_run(*args, **kwargs) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 146, in inner_run handler = self.get_handler(*args, **options) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mezzanine/core/management/commands/runserver.py", line 166, in get_handler handler = super(Command, self).get_handler(*args, **options) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 28, in get_handler handler = super(Command, self).get_handler(*args, **options) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in get_handler return get_internal_wsgi_application() File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/pp/www/Hakomo/hakomo/hakomo/wsgi.py", line 20, in <module> application = get_wsgi_application() File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application return … -
How do I fix the error of my django form not having cleaned_data attribute?
I have this form class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "pass"] and this view def register(req): if req.method == 'POST': form = RegisterForm(req.POST) print('yaml') if form.is_valid(): form.save() return redirect("/home") else: form = RegisterForm() form.save() return render(req, "users/register.html", {"form":form}) but when I visit the url urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.urls")), path('register/', userViews.register, name="register"), path('', include("django.contrib.auth.urls")), ] I keep getting this error Internal Server Error: /register/ .... AttributeError: 'RegisterForm' object has no attribute 'cleaned_data' Please I need some help. Thanks in advance -
What are the parameters that Django use to generate session id
What are the parameters needed to generate a default Django sessionid I am assuming: def generate_session(secrete_keys, current_time, string_key_name, what_else?): return generate(...) -
how do i switch between two form on a page with login and sign up views in django
I have a page that has both login and sign up form in the html. so when one is active, the other is hidden but any time i try to login, the sign up form is displayed instead of the login form. the sign up tab works but the login tab does not. This is my html page: <div class="form-box"> <div class="form-tab"> <ul class="nav nav-pills nav-fill" role="tablist"> <li class="nav-item"> <a class="nav-link" id="signin-tab-2" data-toggle="tab" href="#signin-2" role="tab" aria-controls="signin-2" aria-selected="false">Sign In</a> </li> <li class="nav-item"> <a class="nav-link active" id="register-tab-2" data-toggle="tab" href="#register-2" role="tab" aria-controls="register-2" aria-selected="true">Register</a> </li> </ul> <div class="tab-content"> <div class="tab-pane fade" id="signin-2" role="tabpanel" aria-labelledby="signin-tab-2"> <form action="{% url 'estores:login' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="singin-email-2">Username or email address *</label> <input type="text" class="form-control" id="singin-email-2" name="username" required> </div><!-- End .form-group --> <div class="form-group"> <label for="singin-password-2">Password *</label> <input type="password" class="form-control" id="singin-password-2" name="password" required> </div><!-- End .form-group --> <div class="form-footer"> <button type="submit" name="login" class="btn btn-outline-primary-2"> <span>LOG IN</span> <i class="icon-long-arrow-right"></i> </button> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="signin-remember-2"> <label class="custom-control-label" for="signin-remember-2">Remember Me</label> </div><!-- End .custom-checkbox --> <a href="#" class="forgot-link">Forgot Your Password?</a> </div><!-- End .form-footer --> </form> <div class="form-choice"> <p class="text-center">or sign in with</p> <div class="row"> <div class="col-sm-6"> <a href="#" class="btn btn-login btn-g"> <i class="icon-google"></i> Login With Google … -
action after time is expired in django
I am creating auctions website using django. the user can create auctions by input this fields: title, description, image, startprice, stutasvalue and time. class Auction(models.Model): title = models.CharField(max_length=30) description = models.TextField() startprice = models.IntegerField(default=1) image = models.ImageField(upload_to="auction/") statusvalue = (("Soon", "Soon"), ("Live", "Live"), ("Expired", "Expired")) status = models.CharField(max_length=10, default="Soon", choices=statusvalue) time = models.IntegerField(default=1) def __str__(self): return self.title I can Live the auction from admin-panel. how can I convert statusvalue from Live to Expired after the time is expired? If we bear in mind that time is the number of hours in which the auction must be live. and how can I make counterdown for this time. -
'manager_method() argument after ** must be a mapping, not str' when overloading nested ModelSerialiver.create(...)
I want to overload a ModelSerializer create() method in a generic way using Django RestFramework inspection functions. for the purpose of testing the concept on a related_name of a ForeingKey i have the following models and corresponding serializer. models.py class Country(models.Model): pass class People(models.Model): country = models.ForeignKey( to="myapp.Country", null=True, blank=True, on_delete=models.SET_NULL, related_name="country_people" ) serializer.py class CountrySerializer(serializers.ModelSerializer): country_people = PeopleSerializer(many=True) def create(self, validated_data): country_people_data = validated_data.pop("country_people", []) instance = super().create(validated_data) for cp_data in country_people_data: cp_data["country"] = instance self.get_fields()["country_people"].create(cp_data) class Meta: fields= "__all__" model = Country example of data # json data for country serializer { ..., "country_people":[ {...}, {...} ] } When calling CountrySerializer.save() the CountrySerializer.create() will be called and it will save also nested data on People table. The issue is that I got the following error ModelClass._default_manager.create(**validated_data) TypeError: django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() argument after ** must be a mapping, not str using People.create(**cp_data) is working but it is not the solution in my context I want to solve it using self.get_fields because I want it to be generic and because PeopleSerializer could nest another serializer so back and so forth -
I want to show the total rows beside the search and make search code work in python?
I created a table and I want to do a search for two columns (id and name) so when the user enters any letter or number of name, id columns it shows all row names containing that letter and I want to show the total rows of my table next to search box. in HTML <table class="table table-striped " id="table1"> <tbody> {% for i in data_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{i.employee_code}}</td> <td>{{i.employee_name}}</td> <td>{{i.email}}</td> </tr> {% endfor %} </tbody> </table> In JS I did the search code but it does not work! function searchrecords() { var input,table,tr,td,filter; input=document.getElementById("searchtext"); filter=input.value.toUpperCase(); table=document.getElementById("table1"); tr=table.getElementsByTagName("tr"); for(i=0;i<tr.length;i++) { td=tr[i].getElementsByTagName("td")[0]; if(td) { textdata=td.innerText; if(textdata.toUpperCase().indexOf(filter)>-1) { tr[i].style.display=""; } else { tr[i].style.display="none"; } } } } -
'Media' object has no attribute 'render_styles'
I am getting this error when I try to go to the Django admin category page. my grunt.js page: module.exports = function(grunt) { grunt.initConfig({ sass: { dist: { options: { style: 'compressed' }, files: { 'static/styles/css/style.css': 'media/assets/styles/sass/style.scss' } } }, watch: { sass: { files: ['media/assets/styles/sass/*.scss'], tasks: ['sass:dist'] } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-autoprefixer'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['sass:dist']); }; When I try to go to the django admin, I have no problem but when try to go to the category page or user page, I got this error: AttributeError at /admin/bookmark/category/ 'Media' object has no attribute 'render_styles' Request Method: GET Request URL: http://localhost:8000/admin/bookmark/category/ Django Version: 4.0.3 Exception Type: AttributeError Exception Value: 'Media' object has no attribute 'render_styles' Exception Location: C:\Users\moust\Workspace\python_projects\saas_app\venv\lib\site-packages\django\forms\widgets.py, line 97, in <genexpr> Python Executable: C:\Users\moust\Workspace\python_projects\saas_app\venv\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\moust\\Workspace\\python_projects\\saas_app', 'c:\\users\\moust\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\moust\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\moust\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\moust\\appdata\\local\\programs\\python\\python39', 'C:\\Users\\moust\\Workspace\\python_projects\\saas_app\\venv', 'C:\\Users\\moust\\Workspace\\python_projects\\saas_app\\venv\\lib\\site-packages'] Server time: Sun, 17 Apr 2022 05:14:14 +0000 this is the suit of the error message -
How can I change django form error strings [duplicate]
I use hebrew with django and when I submit a form and there's an error, the grammar of the message is not correct, how can I change form error strings? -
Why my exports are limited to 100 records only in django-import-export?
I am using Django import export in my project. I have ~5000 records in the model. In local, The export is working fine. [exporting all the records in csv] But in production, when I export to csv, Only 100 records are exported. The django app is hosted on Cpanel. I am using mysql phpmyadmin in production. Is there any limit in the cpanel to export in django import-export module which I can change because the problem I am facing in production only. database config in settings.py DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': '********', 'USER': '*********', 'PASSWORD': '*********', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'STRICT_ALL_TABLES', }, } } Model class Treatment(models.Model): clinic = models.ForeignKey(Clinic,on_delete=models.CASCADE,related_name='alltreatments', null=True) slug = models.SlugField(null= True, blank= True) language = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='treatmentlanguage', blank= True, null=True) searched_treatment = models.CharField(max_length= 256, blank= False, null= False) price = models.FloatField(blank= False, null= False) price_type = models.CharField(max_length= 256, blank= True, null= True) package_info_1 = models.CharField(max_length= 556, blank= True, null= True) package_info_2 = models.CharField(max_length= 556, blank= True, null= True) package_info_3 = models.CharField(max_length= 556, blank= True, null= True) package_info_4 = models.CharField(max_length= 556, blank= True, null= True) currency=models.ForeignKey(Currency,on_delete=models.CASCADE,related_name='currency',blank=True,null=True) created= models.DateTimeField(auto_now=True) status = models.BooleanField(default= True) class Meta: # unique_together = ('clinic', 'searched_treatment', 'language') …