Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: making an evenly distributed mixed item feed
Let's say I want to generate a feed consisting of ItemA and ItemB, each item has a "published_date" field and newer items should appear at the top of the feed. However I want to further ensure that the feed always has 2 of ItemA, followed by 1 of ItemA, followed by 2 of ItemA,....regardless of the absolute publish date (i.e. even if the 10 most recent published items were all A, I'd still see B as the third item if there is an instance of it). How can I achieve something like this in Django? I was originally doing this something like # models.py class FeedItem(models.Model): id = HashidAutoField(primary_key=True, min_length=8, alphabet="0123456789abcdefghijklmnopqrstuvwxyz") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True, db_index=True) # When is this scheduled to be published publish_date = models.DateTimeField(db_index=True) # Type of Feed Item ITEM_TYPES = Choices((1, 'A', 'ItemA'), (2, 'B', 'ItemB')) # item_type item_type = models.PositiveSmallIntegerField(db_index=True, choices=ITEM_TYPES) def save(self, force_insert=False, force_update=False, using=None, update_fields=None, **kwargs): """ Ensure that when we save each subclass then we get the correct item_type :param force_insert: :param force_update: :param using: :param update_fields: :param kwargs: :return: """ if (self.__class__.__name__ == 'FeedItemA' and self.item_type != self.ITEM_TYPES._identifier_map['A']): self.item_type = self.ITEM_TYPES._identifier_map['A'] elif (self.__class__.__name__ == 'FeedItemB' and self.item_type != self.ITEM_TYPES._identifier_map['B']): … -
Celery. How to kill a task when it exceeds a certain execution time?
I would like to kill a task when it exceeds a certain execution time. I have been trying with the expires argument and with the time_limit and soft_time_limit configuration variables, but neither works as the task continues to run after this time exceeds. I'm using celery==5.0.5, redis==3.5.3 and Django==3.1.7 This is the code I have been using: # In settings.py CELERY_BROKER_URL = "redis://redis:6379" CELERY_RESULT_BACKEND = "redis://redis:6379" CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/Mexico_City' CELERY_ENABLE_UTC = True CELERYD_TASK_TIME_LIMIT = 300 CELERY_TASK_TRACK_STARTED = True # In tasks.py @shared_task(name='some_process') def some_process(_id, flag): # Do some long process pass # Running the task expires = 300 tasks.some_process.apply_async((_id, flag), expires=expires) I also read other questions, but they have the reverse problem: link, link link -
Update quantity of cart after add product to cart AJAX / Django without refreshing page?
The product is successfully added in the cart but the cart value is not up to date. I will have to refresh the page so that the div is up to date. I tried the load() and html() methods but anything will happened. How to refresh cart container when I add the product to the cart ? I need a help please. Views Django def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({'status': 'success'}) Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Form Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> HTML Span <ul class="navbar-nav ml-auto d-block d-md-none"> <li class="nav-item"> <a class="btn btn-link" href="#"><i class="bx bxs-cart icon-single"></i> <span class="badge badge-danger" id="cartval">{{ cart | length }}</span></a> </li> </ul> JS Code $(".form-order").on('submit', function(e){ e.preventDefault(); var product_id = $(this).attr('data-id') var quantity = $(this).find("#id_quantite").val() console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id+'/' $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, type: 'POST', dataType: 'json', data: data, success: … -
Is it possible to use an iframe in django without putting it in static and generating a url?
In an app made with django, I want to call the editor.html file as an iframe in the search.html file in the following folder. my app template serach.html editor.html Most answers are to register editor.html in url or go to static file. I have checked that both methods are currently running, but I want to save them in the same folder and call them without registering the url. The code that calls the current iframe is <iframe id="sketch" src="./editor.html" </iframe> I wrote it, but the iframe doesn't work. Is there any other way besides the two above? -
Django project does not work after being transferred from Windows to Mac
I'm using Django 3.1.7 on a MacBook Pro after transferring the Django project off of a Windows 10 machine. However, upon re-setting up the database and superuser and running the command pipenv sync to install all necessary modules, the server does run; but it doesn't serve any of my URLs or the CSS styles for the Admin page. I can reach the admin page at '/admin' but no other page that I've set up will display. All it gives me is my custom 404 page whenever I try to serve a page. Is there any way to fix this? Is something wrong? Where are the Admin CSS files? -
How to include an avatar/profile image in Django send_email with a "noreply" address?
In email clients such as Gmail and Apple Mail, with each incoming email there's an avatar/profile image of the email's sender. I have a Django app that sends emails from a "noreply@mycompany.com" email address using send_mail. The (sanitized) code looks something like the following: from django.template.loader import get_template from django.core.mail import send_mail from myapp.models import User ... users = User.objects.all() subject = 'Email for {name}'.format(name=user.name) plaintext = get_template('emails/email_template.txt') html = get_template('emails/email_template.html') data = {'name': user.name} text_content = plaintext.render(data) html_content = html.render(data) for user in users: send_mail(subject, text_content, 'noreply@mycompany.com', [user.email], html_message=html_content) print('Email sent: ' + user.email) I want to have my company's logo be displayed in email clients as the avatar/profile image. What is the best way to accomplish this? For example, is this something I can specify in my emails' Django template? -
Django, lose the variables of a template when I call the extended template
I have a django project and an random app, a homepage.html in localhost:8000/, a base.html with a path url: /base/some_id, an extended template1.html with url:/base/some_id/template1. base.html <body> <h2>{{message}}</h2> <a href="{% url 'template1' some_id %}">BUTTON</a> {% block content%} {% endblock %} </body> template1.html {% extends 'base.html' %} {% block content %} <p>some text here</p> {% endblock %} urls.py urlpatterns = [ path('', views.home, name = 'homepage'), path('base/<int:some_id>/',views.base, name = 'base'), path('base/<some_id>/template1/', views.template1, name = 'template1'),] views.py def base(request,some_id): context={ "message":"Hello", "some_id":some_id, } return render(request,"base.html",context) def template1(request,some_id): return render(request,"base.html",{"newmessage":"some text"}) My page base.html is correctly displayed, but when I click to the tag to go to template1 I take a message "Reverse for 'template1' with arguments '('',)' not found...." I've tried many things but nothing worked, I think my issue is that the variable "some_id" doesn't have any value in template anymore. Any help would be appreciated! Thank you in advance guys! -
DJANGO: Upload image file to cart
I am completing a project which involved building a shopping cart. The shopping cart requires the user to attach an image to the OrderItem The cart is updated from the store via javascript. I have been able to separate out the code into a separate view and have it successfully upload the image, but to an separate instance of the OrderItem which is not connected to the existing orderitem. When attached on the cart the user is able to upload in the browser, but the file is not transmitted to the DJANGO backend or uploaded to the file location. The page reloads but no traceback is present. I am new to coding and have only limited experience. Please help! Settings.py """ Django settings for ecommerce project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = # SECURITY WARNING: don't run with debug turned … -
How to access a point in postgis database from Django?
I am trying to get points (latitude longitude coordinates) from my database using django / postgis, but I run into this error that I can't figure: django.db.utils.ProgrammingError: cannot cast type point to bytea LINE 1: ...lon_id", "lat_lon"."house_id", "lat_lon"."lat_lon"::bytea FR... My database looks like this: And I set up my model (models.py) like this: class LatLon(models.Model): lat_lon_id = models.AutoField(primary_key=True) house = models.ForeignKey(Houses, models.DO_NOTHING) lat_lon = models.PointField() class Meta: managed = False db_table = 'lat_lon' @property def lat_lng(self): return(list(getattr(self.lat_lon, 'coords', []))[::-1]) and make a listview (views.py): class LatlonList(ListView): queryset = LatLon.objects.filter(lat_lon__isnull=False) Finally my urlpatterns look like this: urlpatterns = [ path("", views.home, name="home"), path("hello/<name>", views.hello_there, name="hello_there"), path("about/", views.about, name="about"), path("contact/", views.contact, name="contact"), path("log/", views.log_message, name="log"), path("test_page/", views.LatlonList.as_view(template_name = 'test_page.html'), name="test_page"), path('map/', views.EntryList.as_view()), I guess from the error that Django tries to cast my points to bytea data type, but I clearly specify in the model that they are points (Pointfield). I am new to django, so any responses/hints are appreciated! -
Django Loading Page while Server does some backend retrieval
I am trying to bulid a website via Django. Basically what I'm after is that the website will first open a simple loading screen. On that time there is some processing done in the backend to retrieve the data. Once data retrieval is finalised the loading page is redirected to another page. Any idea on how this can be done please. I'm pretty convinced that I need to use Ajax but would really love to get the syntax of how it can be done Thanks -
CBV form_valid() and form_invalid() methods not called, form not saved to database
I tried following this tutorial: Link Whenever I try creating/updating/deleting a Record (my model, in this case) it redirects me to the page I've told it to redirect me to, and displays that a POST has been called in the command prompt, yet the Record is not created. I've tried overwriting both the form_valid() and form_invalid() functions, and added some print statements. Neither print statements print, so I don't believe either of these methods are called. Why are neither of these methods called, and why isn't my model being created and stored? Here's the model creation form, record_form.html: {% extends "catalog/base.html" %} {% block content %} <h1 class="text py-3 pt-4">Create/Update a Record!</h1> <style> .text { font-size: 40px; font-weight: bold; color: #060007; } </style> <div class="shadow p-3 mb-3 bg-light rounded"> <form class="form" method="POST" action="/catalog/"> {% csrf_token %} <p><label for="my_catalog">Catalog name:</label> {{ form.my_catalog }}</p> <p><label for="name">Name:</label> {{ form.name }}</p> <p><label for="description">Description:</label></p> <p>{{ form.description }}</p> <p><label for="date_start">Date start:</label> {{ form.date_start }}</p> <p><label for="date_end">Date end:</label> {{ form.date_end }}</p> <p><label for="manufacturer">Manufacturer:</label> {{ form.manufacturer }}</p> <p><label for="condition_rating">Condition rating (between 0 and 5):</label> {{ form.condition_rating }}</p> <p><label for="condition_description">Condition description:</label></p> <p>{{ form.condition_description }}</p> <div><input type="submit" value="Save"></div> </form> <style> .form { color: #060007; } </style> </div> {% endblock content … -
Docker - Django - PermissionError after switching to Host volumes on Ubuntu Server
The Docker image / container worked fine on Ubuntu, however I wanted to have access to the static folder. Therefore I added "Host volumes" to the docker-compose.yml (volumes was empty before): version: '3.3' services: api: build: context: . restart: always ports: - "8000:8000" volumes: - ./app_static:/app/static $ docker-compose up After building the image and running the python manage.py collectstatic command, I get the following error: PermissionError: [Errno 13] Permission denied: 'static/media' The folder structure inside the docker image looks like this: appuser@1e2bc02404a2:/app$ ls -la total 24 drwxr-xr-x 1 appuser appuser 4096 Mar 29 21:50 . drwxr-xr-x 1 root root 4096 Mar 29 21:51 .. drwxr-xr-x 1 appuser appuser 4096 Mar 29 21:00 api -rw-r--r-- 1 appuser appuser 765 Mar 29 21:00 manage.py drwxr-xr-x 1 appuser appuser 4096 Mar 29 21:00 mausefallentest drwxr-xr-x 2 root root 4096 Mar 29 21:51 static The problem is, that after adding Host volumes to the docker-compose file, the user for the static folder changed to root. But the Docker image is runnung under the "appuser" user. Thus i get the permission denied error. But how can i solve this problem ? I only have this problem on my Ubuntu server. On Windows its working fine. -
Unable to Save images to database
am unable to save images containing url on database this will give me an error if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' this error is as a result of my attempts to save this scrapped image with beautiful soup below are images list that refused to be saved on my models , this images are been scrapped with beautiful soup something like this brought the images images = [i['data-src'] for i in soup.find_all('img', {'class','attachment-jnews-750x375 size-jnews-750x375 lazyload wp-post-image'})] https://people.net/wp-content/uploads/2021/03/ad1-746x375.jpg https://people.net/wp-content/uploads/2020/08/caroon-1-600x375.jpg why this code brought the above error Post.objects.create( title=title, content_1=paragraphs, image=images, sources=lnk, ) this is my model.py example code class Post(models.Model): title = models.CharField(max_length=250, blank = True, help_text='Maximum 160 Title characters.') image = models.FileField(upload_to='images', blank=True, null=True, help_text='You must upload original image before continuing.') but i get this error if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' but if am saving normal jpeg file it is always a success. how do i save this scrapped images to models -
django braintree authorization error generating token
im trying to integrate django with braintree but im getting authorization error everything seems fine but when i place order after filling the order form i get error: AuthorizationError at /payment/process/ line 39, in payment_process caused by this line :client_token = gateway.client_token.generate() my views.py import braintree from django.shortcuts import render, redirect, get_object_or_404 from django.conf import settings from order.models import Order # instantiate Braintree payment gateway gateway = braintree.BraintreeGateway(settings.BRAINTREE_CONF) def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) total_cost = order.get_total_cost() if request.method == 'POST': # retrieve nonce nonce = request.POST.get('payment_method_nonce', None) # create and submit transaction result = gateway.transaction.sale({ 'amount': f'{total_cost:.2f}', 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # mark the order as paid order.paid = True # store the unique transaction id order.braintree_id = result.transaction.id order.save() return redirect('payment:done') else: return redirect('payment:canceled') else: # generate token client_token = gateway.client_token.generate() return render(request, 'payment/process.html', {'order': order, 'client_token': client_token}) def payment_done(request): return render(request, 'payment/done.html') def payment_canceled(request): return render(request, 'payment/canceled.html') my process template {% extends "shop/base.html" %} {% block title %}Pay by credit card{% endblock %} {% block content %} <h1>Pay by credit card</h1> <form id="payment" method="post"> <label for="card-number">Card Number</label> <div id="card-number" class="field"></div> <label for="cvv">CVV</label> <div id="cvv" class="field"></div> <label for="expiration-date">Expiration Date</label> … -
Django Python iterate attribute of object from list
i have a set of atributes stored on list, and i have an object called customuser, i want to iterate its attribute from the list and display value from database fieldx={'department','usertype','company'} for f in fieldx: print(customuser.f) but i get the following error message: 'CustomUser' object has no attribute 'f' can you help me with this many thanks -
how can insert multiple record using
I'm working on a small project Django Rest Framework, I already create add contact function as you can see in my create function. now I'm working on bulk import, but when I submit my data as a list not as a dict I get an error message : {"non_field_errors":["Invalid data. Expected a dictionary, but got list."]} this is my code to add a contact, class ContactView(ListModelMixin, viewsets.GenericViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer def create(self, request): serializeObject = ContactSerializer(data = request.data) if serializeObject.is_valid(): serializeObject.save() contactObject = Contact.objects.all() contactSerializer = ContactSerializer(contactObject, many=True) return Response(contactSerializer.data, status = status.HTTP_201_CREATED) return Response(serializeObject.errors, status.HTTP_400_BAD_REQUEST) Now i would like to create another function, for bulk create, since i have a list -
Error: Unknown option '--output' React & Django
In my package.json file I have: "scripts": { "dev": "webpack --mode development ./x/frontend/src/index.js --output ./x/frontend/static/frontend/main.js", "build": "webpack --mode production ./x/frontend/src/index.js --output ./x/frontend/static/frontend/main.js" }, and when I try to run this command: npm run build it shows me an error: [webpack-cli] Error: Unknown option '--output' How can I fix this? -
Should i use proxy models in django?
im here trying to start a new project, in django and i came across this problem, while creating the models My users will be different types of users, so i was thinking, should i use proxy models for it? because here is how it´s going to be the realtionship between them. i will have a client, and a personal trainer, and the admin of course, but the problem here is that the client is going to have a ForeignKey with personal trainer, my main question is, can i create in a proxy model an extra field where i establish the relationship with personal trainer proxy model? If not, is there any other way that i can aproach this type of situation Thanks in advance -
Dockerize Django with Celery worker/beat, RabbitMQ and postgresql
I want to setup docker-compose for my app, which contains Django, Celery (+Beat), RabbitMQ and PSQL. My problem is that celery beat container does not work as intended (does not schedule a task with interval 10s). Docker logs - celery beat wakes up in 5.00 minutes, celery worker works fine celery-worker_1 | [2021-03-29 21:05:58,201: INFO/MainProcess] mingle: all alone celery-worker_1 | [2021-03-29 21:05:58,225: WARNING/MainProcess] /usr/local/lib/python3.9/site-packages/celery/fixups/django.py:205: UserWarning: Using settings.DEBUG leads to a memory celery-worker_1 | leak, never use this setting in production environments! celery-worker_1 | warnings.warn('''Using settings.DEBUG leads to a memory celery-worker_1 | [2021-03-29 21:05:58,225: INFO/MainProcess] celery@247ea26ee17b ready. celery-beat_1 | [2021-03-29 21:06:00,525: DEBUG/MainProcess] Setting default socket timeout to 30 celery-beat_1 | [2021-03-29 21:06:00,526: INFO/MainProcess] beat: Starting... celery-beat_1 | [2021-03-29 21:06:00,749: DEBUG/MainProcess] Current schedule: celery-beat_1 | <ScheduleEntry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * * * (m/h/d/dM/MY)> celery-beat_1 | [2021-03-29 21:06:00,749: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes celery-beat_1 | [2021-03-29 21:06:00,751: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. Dockerfile FROM python:3 ENV PYTHONBUFFERED=1 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt docker-compose.yml version: '3.8' services: server: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" env_file: - .env depends_on: - pgdb - rabbit - celery-worker celery-worker: build: … -
django oauth toolkit `or` in required scopes in view
I'm using drf and oauth toolkit with IsAuthenticatedOrTokenHasScope permissions as default. I have a view that contains scopes required_scopes = ['mod', 'admin'] When users logs into the app he have special groups which define his permission scope. So when the moderator logs into the app he gets mod scope. When he calls my view he gets 403 because allow_scopes in AccessToken model returns False. That is because the resource_scopes is ['mod', 'admin'] and provided_scopes is 'mod'. When method allow_scopes checks resource_scopes.issubset(provided_scopes) she returns False which is not intentional in my case. Is there any other option without overwriting allow_scopes in AccessToken model to define that this view needs scope mod or scope admin. ? -
How to objects.get/objects.filter from a "through" class?
im a beginner at django - so im a bit lost with how to go about this. I have three classes: Recipe, Ingredient and IngredientAmount - where IngredientAmount acts a "through" class class IngredientAmount(models.Model): SINGLE = 1 DOUBLE = 2 TRIPLE = 3 AMOUNT_CHOICES = ( (SINGLE, 'Single'), (DOUBLE, 'Double'), (TRIPLE, 'Triple'), ) recipe = models.ForeignKey( 'Recipe', related_name='ingredient_amounts', on_delete=models.SET_NULL, null=True) ingredient = models.ForeignKey( 'Ingredient', related_name='ingredient_amounts', on_delete=models.SET_NULL, null=True, blank=True) amount = models.IntegerField(choices=AMOUNT_CHOICES, default=SINGLE) def __str__(self): return f'Recipe = {self.recipe}, Ingredient = {self.ingredient}, Amount = {self.amount}' they connect to my Recipe class class Recipe(models.Model): alphanumeric = RegexValidator( r'[a-zA-Z][a-zA-Z ]+', 'Only alphabet characters and spaces are allowed.') title = models.CharField(max_length=30, null=True, validators=[alphanumeric]) description = models.TextField(max_length=200, null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) slug = models.SlugField(null=False, unique=True) ingredients = models.ManyToManyField( 'Ingredient', through='IngredientAmount', related_name='recipes') def __str__(self): return self.title def get_absolute_url(self): return reverse('recipe:recipe_detail', kwargs={'slug': self.slug}) the Ingredient class is a simple one with just 'name' variable: class Ingredient(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name And i managed to use a slug to get a RecipeDetail page in my views.py: def recipeDetail(request, slug): recipe = get_object_or_404(Recipe, slug=slug) return render(request, 'recipe/recipe_detail.html', {'recipe': recipe}) So in my templates I can now display the data … -
Why is Python .title() sticky? Applying title case to future strings?
This is a strange one: I'm trying to format a string in python (obviously), and when I use string.title(), it seems like python keeps applying title case to the string, even after applying other formatting to the string. Here's my code: def format_trade_name(self): tr_name = self.trade_name.title() tr_cap = [ 'oxy', 'depo', 'edex', 'emla', 'pred', ] tr_join = '|'.join(tr_cap) tr_regex = r'\b(?!(' +tr_join + r'))(\w{1,4})\b' print(tr_regex) tr_matches = re.search(tr_regex, self.trade_name,re.IGNORECASE) print(tr_matches.groups()) for i in tr_matches.groups(): if i is not None: tr_name = re.sub(r'\b'+i+r'\b',i.upper(),tr_name) print(tr_name) return tr_name Here's the problem: I want the function to capitalize the first letter of each word, and then convert all 4 letter strings (not in tr_cap) to upper case. So if the original string is tylenol depo er, I want the formatted string to be Tylenol Depo ER When I change the 2nd line to tr_name = self.trade_name.capitalize(), my function changes tylenol depo er into Tylenol depo ER (depo is not capitalized). When I keep the 2nd line as as written, tr_name = self.trade_name.title(), my function changes tylenol depo er to Tylenol Depo Er (Er isn't upper case, even though the formatting was applied after using .title(). Can anyone explain to me why the string is … -
Are django signals the correct tool to do post-upload processing?
I'm building a website where I want the website admin to be able to upload a pdf file via the admin site and then for those files to be downloadable via clickable images somewhere on the site (the images would be generated based on the first page of the pdf). I was thinking, I'd use django signals to generate these images every time a pdf is uploaded like so: class Forms(models.Model): name = models.CharField(max_length=200) upload = models.FileField(upload_to='main/data/forms/', validators=[FileExtensionValidator(['pdf'])]) @receiver(post_save, sender=Forms) def generate_image(sender, **kwargs): //do some image generation here Are signals the right tool for this job? I've been reading tutorials about django signals, and it's emphasized that they should only be used for communication between different parts of the code, or for decoupling your code. Is there a better tool to accomplish what I want? P.S. This is my first ever stackoverflow question. I'm super excited, but if I made some faux pas while posting, please tell me! -
django admin how to add context when using custom action button?
I have a custom action button "Add post" for each record in my admin panel. I want to save in context obj.id to use it for a default value in admin:channels_post_add form class ChannelAdmin(admin.ModelAdmin): list_display = ['title','username', 'invite_link', 'account_actions'] def account_actions(self, obj): !!!! I WANT TO ADD CONTEXT HERE!!!! return format_html('<a class="button" href="{}">Add post</a>', reverse('admin:channels_post_add')) account_actions.short_description = 'Actions' account_actions.allow_tags = True class Meta: model = Channel admin.site.register(Channel, ChannelAdmin) class PostAdmin(admin.ModelAdmin): list_display = ['text', 'media', 'send_type', 'created'] class Meta: model = Post def get_form(self, request, obj=None, **kwargs): form = super(PostAdmin, self).get_form(request, obj, **kwargs) try: post_id = !!! AND USE IT HERE!!!! form.base_fields['channels'].initial = post_id except Exception as e: print(e) return form -
AJAX part of the javascript function doesn't work on my Django Project
I am creating an app using firebase authentication. User id and user email values are stored in firabase because login methods like email/password login, facebook login, google login are included with firebase. But another values needed to store like gender, phone, birth date. Because of that I am trying to get user id and email values with ajax after that I can save in local database like SQLite in development environment. My problem is I can't pass user id value with ajax get request. Here are my codes. I initialized the firebase already. At the below code function is running properly.And else block is running properly too. But AJAX section doesn't working no success no failure no ajax is working. <script> function checkUser() { firebase.auth().onAuthStateChanged(function(user) { if (!user) { window.location.replace("{% url 'app:index' %}"); } else { alert('User is active'); document.getElementById("uid").value = user.uid; document.getElementById("email").value = user.email; $.ajax({ type: "GET", url: "{% url 'app:edit_profile' %}", data: { "email": user.email, "uid": user.uid, }, success: function(data){ console.log("success"); console.log(data); }, failure: function(data){ console.log("failure"); console.log(data); }, }); } }); } window.onload = function() { checkUser(); }; My Django view is this: def edit_profile(request): if request.method == 'POST': return edit_profile_post(request) else: uid = request.GET.get("uid", None) print('UID -----> …