Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting 404 not found when trying to update data using a query in Django
I'm trying to add a status in one of the DB table field where first I'm checking whether the passed ID is present in the table if yes then add. The ID is basically coming from the API path variable which I'm fetching and passing to the query. Below is the API which I'm using to call the class view. "/notify/<int:pk>/mark_as_seen/" "/notify/1/mark_as_seen/" # where 1 is the record Id in the DB table Below is the code which is querying the DB table and checks whether the passed Id is available. class MarkAsSeenView(BaseAuthenticationMixin, generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = SeenSerializer queryset = Seen.objects.all() def filter_queryset(self, queryset): qs = super().filter_queryset(queryset=queryset) qs = qs.exclude(seen_by_user=self.request.user).exclude(user=self.request.user) return qs def retrieve(self, request, *args, **kwargs): obj = self.get_object() obj.seen_by_user.add(self.request.user) return super().get(request, *args, **kwargs) Now when I'm calling this View via the above API it works perfectly in the first place where it will add one entry in the table as seen with the user id. Now the issue is after performing all the expected things it again going into the filter_queryset method and trying to search the same ID again which was already excluded in the previous iteration due to which it didn't get the same … -
Django Selenium on FreeBSD Exec format error geckodriver / chromedriver
I am trying to use selenium on django server (hosting with ssh, user permission). Os: FreeBSD 12.2-RELEASE amd64 display = Display(visible=False, size=(1325, 744)) display.start() opts = Options() opts.add_argument('--headless') import os path = os.path.abspath(os.getcwd()) driver = webdriver.Firefox(executable_path =path+"/geckodriver", options=opts) The "geckodriver" is set as 777 using ftp. I have tried: geckodriver-v0.29.1-linux32 geckodriver-v0.22.0-linux64 also with last Chromedriver x64 and Chrome Error: [Errno 8] Exec format error: '/usr/home/vitz/domains/xxx/public_python/geckodriver' Do you have any suggestion? :) -
Exclude is not excluding if searched users are in the list
I am building a small BlogApp and I build a feature of adding favorite users. I am now building a feature if searched user is already in another's users favorite user list then exclude the user from the list. For example :- If user_1 added user_50 in his favorite user's list. and then if user_2 searched user_50 then it will not show in the list. BUT when i try to exclude then it is not excluding. models.py class FavouriteUsers(models.Model): adder = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) favouriteUser = models.ManyToManyField(User, related_name='favouriteUser', blank=True) views.py def search_parent_cont(request): q = request.GET.get('q') exclude_this = ParentCont.objects.filter(childrens=request.user) results = Profile.objects.filter(user__username__icontains=q).exclude(exclude_this) serialized_results = [] for result in results: invite = True result_avatar = result.file.url serialized_results.append({ 'id': result.id, 'username': result.user.username, 'avatar': result_avatar, # 'email': result.email, 'about': result.about, # 'phone': result.phone, 'is_allowed_group_invite': invite, }) return JsonResponse({'results': serialized_results}) BUT this is showing :- TypeError: Cannot filter against a non-conditional expression. I have tried many times but it is still that error. Any help would be Appreciated. Thank You in Advance. -
Django upload image from form
I got this weird problem. I work with a PostgreSQL database. I made a model and form and migrated it, registered it in admin.py. When I am in the admin panel, I can add data to the form. One of the fields is an image, that is copied to media/images in the process. (MEDIA is declared in settings.py). This works like a charm. All the data (including the image) is saved in the database and can be displayed in html. But working from the admin-panel was not my first choice, so I made a html page with a form to input the data to the database. I fill in the fields, add the image and submit it. It tells me that the data is successfully added to the database. When I look in the admin panel, the record is indeed added, all the info is filled in, BUT the image is not. (it says no file is chosen). Also the image itself is not stored in media/images. If I add the image again in the admin panel, and save it, it works. So something goes wrong from the form to the database with saving the image. I googled a lot, … -
Python/Django 'ImportError: cannot import name 'python_2_unicode_compatible' in Django Rest Framework
I recently updated my DRF app from Django 2.1 to Django 3.1. But I keep receiving the error below when running the app. Before the upgrade the app was working fine. I'm using python version 3.9.0. Thanks in advance! ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' Here's the requirements.txt code: Django==3.1.2 djangorestframework==3.7.7 django-rest-swagger coreapi -
OrderItem matching query does not exist, while trying to add a product to cart
I am trying to add to cart a single product, but i have been encountering a problem and now i am stucked, I have tried different ways, but none of them worked. Please help as I am trying to learn django. I have attached the add_to_cart function, urls.py and traceback of the error. Between function i have added a print function , Its says - Internal Server Error(maybe) views @login_required def add_to_cart(request, slug): item = AffProduct.objects.get(slug=slug) order_item = OrderItem.objects.get( item=item, user=request.user, ordered=False ) for i in order_item: print(i) else: print("No orders in here") order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("detailview") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("detailview") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("detailview") Here is urls.py: path('cart/', views.cart, name='cart'), path('add-to-cart/<str:slug>/', add_to_cart, name='add-to-cart'), This is my cart.html: {% block content %} <main> <div class="container"> <div class="table-responsive text-nowrap"> <h2>Order Summary</h2> <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Item title</th> <th scope="col">Price</th> <th scope="col">Quantity</th> <th scope="col">Total Item Price</th> … -
Convert mysql join to django orm
I have few db tables for practice i am converting complex sql queries to django orm queries This is sql code i am stucked in: "SELECT hla.`id`, CASE WHEN hla.`id` IS NULL THEN 'Not enabled' ELSE 'Enabled' END AS scv_user FROM `user` u INNER JOIN custo_profile cp ON u.`custo_profile_id` = cp.`id` AND cp.`is_deleted` = 0 LEFT JOIN hl_acu_user hlacu ON hlacu.`email`= cp.`email` WHERE u.`user_id` = 44"; I am converting this code to django orm code, i tried using select_related but i am not able to find any solution and "scv_user" here is not a db column instead i am adding it in query runtime. Thanks in advance if you could help me out -
How to fix Collectstatic ERROR in Heroku deployment for React-Django APP
I've been trying to deploy my React/Django app on heroku for a while and I still can't fix the collect static error. I've seen and tried plenty of solutions but none of them seems to cut it for me. The react app is moved inside the django project so that everything runs on the port 8000 (locally) here's the error I'm getting -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt ! Python has released a security update! Please consider upgrading to python-3.9.6 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.9.4 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_d8a8f441/manage.py", line 22, in <module> main() File "/tmp/build_d8a8f441/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, … -
Django UserCreationForm not saving the given data data in the User model
When i hit submit, the signup page just refreshes itself and doesn't save the data in he User model. I confirmed it by visiting the admin site. Urls.py: from django.urls import path, include from . import views urlpatterns = [ path('accounts/join/', views.signup, name='signup'), ] views.py: def signup(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') context = { 'form' : form, } return render(request, 'registration/signup.html', context) registration/signup.html: <form method="post"> {% csrf_token %} {{ form.as_p } <input type="submit" value="Start Your Membership""> </form> -
Bootstrap carousel wont show images when i run it in django but they load perfectly fine when i use them in a normal HTML file
I used this bootstrap code to insert a carousel in my django website homepage , but the local images just wont load , how ever if i use images from web apis like unsplash they load perfectly fine , or if i use this code in a normal html file they load just fine , it just wont run in django <body> <div class="container"> <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="img1.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="img2.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="img3.jpg" class="d-block w-100" alt="..."> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-eMNCOe7tC1doHpGoWe/6oMVemdAVTMs2xqW4mwXrXsW0L84Iytr2wi5v2QjrP/xp" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.min.js" integrity="sha384-cn7l7gDp0eyniUwwAZgrzD06kc/tftFf19TOAs2zVinnD/C7E91j9yyk5//jjpt/" crossorigin="anonymous"></script> </body> </html> -
How to return a custom, non model value with serializer in Django?
I'd like to return a custom value from my serializer. I'm getting authentication tokens for the user and would like to return them as part of the registration process. At the moment I'm returning the user object and I don't know how to add the tokens into the return object as the tokens are not a part of my User model. Here's the serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ['password', 'is_active', 'staff', 'admin', 'last_login'] def create(self, validated_data): userName= validated_data['userName'] id= validated_data['id'] dateOfBirth = validated_data['dateOfBirth'] gender = validated_data['gender'] height = validated_data['height'] weight = validated_data['weight'] user = User(userName=userName, id=id, dateOfBirth=dateOfBirth, gender=gender, height=height, weight=weight) user.set_password("") user.save() try: jwt_token = get_tokens_for_user(user) except User.DoesNotExist: raise serializers.ValidationError( 'User does not exists' ) return user userName, id, dateOfBirth, height and weight are fields in my User Model. Now I'd like to return also the jwt_token from the create -method to be used in my views.py, is it possible to add it to the user object without editing the Model? -
add multiple instances via form
I'm trying to create a view that can save me multiple objects of the same type. with the code I wrote below it only creates an object with the data of the last compiled object, leaving out those above form.py class CreaEserciziForm(forms.ModelForm): serie = forms.IntegerField(required =True,label ='Serie',widget = forms.NumberInput(attrs = {'class': 'form-control','placeholder': 'serie'})) ripetizione = forms.IntegerField(required = True,label ='Ripetizioni',widget = forms.NumberInput(attrs = {'class': 'form-control','placeholder': 'ripetizioni'})) peso = forms.DecimalField(required = False,max_digits = 4,decimal_places = 1,label ='Peso',widget = forms.NumberInput(attrs = {'class': 'form-control','placeholder': 'peso'})) dati_esercizio = forms.ModelChoiceField(queryset = Esercizi.objects.all(),empty_label = "-",required = True,label = 'Esercizio',widget = forms.Select(attrs = {'class': 'form-control','placeholder' : 'esercizio'})) class Meta: model = DatiEsercizi fields = ['serie', 'ripetizione','dati_esercizio'] views.py def testView(request): if request.method == "POST": form = CreaEserciziForm(request.POST) if form.is_valid(): esercizi = form.save(commit= False) esercizi.gruppo_single = DatiGruppi.objects.get(gruppi_scheda = 28) #esercizi.save() print(esercizi) else: form = CreaEserciziForm() context = {"form": form} return render(request, "test.html", context)[enter image description here][1] enter image description here -
Downgrade open api version in drf spectacular in django rest framework
I have a project in Django Rest Framework (djangorestframework == 3.12. *) And I am now using drf-spectacular == 0.17.0 and I have an open api version 3.0.3. I need open api version 3.0.1. Tried to do so by downgrading the drf-spectacular version to a lower one but was unsuccessful. How can I downgrade the open api? -
Django UNIQUE constraint failed: accounts_user.username
I am implementing a custom Django user from scratch. Almost all things are working, but an issue arises when I create new user from the Django admin panel as follows. django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.username Why does this error occur even if there is no username field in my User model? I have included supporting files here. models.py import uuid from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from .managers import CustomManager from .utils import path_to_upload # Create your models here. class BaseModelMixin(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) creation_date = models.DateTimeField(_("Created At"), auto_now=True) modification_date = models.DateTimeField(_("Modified At"), auto_now_add=True) class Meta: abstract = True class User(AbstractUser, BaseModelMixin): display_name = models.CharField(_("Display Name"), max_length=200, blank=True, null=True) email = models.EmailField(_("Email Address"), unique=True, blank=False, null=False) profile_pic = models.ImageField(_("Profile Picture"), upload_to=path_to_upload) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["display_name"] objects = CustomManager() forms.py from django import forms from django.contrib.auth.password_validation import validate_password from django.forms import TextInput, PasswordInput from django.contrib.auth.forms import UserCreationForm from django.utils.translation import gettext_lazy as _ from .models import User class AdminUserRegistrationForm(UserCreationForm): password1 = forms.CharField(validators=[validate_password,], widget=forms.PasswordInput(attrs={"placeholder": "Password"})) password2 = forms.CharField(validators=[validate_password, ], widget=forms.PasswordInput(attrs={"placeholder": "Confirm Password"})) class Meta(UserCreationForm.Meta): model = User fields = ["display_name", "email", "profile_pic"] widgets = {} for field in fields: if … -
django add object with the current user
I'm trying to create a todoapp with google login to create personal todolist for each users. here's views.py from django.contrib.auth.decorators import login_required @login_required def todoView(request): all_todo_items = Todoitem.objects.filter(userid=request.user.id) return render(request, 'todoapp/home.html', {'all_items': all_todo_items}) def addTodo(request): add_new_item = Todoitem(content=request.POST['content']) add_new_item.save() return HttpResponseRedirect('/home/') this is my code before without users but when there's currently login user it's throwing this error null value in column "id" violates not-null constraint / DETAIL: Failing row contains (null, sampletodo,null). I believe the third column which is null is the userid and first column null is auto increment id since I set it to id SERIAL primary key in todoitem table I'm 100% sure i need to add something @addTodo views.py, I just dont know how to add todolist with the current user -
Create foreign key from auth_group_permissions table in django
I want to make foreign key from auth_group_permissions table.(the M2M table between permission and group) I know that I can use through, but it isn't appropriate if I make modify in Django library. Is there any appropriate solution. -
does django encode passwords in the Database?
I created a user with a password password123 but in the database the password field look like this pbkdf2_sha256$260000$rJZWVrYXlokRG8fGMS1fek$S7Dm9soflUsy0Q74CJP8sB60tgfRWuRPdqj5XL0DBV0= the problem: is when I create new user via rest framework i got the poassword feidl look like passsword123 so how should i created new user in order to keep the django password encoding functionality also how to deactivate this password encoding functionality -
Django queryset time interval
I need to make object selections in my database by time interval currently i found a method to select only objects from a day but not from an interval with this: data.filter(end_at__day=datetime.datetime.now().day) I saw this on the django __gte documentation which means from a date until today but I failed to make it work I have try this: if request.method == 'POST': form = DashboardSettingsForm(data=request.POST) if form.is_valid(): dis_planned = form.cleaned_data.get('display_planned') dis_currently = form.cleaned_data.get('display_currently') dis_ended = form.cleaned_data.get('display_ended') end_at = start_at = datetime.now() if dis_ended: end_at = datetime.now() - timedelta(hours=12) if dis_planned: start_at = datetime.now() + timedelta(hours=12) data = data.filter(start_at__gt=start_at, end_at__gt=end_at) print(f"interval: start{start_at} end{end_at}") -
Error in setting up django model and serializer
I am having the following error in DRF ( Django Rest Framework ): Internal Server Error: /book/book/ Traceback (most recent call last): File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/generics.py", line 190, in post return self.create(request, *args, **kwargs) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 20, in create headers = self.get_success_headers(serializer.data) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 548, in data ret = super().data File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 246, in data self._data = self.to_representation(self.instance) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 515, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/fields.py", line 1368, in to_representation return value.isoformat() AttributeError: 'SlotChoice' object has no attribute 'isoformat' Following is my serializer.py for booking: from rest_framework import serializers from .models import Booking from court.serializers import CourtSerializer from users.models import User from slots.models import SlotChoice from datetime import date class BookingSerializer(serializers.ModelSerializer): date = serializers.DateField( required=True, ) user = serializers.EmailField(required=True) court = CourtSerializer … -
Which AWS EC2 hardware options should I use for my project
I developed a django prject which uses social_auth (Google) for logins and when the user logs in to the website, their details (pre-stored in database) will be displayed to them and the user can select an option from a dropdown and then they will be provided an option to upload a pdf file and this submitted is stored in a Google drive. This project is an exam submission portal for our university where students can upload their answers written by them in a PDF format (as the exam is being conducted online). The PDF file size can be in range 2-10 mb. For storage I am using Google drive using the Django Google Drive Storage. Now, this project is completed and is working as expected in localhost but the problem is we couldn't figure out which ec2 service should we buy for this purpose. Let's say that the website is set to take submissions from 11:00 to 11:20 (Exam time ends at 11:00 , 20 mins for creating PDF and uploading it). The maximum number of submissions that can occur in that 20 mins is 3000. So, let's say that 1000 requests are done to the server at exact 11:10. … -
Why Django model extesion validator doesn't work
I want to only .xlsm files to be uploadable to the form.I tried a lot of thing according to this question. But did not work. I don't know why? How can I solve it? models.py from django.core.validators import FileExtensionValidator ... pdf = models.FileField(upload_to=customer_directory_path, null=True, blank=True, validators=[FileExtensionValidator(allowed_extensions=['xlsm'])]) ... -
How to include Run functionality in my API in Django?
I'm working on Django project where I have to make a API. In my normal Django I have one functionality named Run , that I want to add that functionality in my API View Here's my model class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') jenkins_build = models.CharField(max_length=10, default=0) jenkins_build_status = models.CharField(max_length=20, default="Never Run") def __str__(self): return self.robot class assignParameter(models.Model): parameterName = models.CharField(max_length=100, blank=True) assignRobot= models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='param', blank=True, null=True) here's my serializer.py from .models import Robot,assignParameter from rest_framework import serializers class assignParameterSerializer(serializers.ModelSerializer): class Meta: model = assignParameter fields = ['id', 'parameterName', 'assignRobot'] class RobotSerializer(serializers.ModelSerializer): param = assignParameterSerializer(many=True, read_only=True) class Meta: model = Robot fields = ['id', 'robot', 'short_Description', 'status', 'parameter', 'jenkins_job', 'jenkins_token', 'jenkins_build', 'jenkins_build_status','param'] here's my normal run function def Run_data(Request,id): if Request.method == 'POST': pi = Robot.objects.get(pk=id) jenkinsJob = list(Robot.objects.values('jenkins_job').get(pk=id).values())[0] jenkinsToken = list(Robot.objects.values('jenkins_token').get(pk=id).values())[0] fm = RobotReg(Request.POST, instance=pi) out = fm.data robot_params = list(dict(out).values()) node = robot_params.pop(1)[0] url = list(Lookup.objects.values('Value').filter(Type='JENKINS_URL').values())[0].get('Value') Uipath = list(Lookup.objects.values('Additionalinfo').filter(Type='JENKINS_NODES',Value=node).values())[0].get('Additionalinfo') robotexe = list(Lookup.objects.values('Value').filter(Type='ROBOT_EXE_PATH',Additionalinfo=node).values())[0].get('Value') robot_params.append(['node', node]) robot_params.append(['Uipath', Uipath]) robot_params.append(['robotexe', robotexe]) params_count = len(robot_params) params_exist = len(robot_params[1][0]) params = "" urlFinal = "" # url = Lookup.objects.filter(Type="JENKINS_URL").values_list(Value) if params_count > 0: for i in … -
How to correctly delete Model object field in django
Hello I want to delete my field : tag_number = models.PositiveIntegerField('Tag number', validators=[ MinValueValidator(1), MaxValueValidator(MAX_TAG_NUMBER), ]) and write fo this method: # @require_POST def book_tag(request, pk): book = get_object_or_404(Book, pk=pk) book.tag_number = **book.tag_number.delete()** book.tag_number = book.generate_tag() book.save() return redirect('book:book-list') But it delete all Book Model!I want to delete just the field 'tag_number'. -
Can I write one viewset for List, Retrieve, Update, and Delete?
I am using a viewset.ModelViewSet to list, retrieve, update and delete Car objects. I have two urls: one ends with .as_view({'get': 'list'}) and other with .as_view({'get': 'retrieve'}), and latter one is used for updating and deleting a car object. Is it ok (won't it throw some errors in the future) or should I rewrite the PUT and DELETE in another view? -
Best practice to compile Django translation files
I am looking for a best practice approach on how to compile translation files in Django. Currently the following is given: GitHub + POEditor Importing into POEditor is done with Webhooks, which works quite fine. Exporting is also done automatically, but compiling the *.po to a *.mo still needs human intervention. One approach could be to do this with GitHub Actions. Is there such a thing as a Best Practice for this? How are large organisations are dealing with this? Thanks