Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to select multiple data in django raw_id pop-up and add them inline
Nice to meet you, everyone. I'm creating a talent booking system on django admin. The models.py is as follows. I'm new to django. I'm sorry if there is an agenda that has already been resolved. [master models.py] class Talent(models.Model): def __str__(self): return self.name class Meta: verbose_name = _('Talent') verbose_name_plural = _('1-3. Talent') ordering = ['id'] name = models.CharField(_('Talent Name'), max_length=128, blank=False, null=False) class Contract(models.Model): def __str__(self): return str(self.contract_start_d) + '-' + str(self.contract_end_d) class Meta: verbose_name = _('Contract') verbose_name_plural = _('2-0. Contract') ordering = ['id'] model = models.ForeignKey(Talent, on_delete=models.CASCADE, verbose_name='Talent', blank=False, null=False) [event models.py] class Ticket(models.Model): def __str__(self): return str(self.id) class Meta: verbose_name = _('Ticket') verbose_name_plural = _('3-0. Ticket') ordering = ['id'] name = models.CharField(_('name'), max_length=128, blank=True, null=True) class TicketContract(models.Model): def __str__(self): return self.contract.model.name class Meta: verbose_name = _('TicketContract') verbose_name_plural = _('3-5.TicketContract') ordering = ['id'] ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, verbose_name='Ticket') contract = models.ForeignKey(Contract, on_delete=models.CASCADE, verbose_name='Contract', null=False) [admin.py] class TicketContractInline(admin.TabularInline): model = TicketContract fieldsets = ( (_('Talent'), {'fields': ( 'contract', )}), ) search_fields = ('contract',) raw_id_fields = ('contract',) ordering = ('id',) extra = 1 class TicketAdmin(admin.ModelAdmin): fieldsets = ( (_('Ticket'), {'fields': ( 'name' )}), ) list_display = ( 'id', ) inlines = (TicketContractInline,) I have set models.py and admin.py like this, but … -
Django not updating pie chart on ajax success event?
I want to change the values in the pie chart whenever onchange event in a tag.But whenever onchange happens the piechart just disappears. Here how my ajax code goes: $( "#date" ).change(function() { $form=$('#form'); var datastring = $form.serialize(); var date=$('#month_date').val(); $.ajax({ url : '{% url 'here:pie_charts' %}', type : 'GET', data : { 'date': date, }, dataType:'html', success : function(data) { data: datastring, $('#form').html(data); }, }); return false; }); Django view returns like this: return HttpResponse(render_to_string(form_template, context, request)) My pie chart : I is not updating on ajax success event instead it disappears. var arr = []; // append multiple values to the array //some_value is the value from context . arr.push({{some_value}}, {{some_value}}); var config = { type: "pie", data: { datasets: [ { data:arr, backgroundColor: [""], label: "People", }, ], labels: ["some_labels'], }, options: { responsive: true, maintainAspectRatio: true, }, }; window.onload = function () { var ctx = document.getElementById("pie-chart").getContext("2d"); window.myPie = new Chart(ctx, config); }; </script> -
Django How to make the condition correct on an HTML page - search bar
I try to do a search engine if the word in my DB thah I created then display the word on the HTML page and if not then nothing.. I did it right in VIEW but I can not apply it on the HTML page I searched the internet and did not find an answer I'm sure I fall for something stupid. This is the view def Search_word(request): search = request.POST.get("search") #Grab the search item return render(request,"search_page.html", {"search":search}) this is the html: {%for i in Word.English_word%} {%if search in Word.English_word%} {{search}} {%endif%} {%endfor%} and the urls: path("Search_page",views.Search_word ,name="Search-page"), The problem is that even if the word is valid it does not show me anything .. -
Facing issue in custom manager of django
I am trying to create a custom manager to retrieve all posts with the published status. New to managers!! Thank you in advance <3. models.py class PublishedManager(models.Model): def get_query_set(self): return super(PublishedManager, self).get_query_set().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique_for_date='publish') author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) views.py def post_list(request): posts = Post.published.all() print(posts) return render(request, 'post/list.html', {'posts': posts}) def post_detail(request): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'post/detail.html', {'post': post}) Error 'PublishedManager' object has no attribute 'all' (views.py, line 6, in post_list) -
Is there any way i can make vs code to format and properly handle django templates?
I tried to use prettier, but it's not handling the Django templates codes properly, is there any alternative to this extension? -
not all my column in 'render_table' are orderable, what can i do?
I use render_table from django_tables2 to write a table that contain 4 headers (Title, Delete, View, and Export), the title is orderable, but the other one are not, the problem is that render_table use class orderable in all elements, how can I edit that ? in HTML I call the function like this : <!-- table --> <div class="mt-3"> {% render_table table %} </div> and this is my table.py script : ENTRIES_TEMPLATE = "<a href='{% url 'form-entries' form=record.pk %}' class='btn btn-outline-info btn-small'><i class='fas fa-file'></i></a>" DELETE_TEMPLATE = "<a href='{% url 'dashboard-topic-delete' pk=record.pk %}' class='btn btn-outline-danger btn-small'><i class='fas fa-trash'></i></a>" VIEW_TEMPLATE = "<a href='{{record.pk}}' class='btn btn-outline-info btn-small'><i class='fas fa-edit'></i></a>" EXPORT_TEMPLATE = """ <div class="btn-group"> <button type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Export </button> <div class="dropdown-menu"> <a class="dropdown-item" href="{{record.get_export_url}}?type=CSV"><i class='fas fa-file-csv'></i> csv</a> <a class="dropdown-item" href="{{record.get_export_url}}?type=XLS"><i class='fas fa-file-excel'></i> xlsx</a> </div> </div> """ # # id = tables.LinkColumn('forms:form-update',kwargs={"pk":A("pk")}) responses = tables.TemplateColumn(ENTRIES_TEMPLATE) delete = tables.TemplateColumn(DELETE_TEMPLATE) view = tables.TemplateColumn(VIEW_TEMPLATE) export = tables.TemplateColumn(EXPORT_TEMPLATE) class Meta: model = Topic template_name = "django_tables2/bootstrap.html" fields = ("Title","view","responses","delete","export") (Only ENTRIES_TEMPLATE need to be Orderable) -
python manage.py loaddata moderation_categories.json having giving me error or FFMPEG not installed
hello i am facing an issue of FFMPEG not istalled i am working on local and on production both working on local python manage.py loaddata moderation_categories.json works fine while on production running the same commands i am having the issue ERRORS: <class 'video_encoding.backends.ffmpeg.FFmpegBackend'>: (video_conversion.E001) ffmpeg binary not found: HINT: Please install ffmpeg. <class 'video_encoding.backends.ffmpeg.FFmpegBackend'>: (video_conversion.E001) ffmpeg binary not found: HINT: Please install ffmpeg. while on running the command docker-compose -f docker-compose-full.yml run --rm webserver python3 manage.py loaddata moderation_categories.json i am having the error traceback: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/serializers/json.py", line 68, in Deserializer objects = json.loads(stream_or_string) File "/usr/local/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/usr/local/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/modeltranslation/management/commands/loaddata.py", line 61, in … -
Django - Is it possible to use other value than pk for modelform field?
I have a model form and I post the form via AJAX. One of the fields is a manytomany field and I render it as checkboxes. By default django uses PKs of the models in the queryset that is passed in. Is there a way to use another field of the model as value instead of PK values. (I have PK as integer - for a reason. I also have a UUID field which is not PK. I want to use that one for values.) -
context processor in django
To display product categories on the site in several views, I get information about the categories from the database. (Do this in at least 8 views) I use context processor to prevent duplicate codes. Is this method better and more efficient? In fact, by creating a context processor, I only get the category information from the database once and do not write it in any view anymore. Is there a better option? -
Sending emails from my django website, via sendgrid
I want to send account confirmation emails to all the users who sign up on my website, so it has to be an HTML email with the activation link. This is how i am trying to do it: import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail def my_view(request): current_site = get_current_site(request) mail_subject = 'Welcome To IIITU Alumni Network' to_email = email ctx = { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), } message = Mail( to_emails = to_email, from_email = '<my email address>', subject = mail_subject, #I made this html page specifically for sending confirmation email #I am not sure if this is the correct way to do it html_content = render_to_string('network/email.html', ctx) ) try: #I have this key as an environment variable sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) #Now this is where the problem is response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) return HttpResponse("A confirmation Email has been sent to your Institute email address. Please Confirm Your email to complete your registration") except Exception as e: print(e.message) return HttpResponse("The Server seems too busy!! Sorry for the inconvenience. Please try again later, or contact administrator if this problem persists.") When this particular view is rendered, it throws the following error message: 'UnauthorizedError' object … -
How to navigate to different routes in VueJs rendered in DJango Templates
I have a separate environment for front end which is written in ViewJS. I am trying to merge it with DJango default url. I have build it and able to render the screen in DJango server url by collectstatic and calling it in Django template. But it is loading all the screens of VueJs at once like below image. Even home screen is displaying without logging in which was working fine in isolated environment. Now even the api call is not triggering. How do I resolve this? main.js import Vue from 'vue' import App from './App.vue' import Router from 'vue-router' import axios from 'axios' import VueAxios from 'vue-axios' import Home from '@/components/Home' import Login from '@/components/Login' Vue.use(VueAxios, axios) Vue.use(Router) Vue.config.productionTip = false const routes = [ { path: '/Home', name: 'Home', component: Home }, { path: '/', name: 'Login', component: Login } ] const router = new Router({ routes, mode: 'history', base: '/test' }) new Vue({ router, render: h => h(App), }).$mount('#app') vue.config.js const path = require('path'); module.exports = { publicPath: '/static/src/vue/dist/', // Should be STATIC_URL + path/to/build outputDir: path.resolve(__dirname, '../static/src/vue/dist/'), // Output to a directory in STATICFILES_DIRS filenameHashing: false, // Django will hash file names, not webpack runtimeCompiler: true, … -
I don't know why Price can't be saved in DB
I am a student learning Django and JavaScript. I am trying to save quantity and price in my code, but no matter how I try, it is not saved. Quantity is stored, price2 is not. Please help me.. I feel like my head is going to explode in a week. Where is the cause? Where do I need to fix it? Where the hell is the problem? I want to display the price in javascript and store the corresponding value as price2. If you could help me, I would really, really, really, really appreciate it. html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"></div> </div> <script> $().ready(function() { $("#optionSelect").change(function() { … -
Django ModuleNotFoundError: No module named 'views'
In my Django Project market I created an app called main. In main I created urls.py main/urls.py: from django.urls import path import views url_patterns = [ path('home/', views.homepage, name='home'), ] main/views.py: from django.shortcuts import render, HttpResponse # Create your views here. def homepage(request): return HttpResponse("<h1> Hello World </h1>" ) market/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')) ] But when I try to run: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Python38\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Python38\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Python38\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Python38\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Python38\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Python38\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python38\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python38\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python38\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Python38\lib\importlib\__init__.py", … -
Ajax in django doesnt work, no error and nothing happens
I wrote a django app that has articles and im trying to add a like functionality, I added the code in the bottom and nothing happens. No error just nothing in the database or the html code changes. Any idea what is the problem? The relevent part of the html/javascript code: <head> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> </head> <button id='like-button' color = 'black'> Like </button> <script type="text/javascript"> $('#like-button').click(function(){ var article_id = '{{ article.id }}'; var user_id = '{{ user.id }}'; var like_dislike = True; $.ajax( { type:"GET", url: "like-article-commm", data:{ article_id: article_id, user_id: user_id, like_dislike: like_dislike }, success: function( data ) { $('#like-button').css('color', 'blue'); } }) }); </script> The like-article-comm View: def Like_Article_View(request): if request.method == 'GET': article_id = int(request.GET['article_id']) likedarticle = Article.objects.get(id = article_id) user_liked_id = int(request.GET['user_id']) userliked = User.objects.get(id = user_liked_id) like_dislike_0 = request.GET['like_dislike'] like_object_list = Like_Article.objects.filter(article_liked = likedarticle, user_liked = userliked) if like_object_list.count() > 0: existing_like = like_object_list.filter() if existing_like.like_dislike == like_dislike_0: return HttpResponse('success') existing_like.like_dislike = like_dislike_0 existing_like.save() like_new_object= Like_Article(article_liked=likedarticle, user_liked=userliked, like_dislike=like_dislike_0) like_new_object.save() return HttpResponse('success') else: return HttpResponse("unsuccesful") urls.py file: from django.urls import path from . import views from .views import ArticleListView, ArticleDetailView, ArticleCreateView, ArticleUpdateView, ArticleDeleteView urlpatterns = [ path('', ArticleListView.as_view(), name="home-comm"), path('article/<int:pk>/', ArticleDetailView.as_view(), name="article-comm"), path('like_article/', views.Like_Article_View, name='like-article-commm'), … -
I want to save the pdf file from local server to online
I want to save the pdf file generated by weasyprint from the local server to online while my website is running on a local server in Django.. please help -
Celery auto reload Django
I am following ChillarAnand's example on how to reload Celery on change in my Django project, however it doesn't seem to close the previous Celery worker. On reload Celery raises the following error: [2021-08-11 10:42:30,216: WARNING/MainProcess] /Users/someuser/Documents/dev/backoffice/venv/lib/python3.8/site-packages/kombu/pidbox.py:72: UserWarning: A node named celery@someusers-iMac.local is already using this process mailbox! Maybe you forgot to shutdown the other node or did not do so properly? Or if you meant to start multiple nodes on the same host please make sure you give each node a unique node name! warnings.warn(W_PIDBOX_IN_USE.format(node=self)) My code in Django's management > commands celery_worker.py as follows: import shlex import subprocess from django.core.management.base import BaseCommand from django.utils import autoreload class Command(BaseCommand): def handle(self, *args, **options): autoreload.run_with_reloader(self._restart_celery) @classmethod def _restart_celery(cls): cls.run('pkill -f "celery worker"') cls.run('celery -A backoffice worker -B -l DEBUG') @staticmethod def run(cmd): subprocess.call(shlex.split(cmd)) I have tried the following 'Kill' command, which works fine when used in terminal, but when used in the commands script OSX raise an error - "kill: illegal process id: $(ps" kill -9 $(ps aux | grep celery | grep -v grep | awk '{print $2}' | tr '\n' ' ') > /dev/null 2>&1kill -9 $(ps aux | grep celery | grep -v grep | awk '{print … -
Django class based view, save in another model after CreateView
I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would like to once I have saved my data in my Loan_assetCreateView(generic.CreateView) that is set the value in Asset.is_loaned to True. How can I do that? My models.py: class Asset(models.Model): # Relationships room = models.ForeignKey("asset_app.Room", on_delete=models.SET_NULL, blank=True, null=True) model_hardware = models.ForeignKey("asset_app.Model_hardware", on_delete=models.SET_NULL, blank=True, null=True) # Fields name = models.CharField(max_length=30) serial = models.CharField(max_length=30, unique=True, blank=True, null=True, default=None) mac_address = models.CharField(max_length=30, null=True, blank=True) purchased_date = models.DateField(null=True, blank=True) may_be_loaned = models.BooleanField(default=False, blank=True, null=True) is_loaned = models.BooleanField(default=False, blank=True, null=True) missing = models.BooleanField(default=False, blank=True, null=True) notes = HTMLField(default="") ip = models.CharField(max_length=90, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Loan_asset(models.Model): # Relationships asset = models.ForeignKey("asset_app.Asset", on_delete=models.SET_NULL, blank=True, null=True) loaner_type = models.ForeignKey("asset_app.Loaner_type", on_delete=models.SET_NULL, blank=True, null=True) location = models.ForeignKey("asset_app.Locations", on_delete=models.SET_NULL, blank=True, null=True) # Fields loaner_name = models.CharField(max_length=60) loaner_address = models.TextField(max_length=100, null=True, blank=True) loaner_telephone_number = models.CharField(max_length=30) loaner_email = models.EmailField() loaner_quicklink = models.URLField(null=True, blank=True) loan_date = models.DateField() return_date = models.DateField() notes = HTMLField(default="") returned = models.BooleanField(default=False, blank=True, null=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class … -
how to extract only day from timestamp in Django
I want to get a specific date like "8" out of (2021-8-3) but it's showing like this image how can I extract the specific date? usertime = User.objects.filter(groups__name = 'patient').values('date_joined').annotate(date_only=Cast('date_joined', DateField())) -
Whats the best websocket solution without too much overhead?
I'm fairly new to real-time databases with WebSockets so I'm facing probably the most important question when it comes to starting, which database and approach within the backend are the fastest and most reliable to set up and scale. I'm having a Django Backend with MongoDB (Djongo) and React in my frontend. Hosted on a google cloud linux VM. I'm currently comparing Websocket solutions for creating Components like text-editors that can be used collaboratively like google docs for example. To keep everything tidy I would have loved to go with an approach within Django but it seems so much overhead to work with Websockets in Django compared to other solutions. What I've gathered so far by trying all of these. Django: Has a lot over overhead as you need, Channels, Redis and therefore all the setup for it to use real-time WebSocket communication. Channels itself seemed kind of ok to set up but with an addition of Redis, the ASGI configs, and then making sure it works with my Mongo DB backend seems very complex to me in comparison to other systems with a lot of potential problems in the way. I coded everything and got most of it working … -
How can I save messages from my facebook webhook to a textfile using python and django. The code is attached below
if 'message' in message: # Print the message to the terminal print(message) # Assuming the sender only sends text. Non-text messages like stickers, audio, pictures # are sent as attachments and must be handled accordingly. print(message['message']['text']) respondinging = input("enter response") post_facebook_message(message['sender']['id'], respondinging) return HttpResponse() -
Integrating a javascript pipeline to Django
I am trying this tutorial to integrate a modern JavaScript pipeline into a Django application. Javascript code is supposed to write a "Hello webpack" into the page, but it does not. Since I already have an existing django project/app, I am writing on top of it. index-bundle.js is created with the content at the end of this post. django manage.py collect-static collects it. https://mysite/static/index-bundle.js loads the js file. There is no console error message. I see <script src="/static/index-bundle.js"></script> in the html generated, so everything should be fine. What is wrong here? index-bundle.js (comments deleted): /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./assets/index.js": /***/ (() => { eval("function component() {\r\n const element = document.createElement('div');\r\n element.innerHTML = 'Hello webpack';\r\n return element;\r\n}\r\n\r\ndocument.body.appendChild(component());\n\n//# sourceURL=webpack://project_dir/./assets/index.js?"); /***/ }) /******/ }); /******/ var __webpack_exports__ = {}; /******/ __webpack_modules__["./assets/index.js"](); /******/ /******/ })() ; -
how to set new unicode codepoints to my language in django settings to support
i'm trying to add my language (kurdish) which is not existing in languages list in django , but i dont know where to find unicode codepoints from django.conf import global_settings import django.conf.locale from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'ku' #ROSETTA_LANGUAGES = ( # ('en',_('english')), # ('ar',_('arabic')), # ('ku',_('kurdish')) #) LANGUAGES = ( ('en',_('english')), ('ar',_('arabic')), ('ku',_('kurdish')) ) ROSETTA_WSGI_AUTO_RELOAD = True EXTRA_LANG_INFO = { 'ku': { 'bidi': True, # right-to-left 'code': 'ku', 'name': 'Kurdish', 'name_local': u'\u0626\u06C7\u064A\u063A\u06C7\u0631 \u062A\u0649\u0644\u0649', # i have to change it to my language code LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = global_settings.LANGUAGES_BIDI + ["ku","kurdish"] LOCALE_PATHS = ( os.path.join(BASE_DIR,'locale/'), ) 'name_local': u'\u0626\u06C7\u064A\u063A\u06C7\u0631 \u062A\u0649\u0644\u0649' used for another language(ughyry) and now it raise this error invalid token in plural form: EXPRESSION note kurdish use arabic character with a very little different -
How to pass variables in template to an ajax script? Django
I have a like button and I want ajax to send a get request with some variables I passed through the view, how do I do that? Every explanation online does this by adding a data-catid attribute however the information im passing is slightly sensetive and I would much rather it wouldn't be in the html code. my button: <button id='like-button' color = 'black', class='likebutton'> Like </button> ajax code <script type="text/javascript"> $('#likebutton').click(function(){ var article_id; var user_id; $.ajax( { type:"GET", url: "like", data:{ article_id: article_id, user_id: user_id }, success: function( data ) { $( '#like'+ id ).addClass('btn btn-success btn-lg'); } }) }); </script> How do I pass the user id and article id? They are both in the template. If there is anything I forgot to add, code or explanation please notify me -
make form look like an excel table
I made this form: the form: AgregatsFormset = inlineformset_factory(Canva, Bilan, fields=('agregat', 'SCF', 'mois1', 'mois2', 'ecart1', 'evolution1', 'finmois1', 'finmois2', 'ecart2', 'evolution2'), can_delete=False, max_num=5) html: {% for bilan_form in form.forms %} {% for fidden_field in bilan_form.hidden_fields %} {{ hidden_field.errors }} {% endfor %} <table> {{ bilan_form.as_table }} </table> {% endfor %} the form look like this how do i make it look like an excel table ? : like this -
Implement Django REST TokenAuthentication for Multiple User Model
I need to implement TokenAuthentication using Custom user model Consumer & Merchant (The default User model still exists and is used for admin login). I've been looking on official DRF documentation and days looking on google, but I can't find any detailed reference about how to achieve this, all of the references I found using default User or extended User models. class Consumer(models.Model): consumer_id = models.AutoField(primary_key=True) token = models.UUIDField(default=uuid.uuid4) email = models.CharField(max_length=100, unique=True, null=True) password = models.CharField(max_length=500, default=uuid.uuid4) class Merchant(models.Model): merchant_id = models.AutoField(primary_key=True) token = models.UUIDField(default=uuid.uuid4) email = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=100) password = models.CharField(max_length=500, default=uuid.uuid4) Settings.py INSTALLED_APPS = [ ... 'rest_framework', ... REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser' ] } I'm also using @api_view decorator with function-based views: @api_view(['POST']) @renderer_classes([JSONRenderer]) def inbound_product(request, pid): product = MerchantProduct.objects.get(product_id=pid)