Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CORS Headers not Working ony With One Specific Endpoint on Django Rest
I have a django 1.10 app with django-cors-headers version 2.0.2. I have set up the settings like this: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I have a frontend server on localhost:8080. When I use my local server everything works fine. But when I try to hit my staging server on AWS I get: Access to fetch at 'MY SERVER URL' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. However, the weird thing is that it only happens on one specific endpoint. All the other endpoints work fine on staging server. The endpoint is a basic put() method from a ModelViewSet from the Django Rest Framework. I've tried tweaking the settings in every possbile way I can imagine but I cannot make it work with this endpoint. The endpoint is this one, specifcally the PUT methods is what's throwing the CORS error: class StudentProfileModelViewSet(viewsets.ModelViewSet): queryset = StudentProfile.objects.all() serializer_class = StudentProfileSerializer filter_backends = ( … -
Django rendering context to a header template?
Here is my main.html, i am currently including the header and the footer {% include "store/header.html" %} {% block content %} {% endblock content %} {% include "store/footer.html" %}``` my header.html sample: this is where I am trying to render my cart <div class="shopping__cart"> <div class="shopping__cart__inner"> <div class="offsetmenu__close__btn"> <a href="#"><i class="zmdi zmdi-close"></i></a> </div> <div class="shp__cart__wrap"> {% for item in items %} <div class="shp__single__product"> <div class="shp__pro__thumb"> <a href="#"> <img src="{{item.product.imageURL}}" alt="product images"> </a> </div> <div class="shp__pro__details"> <h2><a href="product-details.html">{{item.product.title}}</a></h2> <span class="quantity">QTY: {{item.quantity}}</span> <span class="shp__price">${{item.product.price|floatformat:2}}</span> </div> <div class="remove__btn"> <a href="#" title="Remove this item"><i class="zmdi zmdi-close"></i></a> </div> </div> {% endfor %} </div> <ul class="shoping__total"> <li class="subtotal">Subtotal:</li> <li class="total__price">${{order.get_cart_total|floatformat:2}}</li> </ul> <ul class="shopping__btn"> <li><a href="cart.html">View Cart</a></li> <li class="shp__checkout"><a href="checkout.html">Checkout</a></li> </ul> </div> </div> I'm trying to render the items to my cart. here is my view: def header(request): category = None categories = Category.objects.all() products = Product.objects.all() if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems, 'categories':categories, 'products':products, 'category': category} return render(request, 'store/header.html', context) but I'm not sure how to render it since it's just a header. perhaps I should approach it differently in views. -
Django MFA query
I have a button within my application which is visible to authenticated users (not general public). That button is used to download data to excel. I want to apply extra authentication on that button so that my superuser gets notification before download. I thought of implementing Django MFA so that that authentication code will go to my superuser. But I am stuck at a logic as to how to tie my MFA to this specific button click as oppose to general site authentication. Can you please guide? -
Django - [Errno 13] Permission denied - Win10
I am currently trying to install and set-up Django. I am using windows 10 and python 3.9. When i run pip install django I get the following error: ERROR: Could not install packages due to an EnvironmentError: [Errno13] Permission denied: 'c:\\python39\\Scripts\\django-admin.py'. From reading other questions, adding --user to the command works. However, the command django-admin is still not recognised. Any ideas on how to fix the error? -
inline forms validation errors not in template
I have this model: class dateEvent(models.Model): link = models.URLField(null=True, blank=True) link_description = models.CharField(max_length=30, null=True, blank=True) event = models.ForeignKey('Event', on_delete=models.CASCADE) class Event(models.Model): title = models.CharField(max_length=200) [...] views.py: def event_edit_view(request, id): event = get_object_or_404(Event, id=id) form_event = EventForm(request.POST or None), instance=event) DateEventFormSet = inlineformset_factory(Event, dateEvent, extra=5, can_delete=True, fields=('event', 'start_date_time', 'venue', 'link', 'link_description'), widgets={ 'venue': s2forms.Select2Widget(), 'link': forms.TextInput(attrs={'placeholder': 'http://'}), 'start_date_time': CalendarWidget(), 'description_link': forms.TextInput(attrs={'placeholder': 'Link description'}), }) form_date_event = DateEventFormSet(request.POST or None, instance=Event.objects.get(id=id), prefix="dateEvent", queryset=dateEvent.objects.filter(event__id=id)) if request.method == "POST": if form_event.is_valid() and request.POST['action'] == 'submit': if form_date_event.is_valid(): form_event.save() form_date_event.save() messages.success(request, 'Event updated successfully. See the <a href="/event-detail/' + str(id) + '">detail page</a>') return redirect('my-events') else: raise forms.ValidationError(form_date_event.errors) elif form_event.is_valid() and form_date_event.is_valid() and request.POST['action'] == 'update': form_event.save() form_date_event.save() else: raise forms.ValidationError([form_event.errors, form_date_event.errors]) context = { 'event': event, 'id': event.id, 'form_event': form_event, 'form_date_event': form_date_event, } return render(request, "events/event-edit.html", context) And template: <tbody id='date_body'> {{ form_date_event.management_form }} {{form_date_event}} </tbody> When on the template I input illegal data (say, a non-URL in the URL field) Django throws an error via the ugly debug interface: ValidationError at myurl... ['Enter a valid URL.'] Request Method: POST Or a server error 500 if debug is turned off. Why am I not displaying the error on the template? -
migrations.exceptions.NodeNotFoundError When trying to migrate for production
I have a project which works perfectly locally, but I just deployed to Heroku and whenever i try to migrate it keeps saying django.db.migrations.exceptions.NodeNotFoundError: Migration blog.0002_auto_20210105_0051 dependencies reference nonexistent parent node ('blog', '0001_initial') So I have article if not all the articles concerning this error but not luck, I have deleted all migrations folder content (except init), I used makemigrations (locally) and try to migrate on heroku, Please note, im using a custom user model. SOmehome i know this is the cause of the error. Please help im desperate. -
How to get requested user in clean function in django forms?
Well i want to get requested user in clean function of django forms but i'm unable to do that. I'm trying to get that by simply saying self.request.user , it works in views but not working in forms.py, anybody have an idea how to get requested user in djnago forms ? forms.py class KycModelForm(forms.ModelForm): class Meta: model = KycModel fields = '__all__' def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(KycModelForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() user = User.objects.get(username=self.request.user) print(user) views.py class KycFormCreateView(CreateView): form_class = KycModelForm model = KycModel template_name = "accounts/kyc/new_kyc.html" def form_valid(self, form): user_kyc = form.save(commit=False) user_kyc.owner = self.request.user user_kyc.save() return super().form_valid(form) -
Django easy-thumbnails getting weird naming with duplicate extensions
I'm using easy-thumbnails, the original file is saved correctly but the thumbnails are being saved with a duplicate file extension: File.jpg File.jpg.100x100_q85.jpg I would like the thumbnails to be named like this: File.100x100_q85.jpg My model looks like this: def image_filename(instance, filename): folder = 'posts/image' _, ext = os.path.splitext(filename) new_name = str(instance.id) + ext return os.path.join(folder, new_name) class Post(models.Model): name = models.CharField(max_length=255, unique=True) image = ThumbnailerImageField(upload_to=image_filename, null=True, blank=True) Since im using Django Rest Framework I created a serializer following this post: Django easy-thumbnails serialize with Django Rest Framework class ThumbnailSerializer(serializers.ImageField): def __init__(self, alias, *args, **kwargs): super().__init__(*args, **kwargs) self.read_only = True self.alias = alias def to_representation(self, value): if not value: return None url = thumbnail_url(value, self.alias) request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(url) return url Does anyone know how I can get the correct naming on my thumbnails? Thanks! -
How can I add an auto increment field in a model based on total count of objects with same field value?
I'm new to the whole Django thing and a bit lost. Sorry if the title is a bit confusing I'll try to clear things out. So basically I have two models (Folder and Document). A Document can have a single Folder as one of its fields using a Foreign Key. Now I have another field in Document that needs to get the value of the total Document objects that share the same Folder and increase by one. I've tried things I read on the docs (aggregation, F() objects, overriding model's save() function) as well as some answers is read here but didn't manage to get it right so I'm posting to get some help. Below is my models.py file with the two models and some comments for better understanding. class Folder(models.Model): category = models.IntegerField() subCategory = models.IntegerField() name = models.CharField(max_length= 50) desc = models.TextField() class Document(models.Model): folder = models.ForeignKey(Folder, on_delete=models.CASCADE) date_created = models.DateField() date_added = models.DateTimeField() #The field below needs to sum all Document objects that share #the same folder value in the database + 1 and set it as its default value f_no = models.IntegerField(default=lambda: Document.objects.aggegate(Count('folder')) + 1) Thank you in advance, any leads or clues are most welcome -
Django - Can't Disable CORS
I'm trying to send a post request to an API using ajax, but when I do it, the error: Access to XMLHttpRequest at 'url' from origin 'http://192.168.0.9:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Searching, I've found this question, and tried literally all solutions in there, but got no success. So, I started thinking that this should be a problem from the API. But I made the request with Postman Desktop and got success. I'll leave my code here: settings.py ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ "corsheaders", "administrator", "authentication", "oticket", "clients", "crispy_forms", "django.contrib.postgres", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False Of course there are more settings, but there's no need for it. views.py [...] response = render(request, "payment/finish.html", context) response[ACCESS_CONTROL_ALLOW_ORIGIN] = ( "*" if (settings.CORS_ORIGIN_ALLOW_ALL and not settings.CORS_ALLOW_CREDENTIALS) else origin ) return response view.js $.ajax({ type: "post", url: sessionUrl, crossDomain: true, dataType: "xml", headers: { "Access-Control-Allow-Origin": "*", }, complete: (data, status) => { sessionId = $(data.responseXML).find("id").text(); }, }); -
Django 1.10 ./manage.py shell imports different than virtual env imports
Not quite sure how to word this better, however let me provide an example. I am trying to work with a library called django_nested_admin and am getting an inconsistent error. I am currently using Django 1.10 installed via pip. After reading the django-nested-admin release log, I've decided to use a compatible version of the library (3.0.21). pip install Django==1.10 pip install django-nested-admin==3.0.21 When I navigate in my browser to my admin panel, I receive the follow error: ImportError: no module named admin. A template debug traceback gives me further clues: from django.contrib.contenttypes.admin import GenericInlineModelAdmin /env/lib/python2.7/site-packages/nested_admin/nested.py Immediately, I begin to think that the version of Django I am using does not support the attribute access that is being used for import in the venv filesystem. I decide to verify this hypothesis by using the Django shell. ./manage.py shell from django.contrib.contenttypes.admin import * To my astonishment, everything imports just fine. What exactly is going on here? -
In Wagtail v2 API, how do I filter by a foreign key's string (provided by the __str__ method)
So I have a blog type of website where I'm trying to use the API to get a list of articles filtered by their topic. Here is the relevant portion of my ArticleDetailPage() class with the API field: class ArticleDetailPage(Page): """Article detail page.""" ... topic = models.ForeignKey('articles.ArticleTopic', null=True, blank=True, on_delete=models.SET_NULL) ... api_fields = [ ... APIField('topic', serializer=serializers.StringRelatedField(many=False)), ... ] And here's my ArticleTopic() class: @register_snippet class ArticleTopic(models.Model): """ Article topics that resides in Snippets. """ name = models.CharField(max_length=100) slug = AutoSlugField( populate_from='name', editable=True, max_length=100, verbose_name='slug', allow_unicode=True, help_text='A slug to identify articles by this topic.' ) panels = [ FieldPanel('name'), FieldPanel('slug') ] class Meta: verbose_name = 'Article Topic' verbose_name_plural = 'Article Topics' ordering = ['name'] # Alphabetial ordering def __str__(self): return self.name So far so good, when I take a look at the API list of posts, instead of showing the topic attribute as its ID and other data, it's represented as its string representation (i.e. a topic like space or comets). However, when I try to filter the API by appending: &topic=space to the HTML, I get an error saying: Field 'id' expected a number but got 'space'. Instead of using the StringRelatedField(many=False) serializer, I switched to APIField('topic', serializer=serializers.PrimaryKeyRelatedField(many=False, read_only=True)) … -
how do I use a button to display <div> in django template?
results.html {%if searched_user %} <a href= "{{ searched_user }}">{{searched_user}}</a> <button id=likedsongsbutton>View liked songs</button> <div> {% for each_searched_user in searched_user %} <br id="likedsongs"/>{% for liked_songs in each_searched_user.liked_songs.all %}{{liked_songs}} <br/> {% endfor %} {% endfor %} {% endif %} {% endblock %} </div> <script> document.querySelector("#likedsongsbutton").addEventListener(onclick, ) </script> views.py def results(request): if request.method == "GET": search_query = request.GET.get("username") searched_user = UserProfile.objects.filter( user__username__contains=search_query ) return render( request, "results.html", { "searched_user":searched_user }) My question is how do I make the <div> show only when the button is clicked? I do not know what function to pass in the EventListener -
Django Opening Hours With UTC Support/Timezone Issue
I have a Django application where users can setup stores. I recently added functionality to support opening hours following the advice on this thread - Business Opening hours in Django. My model is almost identical to the one given except each is attached to a "Location" object. Process goes like this - these times are put in in local time by the end user, most datetimes/times being used in my application are in UTC. Originally, I thought I could figure out the timezone of each location object, then whenever I compare something to these OpeningHours, I can just use the given time and the tz (on the associated Location object) to calculate the time in UTC and then it's just a regular datetime comparison. My problem is two fold: I'm not sure this is the best solution, it already feels like I'm overthinking it a bit. The bigger problem - I'm setting the timezones on the Location objects using pytz at the time of object creation. This is to say, it will not auto update for DST or anything like that as far as I know. I could calculate the exact timezone/DST at the time of comparison every time but … -
Django: Parse HTML (containing form) to dictionary
For testing the HTML which gets created by my Django application, I would like to extract the <form>...</form> of the response.content which I get the from the Django TestClient. response = client.get('/foo/') # response contains <form> ...</form> data = parse_form(response.content) data['my-input']='bar' response = client.post('/foo/', data) Imagine the form contains this: <form> <input type="text" name="my-input" value="initial"> </form> Then the result of parse_form(response.content) should be {'my-input': 'initial'} I read the testing responses docs but could not find something like this. -
Django Template not updating in the browser
I have the following HTMl code that have links to the following js svripts <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.bundle.min.js' %"></script> <script src="{% static 'js/lightbox.min.js' %"></script> <script src="{% static 'js/main.js' %"></script> The problem is the files are not loading and I am sure I have the linking done right.Since i linked other stuff (not js) the same way.Here is my settings.py static rout STATICFILES_DIRS = [ Path.joinpath(BASE_DIR, 'btre/static') ] and when inspecting its showing like this What should I Do ? P.s: I tried removing files caches from chrome and tried firefox and chrome still the same issue. -
Is there a safe way to safely delete a Model field in Django?
I'm making a blog application in Django, and I want to modify a field of the Post class: I want to change the meta_description field to just description. From: class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) meta_description = models.TextField(blank=True, null=True) body = models.TextField() def __str__(self): """ Show the title and the author in the admin Page """ return self.title + " by " + str(self.author) def get_absolute_url(self): return reverse("blog:article_page", kwargs={"pk": self.pk}) ⏎ To: class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) description = models.TextField(blank=True, null=True) body = models.TextField() def __str__(self): """ Show the title and the author in the admin Page """ return self.title + " by " + str(self.author) def get_absolute_url(self): return reverse("blog:article_page", kwargs={"pk": self.pk}) When I do that in the model: I have an error Making the migration: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, … -
devtools: Open response HTML in new tab
I an ajax/fetch request fails, my framework (django) does display a nice debug page, which contains a lot of useful information. In chrome devtools I can see a preview of this debug page. Is there a way to open the output of the POST request in a new tab? If I use right-button-click "open in new tab" then chrome does a GET. But the GET does not trigger the exception which I would like to debug. -
Django API didn't detect a field in my database
I'm doing the Django official tutorial, here are the models I wrote and migrated from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(name="date published") class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) and I used the command python manage.py shell to use the Django API and ran the following commands: >>> from polls.models import Question, Choice >>> from django.utils import timezone >>> q = Question(question_text="What's new?", pub_date=timezone.now()) and got this error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/mohammedi/.virtualenvs/mywebsite1/lib/python3.7/site-packages/django/db/models/base.py", line 501, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Question() got an unexpected keyword argument 'pub_date' what the hell is wrong with this -
Django: Unique ID's across tables
I was curious if there was a good solution to implement unique ID's between tables. class Voice(models.Model): id = .. <------| slug = ... | name = .... |-- No duplicate IDs | class Group(models.Model): | id = .. <------| slug = ... name = .... My hope is that when I get an ID in a view, selecting from one model will give me None but the other will always return the object (and vice versa). If there is a better approach feel free to share. Right now I am using the slug+id as query filters but would like to move away from that. -
(Django) Value set in session disappears after i render the request through the same view a second time
Here's what's happening: HTML Template "A" has a form that passes a variable with name="var1" to URL1. URL1 sends the request to VIEW1. VIEW1 then checks for and thereafter "gets" the "var1" variable successfully, and sets it in a session variable (request.session['variable'] = "var1" VIEW1 then renders the request to HTML Template "B", which has another form that passes a variable with name="var2" to URL1 again. URL1 sends the request to VIEW1 again. This time, "VAR1" is no longer available to "GET", but "VAR2" is. However, when i print the session variable (print(request.session['variable])), it no longer exists. My question is: Does passing a request back into the same VIEW a second time clear out any session variables you have set on the first pass? It certainly appears to be the case, but i can't figure out why. Before, I was using a global dictionary variable to store everything in, and it worked well, but it would expire if i didn't navigate quickly enough. Accordingly, i switched to storing my dictionary in the session. Thanks! -
Braintree Django Exception "can only concatenate str (not "tuple") to str"
I'm using Braintree Drop-in with my Django Project. It's working completely fine when I use it in development environment (manage.py runserver). But when I'm accessing the same on elastic beanstalk im getting the error "can only concatenate str (not "tuple") to str". The following is my code. extras.py from django.conf import settings import braintree gateway = braintree.BraintreeGateway( braintree.Configuration( braintree.Environment.Sandbox, merchant_id=settings.BT_MERCHANT_ID, public_key=settings.BT_PUBLIC_KEY, private_key=settings.BT_PRIVATE_KEY, ) ) def generate_client_token(): return gateway.client_token.generate() def transact(options): return gateway.transaction.sale(options) def find_transaction(id): return gateway.transaction.find(id) signals.py from django.db.models.signals import post_save from django.dispatch import receiver #from django.conf import settings from invoices.extras import gateway @receiver(post_save, sender=User) def create_phone(sender, instance, created, **kwargs): if created: gateway.customer.create({ "first_name": instance.first_name, "last_name": instance.last_name, "email": instance.email, "phone": instance.phone_number, "id": instance.id, }) views.py @login_required() def customer_invoice_view(request, ticket_id): ticket = get_object_or_404(Ticket, pk=ticket_id) customer = ticket.customer client_token = gateway.client_token.generate({"customer_id": str(customer.id)}) invoice = ticket.invoice if request.method == 'POST': result = transact({ 'amount': invoice.amount_payable, 'payment_method_nonce': request.POST['payment_method_nonce'], 'options': { "submit_for_settlement": True } }) if result.is_success or result.transaction: invoice.is_paid = True invoice.save() ticket = invoice.ticket ticket.status ='Payment Made' ticket.paid = True ticket.save() return redirect(customer_invoice_view, ticket_id=ticket.id) else: for x in result.errors.deep_errors: messages.info(request, x) return redirect(customer_invoice_view, ticket_id=ticket.id) context = { 'ticket' : ticket, 'invoice' : invoice, 'client_token' : client_token, } return render(request, 'invoice/ticket_invoice_view.html', context) ticket_invoice_view.html <div … -
Translation key-based internationalization with Django
Django's default i18n system uses the code language (for instance, English) as translation keys; translations into other languages must be written from that base language. For instance, in a Django template, you would write {% trans "Hello" %} and then translate "Hello" into "Bonjour" or "Hola" in the French or Spanish translation file. This has a major flaw: words that are spelled the same in English cannot be translated differently in other languages. For instance, if I use {% trans "Fire" %} in two places of my code, one of which meaning the thing that burns, and the other using a cannon, I would need "Feu" and "Tirer" respectively in French; but Django's i18n forces me to choose a single translation for "Fire". The translation keys pattern solves this: I use translation keys such as {% trans "campsite.fire" %} and {% trans "cannon.fire" %} in my code, that I translate as "Fire" in an English translation file and as "Feu" and "Tirer" respectively in the French file. Is this a supported use of Django's i18n system? How do I inject variables into such translations? -
Django: Return back from POST-redirect in Chrome without dublicate pages
I have a detail-page, with a button that submits a GET or a POST request (tried both). This request performs an action and redirects to the same detail-page (thus refreshing it). Everything seems to be fine in Firefox, but in Chrome when I press Back Button, I get back on the same page again (so redirecting to the same page creates dublicates of this page in browser history). Can I somehow change this behaviour and remove those dublicates in Chrome also? -
Jquery for followers not triggering
I want to add the following functionality to a site but need Jquery to change the following to unfollow and vice-versa. Everything seems fine but it's not working. (All the links to jquery work perfectly and load) Jquery for the functionality $('a.follow').click(function(e){ e.preventDefault(); $.post('{% url "user_follow" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if(data['status'] == 'ok' ){var previous_action == $('a.follow').data('action'); console.log(previous_action); // toggle data_action $('a.follow').data('action', previous_action == 'follow' ? 'unfollow' : 'follow'); // toggle link text $('a.follow').text(previous_action =='follow' ? 'Unfollow' : 'Follow'); // update followers var previous_followers = parseInt($('span.count .total').text()); $('span.count .total').text(previous_action == 'follow' ? previous_followers + 1 : previous_followers - 1); } } ) }); HTML {% with total_followers=user.followers.count %} <span class="count"> <span class="total">{{ total_followers }}</span> follower{{ total_followers|pluralize }} </span> <a href="" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow" class="follow btn"> {% if request.user not in user.followers.all %} Follow {% else %} Unfollow {% endif %} </a> {% endwith %} view for on jquery request @login_required def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create( user_from=request.user, user_to=user ) else: Contact.objects.filter(user_from=request.user, user_to=user).delete() return JsonResponse({'status': 'ok'}) except User.DoesNotExist: return JsonResponse({'status': 'error'}) return JsonResponse({'status': 'error'}) …