Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Duplicate column name when sclaing django application using Swarm/k8s
my Django app uses a entry-point script in order to start the application using docker as the hypervisor platform of choice. As soon as the container starts, several checks getting executed to determine the service lvl., Database availability, migration status and much much more (please see shortened snipped below): ... if [ "$SERVICE_TYPE" = "app" ] then echo "Check for open migrations" python manage.py makemigrations $App1 $App2 $App3 etc... python manage.py migrate echo "Checking if System User is setup" python manage.py shell <<-EOF from django.contrib.auth import get_user_model User = get_user_model() # get the currently active user model User.objects.filter(user='$SYS_USER').exists() or User.objects.create_superuser('$SYS_USER', '$SYS_USER') EOF as soon as "python manage.py makemigrations $App1 $App2 $App3" gets executed the following error appears: django.db.utils.OperationalError: (1060, "Duplicate column name 'voter_id'") In practice this only happens if I scale the application container using Docker swarm or K8S. The initial start-up procedure of the very first container works fine, always! Please correct me If I'm wrong but shouldn't it be like that if "python manage.py makemigrations" as no open migrations that are waiting to get applied to the database it never should come to such an error? Actually I would always expect that Django prints: "No changes detected in … -
Django group : only add specific user among other
I got a question what the best way to add only specific user to a group. Assume I got a userprofile, and some of user make is_ready true. When creator create a new group to one user. I'd like to only have inside of seller user (is_ready=true) user/models.py class UserProfile(models.Model): ... is_ready = models.BooleanField('Become one', default=False) exemple/models.py class Exemple(models.Model): creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="exemple_creator") seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="exemple_seller") # only user that is_ready=True ... exemple/views.py class Createexemple(CreateView): model = Exemple form_class = CreateExempleForm template_name = 'exemple_new.html' def form_valid(self, form): form.instance.creator = self.request.user form.save() return super(Createexemple, self).form_valid(form) def get_success_url(self): return reverse_lazy('exemple:exemple_home') -
Django Celery Error Message Cannot Serialize
I keep getting this error message when I run my script on my Djano App. (Object of type WSGIRequest is not JSON serializable) when I have my serializer set to JSON. If i change it to Pickle, I get this error message. (cannot serialize '_io.BufferedReader' object). I have spent days on this trying to figure out how to fix this. I appreciate any help. Thanks Here is my script im sending to celery. def ImportSchools(request): print("Getting school data from SIS") url = "" payload = {} token = APIInformation.objects.get(api_name="PowerSchool") key = token.key headers = {'Authorization': 'Bearer {}'.format(key)} response = requests.request("GET", url, headers=headers, data = payload) encode_xml = response.text.encode('utf8') pretty_xml = xml.dom.minidom.parseString(encode_xml) pretty_xml_str = pretty_xml.toprettyxml() xml_string = ET.fromstring(encode_xml) schools = xml_string.findall("school") for school in schools: psid = school.find("id").text name = school.find("name").text school_number = school.find("school_number").text low_grade = school.find("low_grade").text high_grade = school.find("high_grade").text if not School.objects.filter(schoolpsid=psid): print("Record doesn't exist in DB, creating record.") x = School.objects.create(schoolpsid=psid, school_name=name, school_number=school_number, low_grade=low_grade, high_grade=high_grade) x.save() elif School.objects.filter(schoolpsid=psid).exists(): print("Record exists in DB, updating record.") School.objects.filter(schoolpsid=psid).update(school_name=name, school_number=school_number, low_grade=low_grade, high_grade=high_grade) print("School Data Pull Complete") return("Done") -
Parse ISO string to date
I am trying to parse 2020-09-18T16:11:03.4411565+00:00 Code from dateutil import parser parser.isoparse('2020-09-18T16:11:03.4411565+00:00') I am getting ValueError: Unused components in ISO string Also i am using 3.6.9 so i can't use datetime.fromisoformat(date_string) What can I do? -
Is it possible to integrate Django Paypal IPN without using paypal_dict form?
I am trying to use the javascript button code provided by paypal instead of the paypal_dict form passed from the view to the template. I want to use the paypal code because of its modern design and simplicity. I have the paypal code working well on sandbox. Specifically I am using subscriptions payment method. I have integrated paypal IPN in settings.py: INSTALLED_APPS = [ ... 'paypal.standard.ipn', ... urls.py: urlpatterns += [ ... path('', include(apps.get_app_config('oscar').urls[0])), ... I have added the following to apps.py from django.apps import AppConfig class MypaypalConfig(AppConfig): name = 'myPaypal' def ready(self): import myPaypal.signals.handlers and here is my handlers.py file: from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received from django.utils import timezone from Store.colors import * def show_me_the_money(sender, **kwargs): ipn_obj = sender print(sender) if ipn_obj.payment_status == ST_PP_COMPLETED: print("ST_PP_COMPLETED") valid_ipn_received.connect(show_me_the_money) and in my template I have the code provided by paypal: <div id="paypal-button-container"></div> <script src="https://www.paypal.com/sdk/js?client-id= ***" data-sdk-integration-source="button-factory"></script> <script> paypal.Buttons({ style: { shape: 'pill', color: 'gold', layout: 'vertical', label: 'subscribe' }, createSubscription: function(data, actions) { return actions.subscription.create({ 'plan_id': '***' }); }, onApprove: function(data, actions) { // $("#confirm_form").submit() console.log(data) console.log(actions) } }).render('#paypal-button-container'); </script> After I successfully process the payment(sandbox) I don't receive any IPN. Is there a possible way to integrate paypal … -
Login is not working in custom User modal in Django
I have created custom user model consist of username and password and I use logged in through the username and password but when i try to login the login is not working register_app/model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class Register(models.Model): class Meta: db_table = "register" id = models.AutoField(primary_key = True) first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) email=models.EmailField() class HandleloginManager(BaseUserManager): def create_user(self, username, password=None): if not username: raise ValueError("username is required") user = self.model( username = self.username, ) user.set_password(password) user.save(using=self._db) return user class Handlelogin(AbstractBaseUser): class Meta: db_table = "login" username = models.CharField(max_length=150, unique = True) password = models.CharField(max_length = 50) register = models.OneToOneField(Register, on_delete=models.CASCADE) USERNAME_FIELD="username" REQUIRES_FIELD=['password'] objects = HandleloginManager() register_app/views.py from django.shortcuts import redirect, render, HttpResponse from .models import Register, Handlelogin from django.contrib.auth import authenticate, login # Create your views here. def home(request): return render(request, 'home.html') def register(request): if request.method == 'POST': if request.POST.get('firstname') and request.POST.get('lastname') and request.POST.get('username')and request.POST.get('email') and request.POST.get('password'): add = Register() add.first_name= request.POST['firstname'] add.last_name= request.POST['lastname'] add.email= request.POST['email'] add.save() d = Handlelogin() d.username= request.POST['username'] d.password= request.POST['password'] d.register = add d.save() return redirect('/') else: return render(request,'register.html') def users(request): reg = Register.objects.all() return render(request, 'users.html', {'reg':reg}) def login_handle(request): if request.POST: username = request.POST['user'] password = request.POST['pass'] … -
Can't migrate due to FieldDoesNotExist Error
The migration stopped working when switching from ForeignKey between Shop and user to a ManyToManyField. I wanted shops to be able to be owned by different users at the same time: class Shop(models.Model): name = models.CharField('name', max_length=120) #user = models.ForeignKey(User, on_delete=models.CASCADE) user = models.ManyToManyField(User, related_name="shopusers", blank=True) class Meta: constraints = [models.UniqueConstraint(fields=['user', 'name'], name='user cant have the same shop twice!')] @property def get_users_for_shop(self): return ", ".join([u.username for u in self.user.all()]) class Warehouse(models.Model): address = models.CharField('address', max_length=120) user = models.ManyToManyField(User, related_name="User", blank=True) django.core.exceptions.FieldDoesNotExist: NewShop has no field named 'shopusers' I thought by choosing a related name I can use multiple relations to the User model? I already tried completely deleting my database and migrate from start, but tht did not help :( -
Django change permission management logic
I'm trying to change the permission management logic to grant the following behaviour: if a permission belongs both to user group and user or neither, the user can't perform the action tied to permission if a permission belongs to one of user group and user, the user can perform the action. Following the documentation, I thought to do this by writing my custom authorization backend: from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission UserModel = get_user_model() class CustomBackend(ModelBackend): def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user def get_group_permissions(self, user_obj): user_groups_field = get_user_model()._meta.get_field('groups') user_groups_query = 'group__%s' % user_groups_field.related_query_name() return Permission.objects.filter(**{user_groups_query: user_obj}) def get_user_permissions(self, user_obj, obj=None): group_permissions = self.get_group_permissions(user_obj) assigned_permissions = user_obj.user_permissions.exclude(permission__in=group_permissions).all() print(assigned_permissions) return assigned_permissions I don't understand why it doesn't work. I'm also trying to find other solutions. -
I wanted to get data from my django mobels but it's shown error context must be a dict rather than QuerySet
I tried to pull the data from my models but It's return "{'data': <QuerySet [<WareHousePlan: Part ID : 1 Part No : 71398-KK010-00 PartName : HOLDER RR Depart Time : 2020-09-18 22:27:00 Status : True>]>}" which cause TypeError What should I do ? This is my views.py from django.shortcuts import render from django.http import HttpResponse def Home(request): return render(request,'Warehouse/HomePage.html') from .models import WareHousePlan def ShowSchedule(request): data = WareHousePlan.objects.all() context = {"data": data} return render(request,'Warehouse/Showschedule.html',data) -
I get an error when I try to change my upload image function name Django
Here it is my models.py that works. from __future__ import unicode_literals from django.db import models from django.urls import reverse from django.db.models.signals import pre_save from services.utils import unique_slug_generator from PIL import Image def upload_location(instance, filename): return "%s/%s" %('image/service', filename) # Create your models here. class Services(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=250, null=True, blank=True) content = models.TextField(null=True, blank=True) icon = models.ImageField(upload_to=upload_location, blank=True, null=True) category = models.CharField(max_length=255, default='all') def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 320 or img.width > 560: output_size = (320, 560) img.thumbnail(output_size) img.save(self.image.path) def __unicode__(self): return self.title def __str__(self): return self.title def slug_generator(sender, instance, *args, **kargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=Services) The problem is when I want to change def upload_location 's name. I tried to use def upload_location_icon as name and I changed the upload_to to icon = models.ImageField(upload_to=upload_location_icon, blank=True, null=True) This is the terminal error How can I change def upload_location name without errors? -
Decorate an inherited method without changing the method
I have this class, which inherits from another class (in this case django-rest-frameworks mixing.RetrieveModelMixin) and I want to use all of the functionality of the given retrieve() function. However I have to decorate it in order to work with swagger. class TestAPI(mixins.RetrieveModelMixin, viewsets.Viewset): model = TestModel serializer_class = TestSerializerClass @swagger_auto_schema(operation_description="TESTTEST") def retrieve(self, request, *args, **kwargs): pass This states that Expected a 'Response', 'HttpResponse' or 'HttpStreamingResponse' to be returned from the view, but received a '<class 'NoneType'>'. This leads me to believe that the "workflow" is stopped at the pass and not passed on to the parent method, which I need. I tried using the super() method with super(TestAPI, self).__init__() instead of pass but this didn't work either. I don't want to change the behaviour of the retrieve method, I just want to decorate it. When I delete the whole reference to it, it works fine. -
Filter Django queryset by related field (with code-value)
Simplifying my model a lot, I have the following: class Player(models.Model): name = models.CharField(max_length=50) number = models.IntegerField() class Statistic(models.Model): ''' Known codes are: - goals - assists - red_cards ''' # Implicit ID player = models.ForeignKey( 'Player', on_delete=models.CASCADE, related_name='statistics') code = models.CharField(max_length=50) value = models.CharField(max_length=50, null=True) I'm using a code-value strategy to add different statistics in the future, without the need of adding new fields to the model. Now, I want to filter the players based on some statistics, for example, players who scored between 10 and 15 goals. I'm trying something like this: .filter('statistics__code'='goals').filter('statistics__value__range'=[10,15]) but I'm getting duplicated players, I'm guessing because that value__range could refer to any Statistic. How could I properly filter the queryset or avoid those duplicates? -
django-tables2 access request.session
I am using django-tables2 to display some product data which is related to the shop the user is in. I store a request.session["current_shop_id"] variable all the time to select which products the user can see/edit. in the view for example: def get_queryset(self): return Product.objects.filter(shop_id = self.request.session["current_shop_id"]) The table uses a customized column with a button: class ShelfActionColumn(tables2.Column): empty_values = list() def render(self, value, record): view = f"""<a href="/device_all/{record.serial}"> <button class="btn btn-secondary">view</button> </a>""" return mark_safe(view) and in the table: class ShelfTable(tables2.Table): actions = ShelfActionColumn(verbose_name = "",) class Meta: model = ShelfStation sequence = ("name", "serial", "shop", "actions") I would like to disable the view button if request.session["current_shop_id"] != shop.id in the table, So a user can not switch shop by choosing a product of it by mistake. -
In Python(3) using Django, is it faster to break JSON into model fields or query JSON fields
Python 3.8 Django Just as the title describes, I'm wondering which is faster in the long run. I'm receiving a JSON response and saving it to a database, then displaying various fields to views. My two thoughts/options are as follows: Break the JSON response into various native database fields such as # models.py class Data(models.Model) title = models.CharField(max_length=200) body = models.TextField() author = models.CharField(max_length=40) # views.py # yes, I know this is not real code, it is pseudo for the sake of making this easier/faster def incoming_data(request): json_data = json.loads(request.body.decode('utf-8')) Data.objects.create( title = json.dumps(json_data['title']) body = json.dumps(json_data['body']) author = json.dumps(json_data['author']) ) Or, I can save the entire thing into one single row on the database as a JSONFeild # models.py class Data(models.Model) json_data = models.JSONFeild(null=True) # views.py def incoming_data(request): json_data = json.loads(request.body.decode('utf-8')) Data.objects.create( json_data = json_data ) To me, it seems easier, more "pythonic" and more "dry" to save everything as a single JSONField, however as models grow and get much, much larger and JSON responses get longer, I'm beginning to wonder which is faster for two scenarios. Saving data to the database. Obviously, with the first option, I'll have to spend extra time parsing the response and saving each … -
How can I pass user token into template and axios in django rest framework?
I'm learning to use Django rest framework and axios so don't mind me if you find this question ignorant. The whole purpose is I want to get current user information so I'm trying to pass the user token to axios in template but I don't how to pass it. I have been trying to google it but haven't find any solution yet. Login and Register are completely done with regular django form. i have this model class CustomUser(AbstractUser): email = models.EmailField(_('Email Address'), unique=True) # some other fields and i have this form class TeacherRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ['email', ..] def save(self, commit=True): user = super().save(commit=False) user.save() token = Token.objects.create(user=user) <- how i create token print(token) viewset class CustomUserViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = serializers.CustomUserSerializer permission_classes = (IsAdminUser,) urls.py router = routers.DefaultRouter() router.register('users', views.CustomUserViewSet) urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('api/', include(router.urls)), ] here is my template {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <!-- Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script> <!-- axios --> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"></div> <script> // Teacher new Vue({ delimiters: ["[[", "]]"], el: "#app", data: { teachers: null, }, mounted: function () { this.getTeacherInfo(); }, methods: { getTeacherInfo: function … -
Running into issues when I create ever lasting publisher in Pika
I have a Django website and I want requests coming from it to be always published to RabbitMQ. For that, I'm using Pika BlockingConnection and I keep the connection always open to publish website requests using basic_publish, but when the connection is stale a bit I get the following exception whenever I publish a new message pika.exceptions.StreamLostError: Stream connection lost: BrokenPipeError(32, 'Broken pipe') This is the code I use to manage my connection class ConnectionManager(): connection = None def get_connection(self): if(self.connection and self.connection.is_open): return self.connection params = pika.URLParameters('amqp://guest:guest@rabbit-server1:5672/%2F') self.connection = pika.BlockingConnection(params) return self.connection def get_channel(self, queue_name): if(channel and channel.is_open and self.connection.is_open): return channel channel = self.get_connection().channel() channel.queue_declare(queue=queue_name, durable = True) return channel And for publishing: publisher = ConnectionManager() def publish_message(request_message): publisher.get_channel("queue").basic_publish(exchange='', routing_key="some_key", body=json.dumps(request_message), properties=pika.BasicProperties( delivery_mode = 2, )) How can I maintain a forever running connection that serves my purpose? -
Return a JSON without keep the data in memory
To give an example, let's assume this situation: I have in the database all the car models released from 1950 to today (so a lot of data). In this case I speculated about cars, but it can be literally anything. I want to create an HTTP API (with Python and Django, but the concept is valid for any framework) that returns the name and brand of all the cars I have saved (a JSON list). Clearly querying the database and keeping all cars in memory, then serializing them to JSON is not an option (it would take too much memory). So what's the best way to generate a JSON, from large amounts of data in the database, and then return it via HTTP? Here is a code example to systematize the concept: def get_cars_view(request): my_cars_json = collect_json_without_keep_in_memory(Car.objects.all()) return HttpResponse(my_cars_json) -
DRF, Nested serializers CRUD with the help of intermediate table
To simplify my problem, I have three models A, B, and AB. models.py class A: title = models.CharField(max_length=120) detail = models.TextField() class B: name = models.CharField(max_length=125) xyz = models.IntegerField() class AB: link_a = models.ForeignKey(A, on_delete=models.CASCADE, related_name="a_ab") link_b = models.ForeignKey(B, on_delete=models.CASCADE, related_name="b_ab") class Meta: unique_together = ['link_a', 'link_b'] I am using BSerializer from below's code snippet as my serializer, which is pointed by the view (I think I don't have to mention the view to minimize the code in a question). serializers.py class ASerializer(DynamicFieldsModelSerializer): class Meta: model = A fields = ['title', 'detail'] class ABSerializer(DynamicFieldsModelSerializer): a = ASerializer(fields=['title', 'detail']) class Meta: model = AB fields = ['a'] Class BSerializer(DynamicFieldsModelSerializer): class Meta: model = B fields = ['name', 'xyz'] I have to use BSerializer to create data on models B and AB. The approach I am trying to needs the access to the fields of model A, and also the validation of serializer ABSerializer. To solve the scenario, at first I update the BSerializer (serializers ASerializer and ABSerializer not updated) as follows: try-BSerializer i Class BSerializer(DynamicFieldsModelSerializer): my_a = serializers.ListField(child=ABSerializer(fields=['a']), source='b_ab.all', required=True, allow_empty=True, allow_null=True ) class Meta: model = B fields = ['name', 'xyz', 'my_a'] By doing this, I need to pass data … -
What causes OSError: Bad file descriptor error in python's selenium package?
I use selenium to run django tests and I've never encountered this error before. Out of nowhere, hundreds of my tests began failing (though strangely enough not all of them, and not consistently - if I run tests one at a time, they run fine.) I have no idea why this started happening as there have been no changes to my environment. From the traceback below, it looks like the error is being thrown while setting up the webdriver. Has anybody ever encountered this selenium error before and does anyone know how to fix it? Traceback (most recent call last): File "/Users/daniellong/Documents/Coding/GrubBase/GrubBase/tests/__init__.py", line 174, in setUp self.selenium = webdriver.Chrome() File "/Users/daniellong/Documents/Coding/GrubBase/venv/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__ self.service.start() File "/Users/daniellong/Documents/Coding/GrubBase/venv/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) OSError: [Errno 9] Bad file descriptor -
Django ImageField: directly using file from disk
I have a file on my disk, say: /home/user/file.png And I have a model with a StdImageField (which is similar to the ImageField, just some additional options), more here. models.py: class MyModel(models.Model): image = StdImageField(upload_to="images", variations={"thumbnail": (600,400), "normal": (1000, 600)}, blank=True, null=True) What I'd like to do is programatically "upload" this image. I do not just want to assign the existing path to the field, as I want the image to be stored in the right folder and properly resized. So let's say I have an instance of my model in the variable obj, then I'm trying to do the following: from django.core.files.images import ImageFile open_file = open("/home/user/file.png", "rb") django_file = ImageFile(open_file) obj.image = django_file obj.save() Now at first sight this works well because a) my image gets moved to the right folder images in my media root, and b) the image gets resized properly. However, after this operation the database field with the path to the file turns absolute, containing the entire path to the media root: /src/media/images/file.png But this is not how it normally works -- this is supposed to be relative and only contain: images/file.png Why does it become an absolute field and how to solve this? -
Django User Database Implementation
quick question. I'm playing with Django and mysql. So say I have different societies, each with a sign up page, and lets say a user is able to join multiple societies, how can I be able to see in my database, how many/which societies the user is signed up to? (I was thinking maybe if I could use a field in the database that has a list/array datatype. That would be so convenient. But no such datatype exists. Or maybe a textfield and append to it every new society id that a user joins. Not sure.) -
Axios PUT Request 403 Forbidden when logged into Django
Whenever I am logged into a django user and I try and send a PUT request to my URL I get a 403 Forbidden Error. However, it works both when I am not logged in and also from the Django Rest API client. Here is my code in my frontend: let parameters = `user/${userID}` return new Promise((resolve, reject) => { axios({ method: 'PUT', url: 'http://127.0.0.1:8000/' + parameters, data: updatedUser, headers: { 'Content-Type': 'application/json', }, }) .then((response) => { resolve(response) }) .catch(error => { console.log(error) // reject(error) }) }); I am very confused as I can't see the difference when I am logged into a django user and when I am not, as nothing changes in the frontend. Thanks -
How to change another field value when Clear in Django?
I am working with Django form Updation, but I am facing a small issue, I have 3 fields in form updating, name, image, status, Now if a user uploads an image in the form then the status is automatically changing to 1 in the database. but now if I clear the form using checkbox of the image then this status should be updated 0 in my database here is my forms.py file... class UpdateForm(forms.ModelForm): ... def save(self, commit=True): instance = super(UpdateForm, self).save(commit=False) # Set status if saving picture if instance.image: instance.status = 1 if commit: instance.save() here is my views.py file... def myview(request, id): datas=Product.objects..get(pk=id) form = UpdateForm(instance=datas) if request.method === 'POST' form = UpdateForm(request.POST or None, request.FILES or None, instance=datas) if form.is_valid(): edit = form.save(commit=False) edit.save() return HttpResponse('Success') else: return HttpResponse('Fail') template_name='test.html' context={'datas':datas} return render(request, template_name, context) here is my site.html file... <a href="/media/{{datas.image}}"/>{{datas.image}}</a> <input type="checkbox" name="image-clear" id="image-clear_id"/> Clear When I update this form then it updates 1 in the status field, but if I clear from form then status should be 0 in my database -
How to use django-logpipe?
I am trying to use django-logpipe package to implement Kafka for one of my projects. I didn't find any reference to implement that. Could you please suggest any demo or sample reference document to start with. Thanks in advance :) -
Django Admin action button per each row in ListView
as in this post from hakibenita https://hakibenita.com/how-to-add-custom-action-buttons-to-django-admin , i would have an action button per each row in admin listview. This button should change the status of the book (simply a char field with choices in models), but i want it to do without opening another page, just a click on the button and the status is changed. The status value is choosen from a select and clicking the action button call a javascript to read the select button, the javascript then call the admin page to change the status. I can't do a form, because each row in listview is already in a form. I don't want to use admin action, because this is an action per single object. Here is the relevant code: admin.py: class BookAdmin(admin.ModelAdmin): #... def get_urls(self): urls = super().get_urls() custom_urls = [ path('changestatus/<str:status>/<int:bookid>', self.admin_site.admin_view(self.change_status), name = 'changestatus'), ] return custom_urls + urls def change_status(self, request, bookid=None, status=None): if bookid: book = Book.objects.get(pk=bookid) if status == 'available': book.status = Book.AVAILABLE elif status == 'unavailable': book.status = Book.UNAVAILABLE book.save() newStatus = book.get_status_display() self.message_user(request, 'Changed status to "{}"'.format(newStatus), messages.SUCCESS) url = reverse( 'admin:library_book_changelist', current_app=self.admin_site.name, ) return HttpResponseRedirect(url) def status_button(self, obj): return format_html('{}<br />' '<select id="selectstatus">' '<option value="available-{}">Status available</option>' …