Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Showing ads between posts django ? Trying to show ads after specific number of posts
I want to implement this thing, Like facebook showing ads when we are scrolling posts, after 4th or 5th post we see some ads, how can I do that please can someone tell me? If any video link is available please share Between two post like this I am shwoing all the post by for loop, if any nested for loops available please share how can I loop two different model in single loop , showing 1st item of one model after 5th item of another model loop Thank you 💗 **I am not using google ad sense, you can imagine its like I will create my own model , maybe same post model where is_ads=True be a field like that. This is my post model- class Post(models.Model): postuuid = models.UUIDField(default=uuid.uuid4,unique=True,editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150,blank=False) text = models.TextField(null=True,blank=False) image = models.ImageField(upload_to='post_images/',null=True,blank=True,default="") created_at = models.DateTimeField(auto_now_add=True, null=True) likes = models.ManyToManyField(User, blank=True, related_name="post_like") tag= models.CharField(max_length=150,blank=True) post_url=models.URLField(max_length=150,blank=True) video = models.FileField(upload_to='post_videos/',null=True,blank=True,default="") # community = models.ForeignKey(communities,on_delete=models.CASCADE) def __str__(self): return self.title -
Django: how to add fields to a form in html and save it?
I have a form with different fields and one TextInput field named 'directions'. User can add additional direction-fields with a button (just cloning existing one with javascript). But when i try to save it to the database only the last one is saved. If i print request.POST there's a list named 'directions': ['first direction', 'second' , 'and so on...'], so the data is there but it somehow gets truncated after validation. I also tried replacing the field with custom MultiValueField starting with one CharField and adding additional with javascript like this: <input type="text" name="directions_0" required="" id="id_directions_0"> <input type="text" name="directions_1" required="" id="id_directions_1"> but the result is the same models.py: class Recipe(models.Model): title = models.CharField(max_length=255) directions = models.CharField(max_length=512) class Ingredient(models.Model): name = models.CharField(max_length=127) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients') forms.py: class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = '__all__' class IngredientForm(forms.ModelForm): class Meta: model = Ingredient exclude = ('recipe', ) IngredientFormSet = forms.inlineformset_factory(Recipe, Ingredient, form=IngredientForm) views.py: class RecipeCreateView(CreateView): form_class = RecipeForm template_name = 'recipes/recipe_new.html' success_url = reverse_lazy('recipe_list') def get_context_data(self, **kwargs): context = super(RecipeCreateView, self).get_context_data(**kwargs) if self.request.POST: context['formset'] = IngredientFormSet(self.request.POST) else: context['formset'] = IngredientFormSet() return context def form_valid(self, form): context = self.get_context_data() ingredient_formset = context['formset'] if ingredient_formset.is_valid(): self.object = form.save() ingredient_formset.instance = self.object … -
How do i create a tracking url in django?
Below I have wriiten a url used in iframe from amazon. <iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" src="//ws-in.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=IN&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=inderpsingh-21&amp;language=en_IN&amp;marketplace=amazon&amp;region=IN&amp;placement=B08HQL67D6&amp;asins=B08HQL67D6&amp;linkId=49af08c6e03b6db926b23064dffbf266&amp;show_border=true&amp;link_opens_in_new_window=true" frameborder="0"> </iframe> As you can see the below iframe is being used by amazon to track user actions and grant them rewards on the basis of analytical approach. I am being able to create an iframe element with the actual link of the page, but I am finding it difficult to how to create a tracking link so that in further user , the iframes can be useful for user tracking and actions. Not trying to go in depth of tracking events but to understand the actions or procedures needed for tracking. Also I am not using any kind of 3rd-party options for tracking. Any kind of help would be appreciated. -
view sets throwing pagenotfound! found Django DRF
Getting page not found error, trying DRF, I am trying these viewsets but so far error as mentioned thanks in advance! urlpatterns = [ path('',include(router.urls)), path('organisation_list/',OrganisationList.as_view()), ] Routes router = DefaultRouter() router.register(r'list_organisation',OrganisationViewSet) class OrganisationViewSet(ViewSet): permission_classes = [] authentication_classes = [] queryset = Organisation.objects.all() @action(detail=False, methods=['get']) def list_organisations(self,request,*args,**kwargs): print('working') data = self.queryset serializer = OrganisationSerializer(data,many=True) return Response(serializer.data,status=200) error "GET /list_organisation/ HTTP/1.1" 404 3548 -
Django views.py add multiple files
I have a model.py in which I would like to upload multiple files. In my models I have main class and another which I'm trying to use to upload multiple file as suggested. Problem is, I get the following error in my class in views.py 'Exception Value: Unknown field(s) (file) specified for Post' and I can't get it to upload multiple files. model.py class Post(models.Model): title = models.CharField(max_length=40, verbose_name="Naslov predmeta") # a lot more field here but not important file_1 = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteka 1", validators=[validate_file_size]) file_2 = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteka 2", validators=[validate_file_size]) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) class File(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) file = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteke", validators=[validate_file_size]) views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content_don', 'subject', 'rn_number', 'file_1', 'file_2'] def form_valid(self, form): form.instance.author = self.request.user #here I have a lot of code to process data which is writen in the fields response = super(PostCreateView,self).form_valid(form) ################################################################# ##### this code below I'm trying to use to upload multiple files obj = form.save(commit=False) if self.request.FILES: for f in self.request.FILES.getlist('file'): obj = self.model.objects.create(file=f) return response I also tried using forms, but I can't get my scripts/querys and simmilar to work then. Is there a … -
how can i get my project to show under my repo using git when deploying?(django)
:~/portfolio$ ls README.md venvxz My Django project isn't showing up under my repo in the terminal when i want to deploy with AWS! Ive tried "git push origin master", git remote add origin. i think last time i had it working, i pushed my project under a certain branch on GitHub. I have tried git merge, git checkout, my project on GitHub is currently under git master. If i try git branch, it shows 'main' I cannot deploy my website because of this. `:~/portfolio$ git branch main` -
Complex queryset with django content type model
I have a set of models that contain content that is created and contributed by users. Model User: class User(models.Model): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=150, blank=True) is_active = models.BooleanField(default=True) Model Tip: class Tip(models.Model): title = models.CharField(max_length=30, blank=True) content = models.CharField(max_length=150, blank=True) Model Example: class Example(models.Model): headline = models.CharField(max_length=30, blank=True) content = models.CharField(max_length=150, blank=True) Model Struggle: class Struggle(models.Model): headline = models.CharField(max_length=30, blank=True) content = models.CharField(max_length=150, blank=True) and model UserContribution class UserContribution(models.Model): id = models.AutoField(primary_key=True) contributed_by = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name="User that contributed the object", on_delete=models.CASCADE ) contributed_at = models.DateTimeField(auto_now_add=True) object_id = models.PositiveIntegerField( help_text="Primary key of the model", ) content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE ) I want to be able to select a set of users and list the contribution objects they have contributed (created or updated). For example, [ { "user_id": 1, "first_name": "A", "last_name": "B", "tips": [ { "id": 1, "title": "abc", "content": "bcd", "contibuted_at": "2021-08-10" }, { "id": 2, "title": "eabc", "content": "abcd", "contibuted_at": "2021-08-09" } ], "examples": [ { "id": 1, "headline": "abc", "content": "bcd", "contibuted_at": "2021-08-10" }, { "id": 2, "headline": "eabc", "content": "abcd", "contibuted_at": "2021-08-09" } ], "struggles": [ { "id": 1, "headline": "abc", "content": "bcd", "contibuted_at": "2021-08-10" }, { "id": 2, "headline": "eabc", "content": … -
python - Cancel an already executing task with Celery
I need to cancel a task created by celery. I came across this article - Cancel an already executing task with Celery? Since I am calling the task inside my django view, I am also trying to cancel it inside my django view, which looks something like: import myproj.tasks as tasks task = tasks.mytask.delay(...) #I don't have the luxery to do task.revoke() taskid = task.task_id tasks.app.control.revoke(taskid, terminate=True, signal="SIGKILL") I check my worker... and it doesn't give me any indication to think that the worker has stopped working on the task, and it still the same amount of time to actually complete the task as it does to kill it (250 seconds)........ and then the "killed task" disrespectfully returns 250 seconds after its completed. Something else maybe worth mentioning is that the task file imports a class that I've made... so in the task file I have my task defined with the task decorator above the definition, then literally it returns: return myclass.myclass(**kwargs) A potential work around I've considered is copying and pasting my class file into my tasks so that I can set a flag inside blocks of the code to check to see if it needs to be aborted … -
How to debug an Django application running in AWS EC2
I deployed a django app on AWS Elastic Beanstalk and did run it. Some endpoints works well but something said <h1>Server Error (500)</h1> The endpoints with taking errors works well in my local env but took above error when I run it on AWS. So I gonna debug why it takes error... Please help me! Noticed: I have the ssh access. And I checked the /var/log/ directory but I did not find the logging error of application. -
how to authenticate a user using django rest framework
I am trying to authenticate a user using django rest framework and authenticate import below but for some reason i keep getting null as a result when i check the front end with reactJS, i am referring to the variable logged_in_used below: from django.contrib.auth import authenticate ... if request.method == "POST": username = request.data.get('username') password = request.data.get('password') get_user = User.objects.get(username=username) logged_in_used = authenticate(username=get_user.username, password=get_user.check_password(password)) ... # data with token dictionnary ... result = (data_with_token, logged_in_used, status.HTTP_200_OK) Is there something that i am doing wrong here? -
NGROK With Python and Raspberry Pi
I am sorry to return with more ngrok/django issues, but this seems super inconsistent. I am trying to send a string from my django site hosted on heroku to a forwarded socket on my raspberry pi. Testing with both the website and netcat SERVER:PORT(redacted obviously) I am getting TTL(total connections through) but nothing is happening on my python file. I am not sure why this is happening but if anybody sees anything obvious in my code or img then the help would be great! https://imgur.com/a/OZzsDyT Pi script PORT = REDACTED SERVER = '0.0.0.0' ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" my_queue = queue.Queue() print(SERVER) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): print(f"[NEW CONNECTION] {addr} connected") connected = True while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) if msg == '!DISCONNECT!': connected = False print("disconnect") break else: my_queue.put(msg) print(f"[{ADDR}] {msg}") conn.send("MSG Received".encode(FORMAT)) conn.close() def start(): server.listen() print(f"[LISTENING] Server Is Listening On {SERVER}") while True: conn, addr = server.accept() thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start() print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}") print("[Starting] Server") threading.Thread(target=start).start() msg = my_queue.get() print(msg) Django View: HEADER = 64 PORT = REDACTED SERVER = 'REDACTED' ADDR = (SERVER, PORT) FORMAT … -
how can i display all products by user and edit them ? on django
how can i display all products and edit them ? im working on e-commerce project and i want every user add his own products by himself Blockquote Blockquote Blockquote views.py def ProductsFunction(request): Prodcuts = Product.objects.filter(user=request.user) form = ProductEditForm(instance=Product) if request.method == 'POST': form = ProductEditForm(request.POST,request.FILES,instance=Product) if form.is_valid(): form.save() return redirect('accounts/products') context = { 'product':form } return render(request, 'usrstore/products.html',context) models.py class Product(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) ProductName = models.CharField(max_length=100,default=None) ProductDescription = models.TextField(max_length=5000,default=None,null=True,blank=True) ProductPrice = models.DecimalField(max_digits=5,decimal_places=2) ProductCost = models.DecimalField(max_digits=5,decimal_places=2) ProductCreated = models.DateTimeField() Active = models.BooleanField(default=True) CategoryProduct = models.ForeignKey(Category,on_delete=models.CASCADE,default=None) def __str__(self): return self.ProductName @receiver(post_save, sender=User) def createProduct(sender,instance,created,**kwargs): if created: Product.objects.create( user=instance ) Html Code <form action="POST"> {% csrf_token %} {% for p in product %} <div class="product"> <div class="product-img mx-auto"> <img src="{{p.PoductImage.url}}" alt=""> </div> <div class="productName"> {{p.ProductName}} {{p.ProductDescription}} {{p.ProductPrice}} <button type="submit">edit</button> </div> </div> </form> {% endfor %} The Problem -
heroku [remote rejected] main -> main (pre-received hook declined)
I tried to push my code from github and heroku said it couldn't get decide on the build and gave me this error. I set the build to python (since my app is made in Django) but it still gives me the same error when I try to run it again. Now it says remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 1f09558f6b29e630eb55bc936402a9265518d67b remote: ! remote: ! We have detected that you have triggered a build from source code with version 1f09558f6b29e630eb55bc936402a9265518d67b remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version The link provided says the article is a work in progress and it doesn't talk about my error at all. I don't understand what they mean about a different branch since the first time I tried I used the same app, same folders, same … -
Django AttributeError: Importing form class
I'm building a tool which has it's logic written in a separate file tools.py. I created a form which is suppose to pass user input to the variable in my tools.py file. I tried importing the forms class into my tools.py and assigned them to my variables but it has been showing this error AttributeError: type object 'ToolsForm' has no attribute 'sender_input' meanwhile these are my forms.py and tools.py file: Forms.py: from django import forms class ToolsForm(forms.Form): sender_input = forms.EmailField(required=True, widget=forms.TextInput(attrs= {'placeholder': 'Enter your mail account here:'})) Tools.py: from tools.forms import ToolsForm formDetails = ToolsForm sender_input = formDetails.sender_input -
Creating a button that can be used to forward a blog post between users in Django
I am creating a blog post in Django but find it difficult to create a forward button where posts and comments on them can be forwarded from one user to another user. -
Selecting all script tags in HTML using Scrapy in Django
I want to get all script tags from a url but there is an issue I'm facing. Let's say url is: https://somewebsite.com/ How my parse function looks like in my spider class (which is very basic one): def parse(self, response, **kwargs): """ Parses the response. """ script_elements = response.css("script") # There are lots of script tags but most of them are missing. # Let's say, in website, there are 25 script tags. # The code above will return 3 or 4 of them. parsed_result = list() for script_element in script_elements: script = script_element.extract() # other code blocks return parsed_result But when I run scrapy with shell like this: scrapy shell https://somewebsite.com/ And when I select the script tags in shell: response.css("script").extract() I got exactly what I want. Every script tags in HTML is there. Why is there such a difference? I'm running Scrapy with Django web application (I don't know If this makes any difference.) -
DJango ORM double join with Sum
I searched for a similar case on SO and Google with no luck. SHORT EXPLANATION I have transactions that belong to an account, and an account belongs to an account aggrupation. I want to get a list of accounts aggrupations, with their accounts, and I want to know the total balance of each account (an account balance is calculated by adding all its transactions amount). LONG EXPLANATION I have the following models (I include mixins for the sake of completeness): class UniqueNameMixin(models.Model): class Meta: abstract = True name = models.CharField(verbose_name=_('name'), max_length=100, unique=True) def __str__(self): return self.name class PercentageMixin(UniqueNameMixin): class Meta: abstract = True _validators = [MinValueValidator(0), MaxValueValidator(100)] current_percentage = models.DecimalField(max_digits=5, decimal_places=2, validators=_validators, null=True, blank=True) ideal_percentage = models.DecimalField(max_digits=5, decimal_places=2, validators=_validators, null=True, blank=True) class AccountsAggrupation(PercentageMixin): pass class Account(PercentageMixin): aggrupation = models.ForeignKey(AccountsAggrupation, models.PROTECT) class Transaction(models.Model): date = models.DateField() concept = models.ForeignKey(Concept, models.PROTECT, blank=True, null=True) amount = models.DecimalField(max_digits=10, decimal_places=2) account = models.ForeignKey(Account, models.PROTECT) detail = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return '{} - {} - {} - {}'.format(self.date, self.concept, self.amount, self.account) I want to be able to do this in Django ORM: select ca.*, ca2.*, sum(ct.amount) from core_accountsaggrupation ca join core_account ca2 on ca2.aggrupation_id = ca.id join core_transaction ct on ct.account_id = ca2.id group … -
Django Model Custom Field Problems
I've been trying to get this done for days but still can't see where the error is. At the moment I'm using the generic CreateView in views.py for form processing. The particular text field in question is supposed to take a string in the format of "HH:mm" or ":mm" (or 0), convert it to minutes and store in the DB as an integer. For some reason the form.errors still says this must be an integer. Obviously initially it is a string, but should be an integer by the time it gets to saving. Custom Model Field in models.py class FlightTimeFieldInt(models.IntegerField): description = "a field to input flying time" def get_db_prep_value(self, value, *args, **kwargs): if value is None: return None return value def to_python(self, value): if value is None or isinstance(value, int): return value if str(value.split(":")[0]) == '': split = value.split(":")[1] value = int(split) print(value) return int(value) else: h, m = value.split(":") value = (int(h) * 60) + int(m) return value def from_db_value(self, value, expression, connection, context): return self.to_python(value) def formfield(self, **kwargs): defaults = {'form_class': None} defaults.update(kwargs) return super(FlightTimeFieldInt, self).formfield(**defaults) There could be a better way but not sure how to go about it. Thanks for your help! -
Is there a way to dynamically create django models(classes)?
I have been assigned a challenging task recently, we are designing a website for our customers, and my boss wanted me to create flexible model-creation functions: which means he doesn't want us to "hard code" the models, he told us not to manually define django models but to create them at system runtime. For example, we have no models related to our business process at first, admin users can define a form's format on our front pages which will be processed by general users later. Then our backend receives the request from front-end and create the form model with fields provided. I found I can create a class by type() function like type(class_name, (models.Model,), attrs), and I did get new class via this function. But I was wondering how to persist this class in our system? Like saving this new class into my models.py and making migration so that our DB has it as well -
NOT NULL constraint failed Django
I want to save Department model forms with Model Direccion values, using foreign key in Department, but I have this error. Models.py class Direccion(models.Model): calle = models.CharField(max_length=50) numero = models.CharField(max_length=6) #comuna = models.ForeignKey(Comuna, on_delete=models.CASCADE) class Departamento(models.Model): n_habitaciones = models.IntegerField(max_length=1) n_banios = models.IntegerField(max_length=1) n_depto = models.CharField(max_length=5) descripcion = models.CharField(max_length=500) precio = models.IntegerField(max_length=10) img1 = models.ImageField(upload_to='Departamentos/') img2 = models.ImageField(upload_to='Departamentos/') img3 = models.ImageField(upload_to='Departamentos/') img4 = models.ImageField(upload_to='Departamentos/') img5 = models.ImageField(upload_to='Departamentos/') direccion = models.ForeignKey(Direccion, on_delete=models.CASCADE) Forms.py class DeptosForms(forms.ModelForm): descripcion = forms.CharField(max_length=1000, widget=forms.Textarea) img1 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'})) img2 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'})) img3 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'})) img4 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'})) img5 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'})) calle = forms.CharField(max_length=50) numero = forms.CharField(max_length=6) class Meta: model = Departamento fields = ('n_habitaciones', 'n_banios', 'n_depto', 'precio', 'descripcion', 'img1', 'img2', 'img3', 'img4', 'img5', 'calle', 'numero', ) Views.py def AddDepto(request): if request.method == 'POST': form = DeptosForms(request.POST, request.FILES) if form.is_valid(): depto = form.save() depto.save() messages.success(request, 'Departamnto registrado correctamente') return redirect('show_deptos') else: form = DeptosForms() return render(request, 'core/add_dptos.html', {'form': form}) Error: enter image description here -
Django 3 - Passed variable in views.py not accessible in web form like other vars
Newbie to Django here - I have a list of DB entries that I want to be able to cycle through one at a time and currently I am working on loading the first object by its ID. The form renders fine, but other vars aren't accessible as expected - am I missing something in the code? views.py def ticket_edit(request): updateform = TicketForm(request.POST) if request.method == 'POST': if updateform.is_valid(): ticket = Ticket.objects.update( ticketID=updateform.cleaned_data['ticketID'] ) ticket.save() return HttpResponseRedirect(".") else: print("FORM NOT YET VALID: Awaiting form.is_valid()") updateform = TicketForm() #--Get list of ticketIDs--------------- def ticketID_listGet(): tickets = Ticket.objects.all() ticketIDList = [] for ticket in tickets: aTicketID = ticket.appTicketID ticketIDList.append(aTicketID) return ticketIDList tList = ticketID_listGet() tFirst = str(tList[0]) print('TicketIDs: ', tList, tFirst) return render(request,'authentication/ticket-edit.html',{ "has_error": False, "updateform": updateform, "tFirst": tFirst }) ticket-edit.html <div class="container" style="border-style:none"> <form action="." method="POST" id="ticket-update-form" style="border-style:none"> {% csrf_token %} <div class="row"> <div class="col-md-12"> <div class="form-control" style="border-style:none"> {{ updateform.ticketID.label_tag }} {{ updateform.ticketID }} {{ tFirst }} </div> </div> </div> I am not getting errors when using {{ tFirst }}, it's just being ignored as if unrecognized. Ultimately I am trying to determine how to retrieve the existing ticketIDs and the first ticketID as vars and then cycle through them with … -
Create bulk permission retrieval for django user.has_perms to improve speed of the code
I have such a function that runs for multiple projects and users: def has_project_permissions(project, user, can_edit=False, is_owner=False): permission_level = CAN_VIEW if can_edit: permission_level = CAN_EDIT if is_owner: permission_level = IS_OWNER return user.has_perm(permission_level, project) or (user.is_staff and not project.disable_staff_access) Currently I am using for loop to iterate over each user and each project and get permissions. Is there a way to rewrite it and get all the permissions for all of the users and projects in Django? I need it to improve speed since when there are too many users and projects, obviously speed is going to be very bad. I would expect its possible in Django somehow. Here is the function in which I am iterating over projects. Iteration over users happens one level above (not included): def _get_json_for_user(projects, user): """Returns JSON representation of the given User object Args: user (object): Django user model Returns: dict: json object """ if hasattr(user, '_wrapped'): user = user._wrapped # Django request.user actually stores the Django User objects in a ._wrapped attribute user_json = {_to_camel_case(field): getattr(user, field) for field in ['username', 'email', 'first_name', 'last_name', 'last_login', 'is_staff', 'date_joined', 'id']} user_json['displayName'] = user.get_full_name() csi_user = True if user: if len(projects) == 0: csi_user = False else: … -
How to get id of clicked item Django
Hello i have a list of items in the cart but i would like to decrease, increase and delete items from the cart but I have no idea how to get "pk" of these items. Should i use update view if I do not want to use JS? views.py class CartView(TemplateView): template_name = "shop/cart.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cart'] = Cart.objects.annotate( price=Sum(F('orderitem__item__price') * F('orderitem__quantity')) ).get(order_user= self.request.user) cart = context['cart'] cart.total = cart.price cart.save() context['order_items'] = OrderItem.objects.filter(cart=cart) return context def post(self, request, pk): if 'minus' in request.POST: cart = Cart.objects.get(order_user=self.request.user) OrderItem.objects.filter(id=pk, cart=cart).update( quantity=F('quantity')-1) return HttpResponse("cart uptaded") -
Does it Make Sense to Dynamically Add EC2 Instance Private IPs to Django's CACHE LOCACTION Setting in an Elastic Beanstalk Environment with NGINX?
I'm using Elastic Beanstalk with load balancing and I've set a minimum number of instances to 2. So I have two instances with two different private IPs. What I'm trying to achieve is to add Memcached caching locations dynamically to Django's CACHES setting based on the EC2 instances that exist in an environment. My Primary Question Since Elastic Beanstalk uses NGINX (in my case), do I need to dynamically add the instance IPs to Django's CACHES location? Or would setting 'LOCATION': '127.0.0.1:11211', be sufficient for all running EC2 instances? Secondary Question Does NGINX centralize the cache for all running instances? My NGINX primary config: (staging) [ec2-user@ip-172-31-9-242 conf.d]$ cat elasticbeanstalk/00_application.conf location / { proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Connection $connection_upgrade; proxy_set_header Upgrade $http_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } The Django documentation says the same cache can be shared across multiple servers - Memcached caching: One excellent feature of Memcached is its ability to share a cache over multiple servers. This means you can run Memcached daemons on multiple machines, and the program will treat the group of machines as a single cache, without the need to duplicate cache values on each machine. To take advantage of … -
What is the purpose of deleting kwargs in a field's deconstruct method?
With the documentation detailing how to write a custom model field: Writing custom model fields, I'm failing to understand the implementation of Field Deconstruction and the deconstruct(). In the example they provided: For example, in our HandField class we’re always forcibly setting max_length in init(). The deconstruct() method on the base Field class will see this and try to return it in the keyword arguments; thus, we can drop it from the keyword arguments for readability: from django.db import models class HandField(models.Field): def __init__(self, *args, **kwargs): kwargs['max_length'] = 104 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs Reading further down in the documentation it says the following: for any configuration of your Field instance, deconstruct() must return arguments that you can pass to init to reconstruct that state. Why is the keyword argument max_length being deleted if its required to instantiate the field?