Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF token missing or incorrect (Django)
My form is created like so <form class="k-form" id="k_form" novalidate="novalidate">{% csrf_token %} and closed later in the html. This is my AJAX post: $('#submit').on("click",function(e){ var ready_to_submit = true; if(ready_to_submit){ e.preventDefault(); var local_data = new Object(); local_data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val(); console.log(local_data.csrfmiddlewaretoken); var json_data = JSON.stringify(local_data); console.log(json_data); $.ajax({ type:'POST', url:'/create_new_group/create_group/', data:json_data , success:function(data){ if(data.status == 1){ //success! console.log('Success!') } else if(data.status == 2){ //failed console.log('Failed!') } } }); } }); This returns Forbidden (CSRF token missing or incorrect.): /create_new_group/create_group/ on my Django server. What am I doing wrong? -
How to inject an attribute or an object into a view in Django Rest Framework?
I am kinda new to Django Rest Framework. I have a views.py that looks something like this: class MyAPIView(APIView): """ My API """ def get(self, request, path): """ Handles GET calls """ def post(self, request, path): """ Handles POST calls """ Now, I would like to inject an instance of some other class that does some task that it's supposed to into my view. Something like this: class MyAPIView(APIView): """ My API """ _some_util_instance = None # How to inject this? def __init__(self, util_instance): self._some_util_instance = util_instance # Is this the right way? def get(self, request, path): """ Handles GET calls """ def post(self, request, path): """ Handles POST calls """ What is the best way to inject such an instance into my views class? I could not find much about this in the documentation. I am familiar with using DI and IoC Containers. However, I am not sure how Django Rest Framework handles all of that. -
How to check either I have a new database entry and show in notification bar with alert
I am getting data in django of a ajax from database like $.ajax({ url: '/activity/', type: 'GET', data:{}, success: function(data) { // alert(data); var div1 = document.getElementById('activity'); div=data; div1.appendChild(div); }); And this ajax is set to be on a run on page refresh , but now I want to check if user have new message and on page. So without refresh want to show message . How can I achieve this thing. d -
Django rest framework serializer foreign key
so i have the following models in my models.py : class Coordonnees(models.Model): latitude = models.CharField(max_length=20) longitude = models.CharField(max_length=20) def __str__(self): return self.latitude+','+self.longitude class Ecole(models.Model): nomEcole = models.CharField(max_length=100) numTel = models.CharField(max_length=100) coordonnee = models.ForeignKey(Coordonnees, on_delete=models.CASCADE) def __str__(self): return self.nomEcole and in my serializers.py : class CoordonneesSerializer(serializers.ModelSerializer): class Meta: model = Coordonnees #our fields fields = ('id','latitude','longitude') class EcoleSerializer(serializers.ModelSerializer): class Meta: model = Ecole #our fields fields = ('id','nomEcole','numTel','coordonnee') well the problem is that when i check the json file of my "Ecole" i get the following output [{"id":1,"nomEcole":"draoui","numTel":"28747484","coordonnee":1}] so the question is : instead of having 1 in "coordonnee" i want to show the latitude and the longitude -
How to raise an error in template by form.error.as_text?
I cant understand how to show error in template without redirecting on error page. My task is to check existence of email in database and if its doesnt exist raise an error in form. Im using Django 2.1 and Python 3.7 What i have: django/auth/views.py class PasswordResetView(PasswordContextMixin, FormView): email_template_name = 'registration/password_reset_email.html' extra_email_context = None form_class = PasswordResetForm from_email = None html_email_template_name = None subject_template_name = 'registration/password_reset_subject.txt' success_url = reverse_lazy('password_reset_done') template_name = 'registration/password_reset_for.html' title = _('Password reset') token_generator = default_token_generator @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def form_valid(self, form): opts = { 'use_https': self.request.is_secure(), 'token_generator': self.token_generator, 'from_email': self.from_email, 'email_template_name': self.email_template_name, 'subject_template_name': self.subject_template_name, 'request': self.request, 'html_email_template_name': self.html_email_template_name, 'extra_email_context': self.extra_email_context, } email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): form.save(**opts) return super().form_valid(form) else: raise forms.ValidationError('Email is not in database') return email its standart django class and im just trying to customize it a little bit. Its works but redirects user on error page. And here is a form of password reset class PasswordResetForm(forms.Form): email = forms.EmailField(label=_("Email"), max_length=254) def check_email(self, email): email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): return email else: return forms.ValidationError('Email does not exist') Ive tryed to add check method in form but its not working( And here is code of my template: {% if … -
Working with Django and Django JSON log formatter
Installed the below using pip https://pypi.org/project/django-log-formatter-json/ In my code i put import json_log_formatter however I am getting the error ModuleNotFoundError: No module named 'json_log_formatter' When I run pip install django-log-formatter-json I get Requirement already satisfied: django-log-formatter-json in ... Can someone explane why its not finding the module? Am I not reading the documentation correctly? -
PythonAnywhere and Celery
I am running a Django app on PythonAnywhere. Unfortunately, Celery is not supported (on PythonAnywhere). I would like to use another library like Celery that allows me to execute some process asynchronously (and, icing on the cake, which would also support task scheduling). Does someone find a solution that it supported by PythonAnywhere? Could you recommand an easy friendly library just for executing some process asynchronously? Many thanks in advance for your help, Gilles -
How can I update a django BooleanField with a logical combination of other BooleanField's on the same model?
Consider this simple django model (backed by Postgres): class M(Model): a = BooleanField(default=False) b = BooleanField(default=False) c = BooleanField(default=False) class Meta: app_label = 'my_app' How can I use update to set the value of c to the logical AND of a and b? My first instinct was M.objects.update(c=F('a') and F('b')) but apparently the python is executed first (with the logical AND of the F functions simply returning the second method), because this yields the following SQL: UPDATE "my_app_m" SET "c" = "my_app_m"."b" I tried wrapping the expression in ExpressionWrapper, but this had no effect. I also tried using * instead of and (to multiply the F expressions), but this yielded an operation error on the sql side. I know I could do this in python by fetching the objects, manipulating them, and then saving. I'm guessing I could also probably do the update by casting to int then multiplying, then casting back. But I'm surprised the ORM doesn't simply handle this. Is there a step I'm missing, or a different standard way of accomplishing the same effect? Thanks for your time! -
Django save function error - int() argument must be a string or a number, not 'Template'
I am building a Django Application. when I try to save my model class, I am getting the following error message int() argument must be a string or a number, not 'Template' My Model seems to be like this. class Template(models.model): creation_time = models.DateTimeField(null=True,default=datetime.datetime.now) type = CharField(max_length=10,blank=True,null=True) def save(self,info=None): super(Content,self).save() if info: print 'info' My Function Call from my view seems to be like this one template = Template(creation_time=datetime.datetime.now(),type='html') template.save(info='Front Page') -
Modeling User to User connections in Django
I have an User object and a Connection object to manage connections between users. class User: username = models.CharField(max_length=100,) and class Connection: user = models.ForeignKey(User) friend = models.ManyToManyField('self', related_name="_friends", symmetrical=True) followers = models.ManyToManyField('self', related_name="_followers", symmetrical=False) following = models.ManyToManyField('self', related_name="_following", symmetrical=False) I'm not sure how to add friends in this modeling. user.connection_set._friends.add(target) -> does this work? Can someone help me with this. -
FileNotFoundError when "python manage.py carrot_daemon start" (Django-carrot & RabbitMQ)
After installing Erlang, RabbitMQ 3.7.8 and Django-carrot 1.2.1, when I try to execute "python manage.py carrot_daemon start" I get the following error: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pydev\pydevd.py", line 1664, in <module> main() File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pydev\pydevd.py", line 1658, in main globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pydev\pydevd.py", line 1068, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/PycharmProjects/text_mining/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\AppData\Local\Continuum\anaconda3\envs\text_mining\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\AppData\Local\Continuum\anaconda3\envs\text_mining\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\AppData\Local\Continuum\anaconda3\envs\text_mining\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\AppData\Local\Continuum\anaconda3\envs\text_mining\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\AppData\Local\Continuum\anaconda3\envs\text_mining\lib\site-packages\carrot\management\commands\carrot_daemon.py", line 152, in handle self.start(**options) File "C:\Users\AppData\Local\Continuum\anaconda3\envs\text_mining\lib\site-packages\carrot\management\commands\carrot_daemon.py", line 128, in start proc = subprocess.Popen(options, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) File "C:\Users\AppData\Local\Continuum\anaconda3\envs\text_mining\lib\subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "C:\Users\AppData\Local\Continuum\anaconda3\envs\text_mining\lib\subprocess.py", line 997, in _execute_child startupinfo) File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pydev\_pydev_bundle\pydev_monkey.py", line 445, in new_CreateProcess return getattr(_subprocess, original_name)(app_name, patch_arg_str_win(cmd_line), *args) FileNotFoundError: [WinError 2] The system cannot find the file specified I am also using Python 3.6.5 and conda 4.5.11. Has somebody any idea why this could happen? Thanks a lot in advance. -
Trying to send data in the body of a Axios GET to use in Django backend, but print of request.body is empty
According the Axios, this should be possible: https://github.com/axios/axios/issues/462#issuecomment-252075124 I have the following and pos_title does have a value. export function getQuery(pos_code, id) { if (id === 94) { var strArray = pos_code.split(' - '); pos_code = strArray[0]; var pos_title = strArray[1]; } return function(dispatch) { axios.get( `${URL}/api/survey/${(id)}/results/${(pos_code)}/`, { headers: { 'Content-Type': 'application/json', 'Authorization': 'JWT ' + sessionStorage.getItem('token') }, data: { body: pos_title } } ) .then(response => { dispatch({ type: QUERY, payload: response.data }) }) .catch(error => { console.log(error); }) } } In the corresponding views.py, the print(body_data) is empty: class GetQueryDataAPIView(APIView): permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): data = {'id': request.user.id} if kwargs: data['survey_id'] = kwargs.get('survey_id') data['pos_code'] = kwargs.get('pos_code') if data['survey_id'] == 94: body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) print(body_data) serializer = GetQueryDataSerializer(data=data) if serializer.is_valid(raise_exception=True): return Response(serializer.data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) -
Django set bookmark for url querystring
I'm querying through some filters (django-filters) a list of Book objects, what I want to do is save my research (aka my url with the GET params), creating a Bookmark object for the user. models.py class Bookmark(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=20) url = models.URLField(max_length=200) forms.py class BookmarkForm(BootstrapForm, forms.ModelForm): class Meta: model = Bookmark fields = ['nome', 'url'] widgets = { 'url': forms.HiddenInput() } To do so I'm extending a CreateView and trying to pass current url to the initial valued of bookmark.url. class AddBookmarkView(PermissionRequiredMixin, LoginRequiredMixin, CreateView): permission_required = 'core.add_bookmark' template_name = 'core/bookmark_form.html' model = Bookmark form_class = BookmarkForm def get_initial(self): initial = super().get_initial() initial['url'] = request.GET.urlencode() return initial def get_success_url(self): return reverse('elenco_libri') def form_valid(self, form): bookmark = form.save() bookmark.user = self.request.user bookmark.save() return HttpResponseRedirect(self.get_success_url()) This doesn't get anywhere because I don't have the GET request in get_initial() function. Where could I store the url? I thought about the get() function but I don't know how. Can anyone help? Thanks in advance. -
Django: Success message not displayed
Don't see any SuccessMessage. Anyone can tell me why I don't get any success message once I successfully created the database entry? class TicketCreate(AdminPermissionRequiredMixin, SuccessMessageMixin, FormValidationMixin, BaseTicketView, TemplateView): template_name = 'tickets/admin/create.html' success_message = _("Ticket has been successfully created.") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['ticket_form'] = self.ticket_form context['tax_form'] = self.tax_form return context @cached_property def ticket_form(self): return TicketForm(data=self.request.POST or None, event=self.request.event) @cached_property def tax_form(self): return TicketTaxForm(prefix='tax', data=self.request.POST or None) @transaction.atomic def post(self, request, *args, **kwargs): if self.ticket_form.is_valid() and self.tax_form.is_valid(): tax_instance = self.tax_form.save(commit=False) tax_choice = self.tax_form.cleaned_data.get('tax_choice') new_tax = (tax_choice == TicketTaxChoice.NEW_TAX and tax_instance.name and tax_instance.percentage) # save the tax instance if new_tax: tax_instance.event = self.request.event tax_instance.save() # save the ticket instance ticket_instance = self.ticket_form.save(commit=False) ticket_instance.event = self.request.event if new_tax: ticket_instance.tax = tax_instance self.ticket_form.save() return redirect( 'tickets:admin:detail', self.request.organizer.slug, self.request.event.slug, ticket_instance.pk ) return super().get(request, *args, **kwargs) -
Django Tests use the production database when making queries on the static elements of the class, why does this happen?
I have two Databases, one for use with Django (app_db) and another read-only one that is not stained with Django (remote_db), I have my custom router defined (db_for_read, db_for_write, allow_relation) and selects the right one when used with an app (module) created to manipulate the data, inclusive in the tests. In addition, remote_db to their own migrations. Distributions Apps and Database: - app news_module with model class News, NewsCategoryClassifier, use app_db. - app categories_module with model class Category, use remote_db. My Setting: DATABASE_ROUTERS = ['src.core.router.MyCustomRouter'] DATABASES = { 'default': env.db('APP_DB'), 'remote_db': env.db('REMOTE_DB') } my test: class CategoriesClassifierTest(TestCase): def test_instance_have(self): Category.object.create(name='Sports') Category.object.create(name='Financials') cl = NewsCategoryClassifier() self.assertIsInstance(cl, NewsCategoryClassifier) self.assertEquals(['Sports', 'Financials'], cl.choices) This works as expected. class NewsCategoryClassifier: def __init__(self): self.choices = Categories.objects.all() But when I run the test that involves a query on a class attribute I get data from the production database. class NewsCategoryClassifier: choices = Categories.objects.all() I would like to get how I can test the data in NewsCategoryClassifier from test_remote_db. I don't know if by creating a custom TestRunner I can come up with my solution. -
django template tag html safe escape not working for bold
Hello there I´m trying to insert some bold style in a text and insert it throught django template tag variable. I tested and works with underline and , but for or doesn´t !! Example: in my database I have something saved like this : objattribute.text = some `<em>`text`</em>` some text `<b>`some text`</b>` some text and template tag {{ objattribute.text|safe }} Result I´m getting : some <em>text</em> some text some text some text Any ideias about it?? -
Sharing database between two projects
I currently have two different projects in my Heroku folder, their functionality is pretty different, but I need them to share the same database. Is it possible to share the same database between two different projects in Heroku? -
How use get_queryset in Django Admin for retrieve only objects created by AdminUser?
I have an app which 3 kind of users: RegularUsers: Users of the app. Can't login admin site. They are managed by AdminUsers. They are the final users of the app. AdminUsers: They can login admin site in order to manage their RegularUsers. They just can manage users created by themselves. SuperUser. The admin of the WebApp having all permissions. I have different Models too. The website is a webGallery. Above you have my MODELS.PY class MyUser(AbstractUser): descripcion = models.TextField(blank=True) telefono = PhoneNumberField() avatar = models.ImageField(verbose_name='Imagen de perfil', upload_to='img/avatars', default='img/placeholder-image.png') def __str(self): return self.username class RegularUser(MyUser): MyUser.is_staff = False MyUser.is_superuser = False class Meta: verbose_name = 'Usuario Regular' verbose_name_plural = 'Usuarios Regulares' class AdminUser(MyUser): usuarios = models.ManyToManyField(RegularUser, help_text="Selecciona los usuarios que administra", blank=True) class Meta: verbose_name = 'Administrador' verbose_name_plural = 'Administradores' class Album(models.Model): id_album = models.AutoField(primary_key=True) titulo = models.CharField(max_length=40, null=False) ... usuario = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) .... # admin = models.ForeignKey(Familiar, on_delete=models.CASCADE, related_name="Administrador") ??¿¿ evento = models.ForeignKey(Evento, on_delete=models.CASCADE, blank=True, null=True) class Multimedia(models.Model): titulo = models.CharField(max_length=80) album = models.ForeignKey(Album, on_delete=models.CASCADE) keyword = models.ManyToManyField('Keyword', help_text="Selecciona las palabras clave para etiquetar.") ...... class Imagen(Multimedia): titulo = models.CharField(max_length=100) image_width = models.PositiveSmallIntegerField(default=640) image_height = models.PositiveSmallIntegerField(default=480) fichero_imagen = models.ImageField(verbose_name='Archivo de imagen', upload_to='files/img', width_field='image_width', height_field='image_height') thumbnail = ImageSpecField(source='fichero_imagen', … -
Django REST framework: validate using request method
Is it possible to validate request method (POST, PUT, GET...) together with queryset in example below? def validate_title(self, value): qs = Place.objects.filter(title__iexact=value) if qs.exists(): raise serializers.ValidationError("Duplicated title") return value -
passing the correct urls.py pattern
I have a button which allows me to add a new botany record, I can click on a 'details' button and to gets the correct record by the botany_id. e.g: http://localhost:8000/botany/1/ http://localhost:8000/botany/2/ http://localhost:8000/botany/3/ In that view/html I have another button which adds a composition to a related table. It should resolve using http://localhost:8000/botany/1/addcomposition/3/ but it tries http://localhost:8000/botany/addcomposition/3/. This suggests there is an issue in the urls.py which looks like this, I suspect its missing a pattern to account for the botany_id url(r'^addcomposition/(?P<pk>\d+)/$', views.addcomposition, name='addcomposition'), For clarity I also include the html <a href="{% url 'addcomposition' pk=fraction.fraction_id %}" class="btn btn-primary" role="button">+ Composition +</a> -
Django Template and Bootstrap Tables
I have a django queryset that looks something like this Group Label Name A 1 Jack A 2 Ryan B 2 Alice C 1 Sam B 1 Mark ... Basically, what I am attempting to do in my html, is create 6 small tables (2 rows of 3 tables). However, I want the first table to be Group A sorted by Label #, the second to be Group B sorted by Label #, etc. I could bite the bullet and do 6 different django querysets, but this seems inefficient. My initial thought was to have some counter in the django template to keep track of whether or not to start a new row. However, I am not sure if there is a way to filter & sort in the django template instead of the view. Thanks for any help. -
Django: DeleteView + HttpResponseNotAllowed
I found this DeleteView. Anyone can tell me what return HttpResponseNotAllowed(['POST'])is for? Should I add it to my own DeleteView as well? class DiscountDelete(AdminPermissionRequiredMixin, DeleteView): model = Discount def get(self, *args, **kwargs): return HttpResponseNotAllowed(['POST']) -
How to connect React with Django REST?
I am running React JS with the Nginx server, and would like to connect with the Django REST API running with Gunicorn. When I call the page http://18.220.194.77/ gunicorn shows the GET with code 200, but the data is not updated, if I access http://18.220.194.77:8000/api/ I can see Django working, below settings: Nginx: server { listen 80 default_server; server_name 18.220.194.77; root /var/www/frontend/build; location /api { proxy_pass http://18.220.194.77:8000; # this is where you point it to the Django server } location / { try_files $uri $uri/ /index.html; # this is where you serve the React build } } React served by Django: import React, { Component } from 'react'; class App extends Component { state = { todos: [] }; async componentDidMount() { try { const res = await fetch('http://18.220.194.77:8000/api/'); const todos = await res.json(); this.setState({ todos }); } catch (e) { console.log(e); } } render() { return ( <div> {this.state.todos.map(item => ( <div key={item.id}> <h1>{item.title}</h1> <span>{item.description}</span> </div> ))} </div> ); } } export default App; -
Errno 99 Cannot assign requested address Request Method: POST Request
I get the following error when doing a user registration in django-rest-framework using the path /rest-auth/registration/ [Errno 99] Can not assign the requested address Request method: POST Request URL: http://104.42.33.211/rest-auth/registration/ Django version: 1.11.2 Python executable: /usr/local/bin/python The API service is run for port 80 of a Docker container hosted on a Linux server in Microsoft Azure -
Render ForeignKey field as a text field in form but keep foreign key behaviour
This question looks stupid ans simple, but I really can't figure it out. I have a model with a foreign key field to another model, lets say: class Parent: name = models.CharField() class Child: name = models.CharField() e_id = models.IntegerField() parent = models.ForeignKey(Parent) I render Child instances with defalt django forms, with no any additions. I use inlineformset_factory(Parent, Child, extra=1) if it is important. And the key moment: django renders parent(which is a foreign key) as a dropdown input. And I need to show parent's id in form as a simple text input and not a dropdown. But I want to keep all behaviour of foreign key and make django validate that a content of parent_id input is a valid and existing id of Patent model. I tried to create a ChildForm like this: class ChildForm(django.forms.ModelForm): class Meta: model = Child fields = ('name', 'e_id', 'parent') parent = CharField(label=_("Parent"), required=True) And use it like this: inlineformset_factory(Parent, Child, extra=1) And it rendered as a charfield like I want. But here is no validation and smart trasformations of id into instance anymore. If I write incorrect parent_id, I get "Cannot assign "u'21'": "Children.parent" must be a "Parent" instance." error. So I feel …