Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form not submitting - problem with form tag
The signup page of my app is exhibiting unexpected behaviour. I'm using the standard django auth. After editing the html a bit, the form stopped submitting altogether. As in nothing would happen when I clicked submit. Similar behaviour to this chap, and this one, and this question. I've fixed it. For some reason, I needed to add an additional opening form tag. I have no idea why. This is what the html looks like now: <form method="POST"> <form method="POST"> {% csrf_token %} {{ form.non_field_errors }} {% bootstrap_form form %} <input type="submit" class='btn btn-primary' value="Sign Up"/> </form> Without the additional form tag at the top, it doesn't work. Can anyone explain what's going on here? I also noticed that in Atom, when I only have the one opening tag, the editor highlights the tag in orange - meaning it's being treated as an attribute not a tag. When I have both opening tags, one still gets highlighted as an attribute. Like I said, it's working now but I would prefer to rectify this if anyone in the community can help. -
Django version 2.1.4 - Exception Type: NoReverseMatch
I am doing Django blog v2.1.4 getting below error. django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. NoReverseMatch at / Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Exception Location: C:\Users\khattab\Anaconda3\envs\myenv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 622 Python Executable: C:\Users\khattab\Anaconda3\envs\myenv\python.exe Python Version: 3.7.1 Python Path: ['C:\Users\khattab\Desktop\blog_project\mysite', 'C:\Users\khattab\Anaconda3\envs\myenv\python37.zip', 'C:\Users\khattab\Anaconda3\envs\myenv\DLLs', 'C:\Users\khattab\Anaconda3\envs\myenv\lib', 'C:\Users\khattab\Anaconda3\envs\myenv', 'C:\Users\khattab\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\khattab\Anaconda3\envs\myenv\lib\site-packages'] Server time: Thu, 10 Jan 2019 15:46:37 +0000 My URL path('accounts/login/', auth_views.LoginView.as_view()), Thank you -
How to add meta data in a csv using python?
I am trying to create a csv file to export user list. I want to add some meta data like the type of user, author and some other data that should not be displayed in excel sheet. Is it possible to add such meta datas in CSV. if possible can some one help me? -
Django annotate over a subquery
i'm struggling with an aggregation, what I'm trying to do is, to perform some sum over a subquery. Let's assume the following model: +------------------------+-----------+ | Column | Type | +------------------------+-----------+ | customer | fk | +------------------------+-----------+ | total | float | +------------------------+-----------+ | somefield | charfield | +------------------------+-----------+ | issued_on | date | +------------------------+-----------+ | validation_status_code | charfield | +------------------------+-----------+ the subquery is as follow: Invoice.objects.filter(customer_id=4).order_by('issued_on')[:48+1] This is only half of the invoices of a customer, the idea here is to obtain the aggregate over a period of time (this is the subquery). Suppose I want to get the Sum of total, the Sum of the total if the status is "error" and gruop by 'somefield', I've figured it out the SQL query (it's on mysql), I want to know if it's possible to do this via Django ORM. The query is the following: SELECT table1.somefield, SUM(table1.total) AS total_clean, SUM(CASE WHEN table1.validation_status_code = 'error' THEN table1.total ELSE NULL END) AS canceladas, (SUM(table1.total) - SUM(CASE WHEN table1.validation_status_code = 'error' THEN table1.total ELSE NULL END)) AS ventas FROM (SELECT invoice.id, invoice.customer_id, invoice.total, invoice.somefield, invoice.validation_status_code, invoice.issued_on, FROM invoice WHERE invoice.customer_id = 4 ORDER BY invoice.issued_on ASC LIMIT 49) AS table1 GROUP BY table1.somefield -
Django - ajax poll with results on the same page
I'm learning django and I need help with my app. In a page I have a poll: I want that after a user has voted, the poll form disappears and a div #ajaxresults appears with the updated votes for each option. I'm using an ajax call but I can't return the updated votes. If I call directly '/polls/4/results' I can see the right list but I can't include that block on the same page of the form. What am I missing? urls.py app_name = 'polls' urlpatterns = [ path('', views.index, name='list'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] view.py def results(request, question_id): question = get_object_or_404(Question, pk=question_id) #return render(request, 'polls/results.html', {'question': question}) return redirect(question.get_absolute_url()) @require_POST def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) selected_choice = question.choice_set.get(pk=request.POST['selectionId']) selected_choice.votes += 1 selected_choice.save() return render(request, 'polls/results.html', {'question': question}) detail template (extends base.html) <form id="quiz-module" action="#"> <input type="hidden" id="pollId" name="pollId" value="{{question.id}}"> {% csrf_token %} <fieldset> <h2>{{ question.question_text }}</h2> <ul> {% for choice in question.choice_set.all %} <li><input type="radio" name="opt" value="{{ choice.id }}" {% if forloop.first %}required {%endif%}/>{{ choice.choice_text }}</li> {% endfor %} </ul> </fieldset> </form> <section id="quiz-results"> <h3>Your vote</h3> <p id="ajaxresults"></p> <h3>All votes</h3> <dl> {%block updated_results %}{% endblock %} </dl> </section> template vote is … -
add placeholder in views.Login in Django
i use django.contrib.auth.views import Login but i want add css and placeholder to Login views i use python3 Urls : url(r'^login$' , LoginView.as_view(template_name='login.html'), name='Login' , kwargs={"authentication_form": LoginUser}), form : from django.contrib.auth.forms import AuthenticationForm from django.forms.widgets import PasswordInput, TextInput class LoginUser(AuthenticationForm): username = forms.CharField(widget=TextInput(attrs={'style':'font-size : 20px;color:white','placeholder': 'Username'})) password = forms.CharField(widget=PasswordInput(attrs={'placeholder':'Password' , 'style' : 'font-size : 20px;color:white'})) this code don't work i you can please help me -
Trying to post images from reactjs to django using DRF I get an empty queryset
Im trying to post an image from reactjs to my backend using Django Rest Framework but when i print request.data I get an empty querydict <QueryDict: {}>. This is how I post my image reactjs handleFormSubmission = () => { const {phoneNumber, avatar} = this.state; if(!phoneNumber && !avatar) console.log('something!!'); this.setState({ isLoading:false }) let data ={ phone_number:phoneNumber, avatar } let config = { headers:{ 'Content-Type': 'multipart/form-data', 'Accept': 'application/json' } } axios.put('/profile/change', this.state, config ).then(res=>{ this.setState({ isLoading:true }) }) } Then when console.log the image its converted to base64. I am also using multipart/form-data as part of my headers views.py def put(self, request): """ update user pf :param request: :return: """ current_user = Profile.objects.get(user=request.user.id) serializers = ProfileSerializers(current_user, request.data, partial=True) if serializers.is_valid(): serializers.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) I think that my backend basically has no problem because when i post images using postman the images are saved successfully -
Python 3 and Django 2 faster to load or copy object for view?
I am curious as to the most performant way to get large objects into views for Django 2 In views.py I need to load a large object into memory. I have this both pickled as well as a json file. The pickled version is only a marginal improvement at 95% the size of the json version. While I would like to do this once when the serve starts, and then have a view have access to this module level variable, one of my views needs to modify the object to do what it is suppose to do. So if I load it once as a module level variable, (here named persistent), we see that sequential calls use the updated variable -- as expected: views.py ... persistent = {'val': 0} # loaded from pickled / json file def test(request, val): old = persistent['val'] # required information from unmodified object persistent['val'] = val # some computation which is required to modify the object return JsonResponse({'old': old, 'new': val}) ... urls.py ... urlpatterns = [ ..., path('test/<val>/', views.test, name='test') ,... ] api calls localhost:8000/test/10 ---> {'old': 0, 'new': 10} localhost:8000/test/100 ---> {'old': '10', 'new': 100} this is of course expected. However, for my … -
Django Multiselectfield allows to add any value which is not in choice list from shell, How to prevent that?
DEPARTMENT_CHOICE = ( ('BCT','Department Of Electronics and Computer Engineering'), ('BEL','Deparment Of Electrical Engineering'), ('BCE','Deparment Of Civil Engineering'), ('SHE','Deparment Of Science and Humanities'), ('BME','Deparment Of Mechanical Engineering'), ) department = models.CharField (max_length =10 ,choices = DEPARTMENT_CHOICE,blank=True,verbose_name="Department") But if we add eg ZZZ in department, it will be added in database but I want to prevent that. How can I do it to prevent add items which are not in choice tuple? -
Forbidden (CSRF cookie not set) csrf_exempt
I'm returning with a 403 Forbidden (CSRF Cookie not set) error on a CBV with csrf_exempt being called on dispatch either via the csrf_exempt decorator or using CsrfExemptMixin from django-braces. Not quite sure why as other views using CsrfExemptMixin works fine class CaseDeletedView(CsrfExemptMixin, View): def post(self, request, *args, **kwargs): ... return HttpResponse(status=204) With decorator class CaseDeletedView(CsrfExemptMixin, View): def post(self, request, *args, **kwargs): ... return HttpResponse(status=204) @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) -
Django widget that depends on model
I am pretty new to django and have a question. I got a ModelForm using Widgets. Since I have a field called discount which I only want to be editable if the displayed model fullfills some requirements, I make it read-only using a widget entry: class Meta: widgets = {'discount': forms.TextInput(attrs={'readonly': True})} Now I want to make it possible to write to this field again, iff the Model (here called Order) has its field type set to integer value 0. I tried to do so in the html template but failed. So my next idea is to make the widget somehow dependent to the model it displays, so in kinda pseudocode: class Meta: widgets = {'discount': forms.TextInput(attrs={'readonly': currentModel.type == 0})} Is there a proper way to do something like this? Thanks in advance -
django emoji with mysql, charset settings
First: DATABASES = { 'default': { 'ENGINE': "django.db.backends.mysql", 'NAME': '<DB_name>', 'USER': '<user_name>', 'PASSWORD': '<password>', 'HOST': '<DB_host>', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8mb4', 'use_unicode': True, }, } } Second: DATABASES = { 'default': { 'ENGINE': "django.db.backends.mysql", 'NAME': '<DB_name>', 'USER': '<user_name>', 'PASSWORD': '<password>', 'HOST': '<DB_host>', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } I found a website that explain First one to use emoji on django application. But I also found that Second one is also working well through using emoji. Which one is correct or good enough for production django application? Which is considerable for production? My database: AWS RDS MySQL 5.7.19 -
Django template translation not working as expected
I am using django 2.1 , here is all the settings related to translation: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', _('English')), ('bn', _('Bengali')) ) LOCALE_PATH = ( os.path.join(BASE_DIR, 'locale') ) TIME_ZONE = 'Asia/Dhaka' USE_I18N = True USE_L10N = True USE_TZ = False Template tag that I want to translate: {% load i18n %} <div class="widget widget-about"> <h4 class="widget-title">{% trans "About Us" %}</h4> </div I run both ./manage.py makemessages --all ./manage.py compilemessages commands , also added translation in .po file after makemessages command: # locale/bn/LC_MESSAGES/django.po #: templates/partials/footer.html:8 msgid "About Us" msgstr "আমাদের সম্পর্কে" When I changed the language code from en to bn, template string still rendering the default english "About Us". Here are all the codes that I am using for changing language: <div class="header-dropdown"> {% get_current_language as LANGUAGE_CODE %} {% if LANGUAGE_CODE == 'en' %} <a href="#"><img src="{% static 'image/flag/en.png' %}" alt="flag">ENGLISH</a> {% else %} <a href="#"><img src="{% static 'image/flag/bn.png' %}" alt="flag">বাংলা</a> {% endif %} <div class="header-menu"> <ul> <li><a href="{% url 'change_language' %}?lan=en"><img src="{% static 'image/flag/en.png' %}" alt="USA Flag">ENGLISH</a></li> <li><a href="{% url 'change_language' %}?lan=bn"><img src="{% static 'image/flag/bn.png' %}" alt="Bangladesh Flag">বাংলা</a></li> </ul> </div><!-- End .header-menu … -
How to sort django queryset with two fields while creating duplicates
I have a Deadline model which have two fields, start_date and end_date. I want to sort the queryset with both the fields but have a copy of deadline for each date I tried creating annotated common fields and ordering through that. class Deadline(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField dl_start = deadline_queryset.annotate(date=F('start_date')) dl_end = deadlien_queryset.annotate(date=F('end_date')) dl_all = dl_start.union(dl_end).order_by('date') I need a timeline of events. If I've 2 deadline objects: D1(12-dec, 24-jan) and D2(15-dec, 21-jan), I need a list of deadlines like D1, D2, D2, D1 -
Using date filter in Django template raises TemplateSyntaxError
I'm trying to format a datetime using Django built-in date filter. When I use {{ thread.added_at|date }}, it works as expected and the date printed is similar to "Dec. 21, 2018". But since I also want to format the date, I use the filter like this: <span>{{ thread.added_at|date:"d m y" }}</span> When I try to load the page, I get a TemplateSyntaxError: TemplateSyntaxError at /questions/ expected token 'end of print statement', got ':' The website runs on Django 1.8.19. In Django 1.8 documentation, date filter appears to be able to be used like that. What is the problem in my template? -
Django ORM Issue With Column Not Existing
I am attempting to debug an employee's work and I am kind of hitting a wall. For context: we have a models package called objects_client, in this package we have a model called UnitApplication. There is not a visible column in the UnitApplication model. And there are no references elsewhere in code that we have actually written that calls for the column objects_client_unitapplication.visible. All I am trying to do is gather the object using the usual Django ORM, in my mind this should not provide me with any errors, I am just grabbing a row from a database based on an id. Also a note: the variable db_connection is correct and it references a client database, as this is where I am grabbing the data from. What is going on? I get the same error when I attempt to gather all objects using UnitApplication.objects.using(db_connection).all() try: print('before gathering property_unit_application_obj') # THE ERROR HAPPENS HERE --------- # column objects_client_unitapplication.visible does not exist property_unit_applications_obj = UnitApplication.objects.using(db_connection).get(property_id=int(property_id_param)) print('prop_unit_app_obj: {}'.format(property_unit_applications_obj)) except Exception as ex: print('Exception: {}'.format(ex)) Here is the full traceback without the exception clause: Traceback (most recent call last): File "C:\Users\mhosk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column objects_client_unitapplication.visible does not exist … -
How is the zip function used in Python3?--A movie recommendation system project
Syntax error displayed when I try to run. The zip function should have been misused, but I don't know how to fix it. This is a movie recommendation system project in machine learning Web applications. I try the following method movies, moviesindxs = zip(*literal_eval(data.get("movies"))) This is part of the code # since def rate_movie(request): data = request.GET rate = data.get("vote") print(request.user.is_authenticated) movies, moviesindxs = zip(*literal_eval(data.get("movies"))) movie = data.get("movie") movieindx = int(data.get("movieindx")) # save movie rate userprofile = None if request.user.is_superuser: return render(request,'books_recsys_app/superusersignin.html') #return render_to_response( #'books_recsys_app/superusersignin.html', request) elif request.user.is_authenticated: userprofile = UserProfile.objects.get(user=request.user) else: return render(request,'books_recsys_app/pleasesignin.html') #return render_to_response( #'books_recsys_app/pleasesignin.html', request) This is the content of the error report SyntaxError at /rate_movie/ invalid syntax (<unknown>, line 1) Request Method: GET Request URL: http://127.0.0.1:8000/rate_movie/?vote=4&movies=%3Czip%20object%20at%200x112a0ce08%3E&movie=Some%20Kind%20of%20Wonderful%20(1987)&movieindx=602 Django Version: 2.1.4 Exception Type: SyntaxError Exception Value: invalid syntax (<unknown>, line 1) Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py in parse, line 35 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Python Version: 3.6.0 Python Path: ['/Users/changxuan/PycharmProjects/reconmendationSystem/ReconSystem', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages'] Server time: 星期四, 10 一月 2019 11:04:41 +0000 -
Replace a char in django template before final rendering
I want to make all of my asterisks (*) in a template in red color in a Django Template. (E.g. in form labels that * symbol points the field is required. But when putting * in label of a form field it is rendered as black color as usual. How can I accomplish this by for example registering a filter or tag? Note that I use some libraries (e.g. bootstrap4 form) and the page is full of {{ }} tags. BUT I want to find&replace all ;black *' with 'red *' in final rendered html page. -
Rewrite Django Checkbox widget to use record fields
I have a model with a field that is has ManyToMany relationship with another model. When displaying this relationship in a form for selection I'm color coding the checkbox based on field contents within the related table. So my checkboxes are generated as follows: {% for addon in addons %} <div class="col-xl-12"> <div class="{% if addon.css_class == 'featured' %}checkbox-terms {% endif %}{{ addon.css_class }} extra"> <input type="checkbox" id="{{ addon.css_class }}" name="addons" value="{{ addon.id }}" id="id_addons_{{ forloop.counter0 }}"> <label for="{{ addon.css_class }}"><span class="{% if addon.css_class == 'featured' %}checkbox-terms{% else %}{{ addon.css_class }}{% endif %}-icon"></span> <div class="{{ addon.css_class }}-title">{{ addon.name }}</div> <div class="{{ addon.css_class }}-description">{{ addon.description }}</div> </label> </div> </div> {% endfor %} I would like to turn this into a widget subclass of forms.CheckboxSelectMultiple. So I've subclassed using: class AddOnCheckboxSelectMultiple(forms.CheckboxSelectMultiple): template_name = 'django/forms/widgets/addon_checkbox_select.html' option_template_name = 'django/forms/widgets/addon_checkbox_option.html' But in order for this to work I need to access field values within each record when rendering the checkboxes through the widget. Is this possible, and if so, how do I do it? Thanks -
unexpected keyword argument thrown when passing values to task using *args
I am new to celery, and have run into the following: I have a task that is part of a django application, and it takes in the following: def run_tests_report(correlation_id, workers, *args) The value(s) that gets passed to *args is a string defined in our django data model as test_name_or_mark = models.CharField as part of a function in base.py run_tests_report() gets called by tasks.append( task.si(correlation_id=request.correlation_id, workers=request.workers, test_name_or_mark=request.test_name_or_mark) when I attempt to use this task with a our request the following error is thrown: TypeError: run_tests_report() got an unexpected keyword argument 'test_name_or_mark' I have been able to assert that the value of test_name_or_mark is a string that contains the value I expect. I have also been able to validate that this works when I make a direct call to the task: with workers: In [4]: run_tests_report('alwaysbetesting9_no_workers_multiple_marks', '2', 'smoke', 'fix', 'regression') MORE THAN ONE smoke or fix or regression workers multiple marks without workers: In [2]: run_tests_report('alwaysbetesting8_no_workers_multiple_marks', 0, 'smoke', 'fix', 'regression') MORE THAN ONE smoke or fix or regression no workers multiple marks I am confused as to why this is not working now that I am calling the task with django. Do I need to update the data model? -
Django: How do I perform a CreateView redirect properly?
To perform a redirect I do return redirect([...]). However, that only works, if I additionally do def get_success_url(self):. The url in it actually doesn't matter, as it is using the redirect of my def form_valid(self, form):. Do you know how to avoid the get_success_url? I also tested to just move the return from form_valid to get_success_url. But then I receive an error that return is missing. class AdminRewardCreate(AdminPermissionRequiredMixin, SuccessMessageMixin, FormValidationMixin, AdminBaseRewardView, CreateView): form_class = RewardForm template_name = 'rewards/admin/create.html' success_message = _("Reward has been successfully created.") def form_valid(self, form): instance = form.save(commit=False) instance.event = self.request.event # when the super method is called the instance # is saved because it's a model form super().form_valid(form) return redirect( 'rewards:admin:index', self.request.organizer.slug, self.request.event.slug ) def get_success_url(self): return reverse( 'rewards:admin:index', kwargs={ 'organizer': self.request.organizer.slug, 'event': self.request.event.slug, } ) -
Model field doesn't get updated on first save
I've got this UpdateView I'm using to update my channels: class ChannelUpdate(UpdateView, ProgramContextMixin): model = ChannelCategory form_class = ChannelForm template_name = 'app/templates/channel/form.html' def dispatch(self, request, *args, **kwargs): return super(ChannelUpdate, self).dispatch(request, *args, **kwargs) def get_success_url(self): return reverse('channel_index', args=[self.get_program_id()]) def get_context_data(self, **kwargs): context = super(ChannelUpdate, self).get_context_data(**kwargs) context.update({ 'is_new': False, }) return context def form_valid(self, form): channel = Channel.objects.get(id=self.kwargs['pk']) channel_codes = ChannelCodes.objects.filter(channel_id=channel.pk) if 'is_channel_enabled' in form.changed_data: for channel_code in channel_codes: channel_code.is_active = channel.is_channel_enabled channel_code.save() return super(ChannelUpdate, self).form_valid(form) So when I edit a Channel, I have a checkbox, which changes my bool value for my model field is_channel_enabled to either True or False. If I do so, I trigger my if-statement in the def form_valid method which then loops through all my channel_codes and sets their bool field is_active to the same value as the bool field is_channel_enabled from my Channel. But my problem right now is: Lets say I uncheck the box and after I save my form, the bool still is True even though I've unchecked the box and it should be False, but if I then edit my Channel again and check the box, the bool changes to False, so that every time I check the box, the exact opposite happens: … -
how to upload image from the form using django with jqery and ajax
upload image beside other data when user submit the form. the form was adding the data correctly before i add the image field now it doesn't add any data to the database i added picture field to the model added picture element in the form added the input tag in the html send the data through AJAX to the view getting the data from ajax request and added to the view function models.py picture = models.ImageField(upload_to = 'pictures/%d/%m/%Y/',null=True, blank=True) form.py from django import forms from blog.models import te2chira, destination class SaveTe2chira(forms.ModelForm): class Meta: model = te2chira fields = ['title', 'description','picture' ] html <form method="POST" class="form-style-9" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <li> <input type="file" id="img" name="img"/> </li> <li> <input type="submit" class="field-style field-full align-none" id="save" value="save" /> <script type="text/javascript"> $(function(){ $('#save').on('click',function(e){ e.preventDefault() // year=$('#year').val() // date=$('#date').val() num=$('#num').val() title=$('#title').val() text=$('#text').val() issent=0 img = $('#img').prop('files')[0] $.ajax({ url:'/create/te2chira', method:'POST', data: { n:num, ti:title, te:text, s:0, img:img }, headers:{ 'X-CSRFToken':'{{csrf_token}}' } }).done(function(msg) { document.location = "/creativePageSend.html" alert('success') }).fail(function(err){ alert('no success') }) }) }) </script> </li> </ul> </form> views.py def post_new(request): title = request.POST['ti'] description = request.POST['te'] num=request.POST['n'] issent=request.POST['s'] img = request.FILES['img'] n=te2chira.objects.create(title=title,te2chira_date=timezone.datetime.now(),description=description,num=num,is_sent=issent,picture = img) print(timezone.datetime.now()) n.save() id=n.te2chira_id request.session['idTe2chira']=id return render(request,'./creativePageSend.html',{'id':id}) upload the image with … -
Django fixture for extrernal translation app. How can I load the data?
I am using django-hvad to translate some fields in my models. For example: from django.db import models from hvad.models import TranslatableModel, TranslatedFields class Article(TranslatableModel): name = models.CharField(max_length=255, unique=True) translations = TranslatedFields( description=models.CharField(max_length=255), ) At the same time I would like to use django fixtures and load some sample data into the model with python manage.py loaddata articles.json: articles.json [ { "model": "posts.Article", "pk": 1, "fields": { "name": "First article" } }, I know that django-hvad creates additional tables for translations. In this case there will be posts_article_translation table. I cannot populate this table with following json, because obviously there is not Article_translation model: { "model": "posts.Article_translation", "pk": 1, "fields": { "description": "Good article", "master_id": 1 } }, What can be a better solution to populate translations fields? -
How to do jsonrpc with django?
For doing REST, we have DRF. Is there a similar framework for doing JsonRPC? The alternatives that I have found are not very inspiring. Is there a recommended approach to JsonRPC in Django? Is it possible to use DRF with JsonRPC instead of REST?