Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Limit django rest framework api according to payment plans
I have some dinamically added features performed by an admin user, which i will associate with certain endpoints. What would be a good approach to this problem? The problem is how can i do this association? -
Can't send email in management command run by cron
I have a strange problem with a Django management command I am running via cron. I've a production server set up to use Mailgun. I've a management command that simply sends an email: from django.core.mail import send_mail class Command(BaseCommand): help = 'Send email' def handle(self, *args, **options): send_mail('Test email', 'Test content', 'noreply@example.com', ['me@example.com',], fail_silently=False) This script works perfectly if I run it via the command line (I'm using virtualenvwrapper): > workon myapp > python manage.py do_command or directly: > /home/user/.venvs/project/bin/python /home/user/project/manage.py do_command But when I set it up with cron (crontab -e): */1 * * * * /home/user/.venvs/project/bin/python /home/user/project/manage.py do_command The script runs (without error), but the email isn't sent. What could be going on? -
How does Django maintain consistency between its logical constraints, and its database?
Lets say I have a model defined as follows: class Foo(models.Model): bar = models.CharField(max_length=10) Using this model, I create a Foo object in my database using the following code: Foo.objects.create(bar="0123456789") Should work well enough. However, after creating the object, I reduce the max_length property to 5. So now, technically, the object I created has a consistency error. How does Django manage a situation like this? I assume they don't raise any errors until that object is saved again. If so, is that the optimal solution for a situation like this, and are there are any other approaches? -
Uncorrect redirecting
I've a redirecting problem for a typology of post on my blog. On my blog there are two categories: GIS, Sustainable Mobility. When I click on a post of Sustainable Mobility I can see the content of the post and the link address is correctly showed as 'blog/sustainable-mobility/post-title'. But when I click on a post of GIS, I see the "Page not found (404)" error and the link addess is 'blog/sustainable-mobility/post-title' instead of 'blog/gis/post-title'. Here there is the code. What I've wrong? NB: I don't have this problem if change the category of the post -
Django templated email 'dict' object has no attribute 'get_host'
I'm trying to send a verification email after a user registers an account using django_templated_email. This is the error I get after the user is created: AttributeError 'dict' object has no attribute 'get_host' So Django is trying to call get_host() and is unable to? So it's an error because it can't retrieve my host name? Can someone point out what am I missing here? class UserListView(generics.ListCreateAPIView): serializer_class = UserSerializer def perform_create(self, serializer): user = serializer.save() context = {'user': user} to = user.email email.ActivationEmail(context).send(to) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'password', 'email') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password') user = super(UserSerializer, self).create(validated_data) user.set_password(password) user.save() return user class ActivationEmail(BaseEmailMessage): template_name = 'email/activation.html' def get_context_data(self): context = super(ActivationEmail, self).get_context_data() user = context.get('user') context['uid'] = utils.encode_uid(user.pk) context['token'] = default_token_generator.make_token(user) context['url'] = '#/users/verify/{uid}/{token}'.format(**context) return context Traceback: Environment: Request Method: POST Request URL: http://localhost:8000/users/ Django Version: 2.0 Python Version: 3.6.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'simple_history', 'corsheaders', 'templated_mail', 'accounts',] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'simple_history.middleware.HistoryRequestMiddleware'] Traceback: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. … -
Checkbox Select Multiple (more than one option) for related models using ModelForm
I need to write simple app where user can select multiple choices (more than one option) I create someting like that: models.py from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) choice_limit = models.PositiveSmallIntegerField(default=1) add_date = models.DateTimeField('add date', auto_now_add=True) change_date = models.DateTimeField('change date', auto_now=True) question_enable = models.BooleanField('is published', default=False) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return "%s %s %s" % (self.question, self.choice_text, self.votes) views.py def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: #selected_choice = question.choice_set.get(pk=request.POST['choice']) some_var = request.POST.getlist('choice') selected_2 = Choice.objects.filter(question__in=some_var) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: for x in selected_2: x.votes += 1 x.save() return HttpResponseRedirect("/") template <form action="{% url 'vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend>Please select one of the following</legend> {% for choice in question.choice_set.all %} <input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <input type="submit" value="Vote"> I don't know it is good Django way? It is any posiple to write this app with ModelForm and generic views? I try … -
ERROR: Couldn't connect to Docker daemon at http+docker://localhost - is it running?
Tengo un problema cuando intento construir o compilar un entorno con Docker Compose en una instancia de AWS. He seguido los pasos de la documentación oficial para la instalación de docker-compose y teoricamente me instala sin errores. El problema esta cuando ejecuto el comando docker-compose build dentro de mi entorno Dockerizado. Tutorial de instalación 1 Código de error: ERROR: Couldn't connect to Docker daemon at http+docker://localhost - is it running? If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable. Imagen del error 2 He intentado con varias soluciones como: Agradecería si alguien puede ayudarme con alguna solución para mi inconveniente. -
Redux-Saga pass headers to axios.post call
I am having some difficulties with redux-saga. I have the following saga: createPostSaga: function* createPostSaga(action) { const token = yield select(selectToken); const headerParams = { Authorization: `JWT ${token}` }; console.log(token, headerParams); try { yield call(axios.post, "/posts/", action.payload, headerParams); yield call(getPosts()); } catch (error) { console.log(error); } } As you can see I am selecting my token, and putting into an object with key Authorization and value JWT ${token}, my API is still responding with 401 unauthorized, but it must be an issue with this call because I can replicate this call in Postman and it goes through fine: Does anyone see what I did wrong? -
Complex Django 2fa login methode incomplete
im currently working on a 2fa login function but if i enter the right token (decrypted) im not able to login :( I guess i lost the path here, can smb maybe have a look where i have to place the "return redirect(reverse('home'))" in case the token is right: def login_2fa(request): if request.method == 'POST': form = Login2faForm(request.POST, request.POST) if form.is_valid(): if request.POST['token'] == request.session['token']: user = User.objects.get(id=request.session['userID']) customlogin(request, user) return redirect(reverse('home')) else: encrypted = request.session['encrypted_token'] return render(request, 'registration/login_2fa.html', {'form': Login2faForm(), 'token': str(encrypted)}) else: encrypted = request.session['encrypted_token'] return render(request, 'registration/login_2fa.html', {'form': Login2faForm(), 'token': str(encrypted)}) else: token = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(42)) request.session['token'] = token user = User.objects.get(id=request.session['userID']) if 'encrypted_token' not in request.session : encryption_key = PGPKey.from_blob(user.pubpgp.rstrip("\r\n"))[0] encrypted = encryption_key.encrypt(PGPMessage.new(token), cipher=SymmetricKeyAlgorithm.CAST5) request.session['encrypted_token'] = encrypted else: encrypted = request.session['encrypted_token'] return render(request, 'registration/login_2fa.html', {'form': Login2faForm(), 'token': str(encrypted)}) Thanks in Advance -
Restricting permissions depending on group Django admin
I'm trying to change displayed fields on Django admin depending on the group the logged user belongs to. I've read something about overriding the get_fieldsets method but I haven't been able to make it work. This is the admin class I've defined: class CartelAdmin(admin.ModelAdmin): model = Cartel campos_alumnos = ('titulo', 'descripcion', 'autores', 'imagen', 'bloque', 'pregunta_asociada') def get_fieldsets(self, request, obj=None): if request.user.groups.filter(name='Alumnos').exists(): return self.campos_alumnos else: return super(CartelAdmin, self).get_fieldsets(request, obj=obj) This is the model itself: class Cartel(models.Model): titulo = models.CharField( max_length = 200, verbose_name = "Título del cartel") descripcion = models.TextField( verbose_name = "Descripción del cartel") autores = models.CharField( max_length = 200, verbose_name = "Nombre de los autores") imagen = models.ImageField( upload_to = 'imagenes', verbose_name = 'Imagen del cartel') fecha_aparicion = models.DateTimeField( verbose_name = 'Fecha en la que se empezará a mostrar el cartel') fecha_fin_reto = models.DateTimeField( verbose_name = 'Fecha límite para responder al reto') fecha_fin_curso = models.DateTimeField( verbose_name = 'Fecha en la que el cartel pasará a \'Ediciones anteriores\' y el reto a \'Banco de preguntas\'') bloque = models.ForeignKey( to = Bloque, null = True, on_delete = models.SET_NULL, verbose_name = 'Bloque al que pertenece el cartel') pregunta_asociada = models.OneToOneField( Pregunta, null=True, blank=True, on_delete=models.SET_NULL, unique=True, verbose_name='Reto asociado al cartel') -
Convert Imageurl to String in Django?
Convert this:"http://127.0.0.1:8000/Food/image/141676.jpg" (IT IS A LINK) TO This http://127.0.0.1:8000/Food/image/141676.jpg -
How to implement microservices in django and make them communicate with one another
I'am new with the framework django and I want to realize a project using microservices. I have been looking for detailed documentation about but til now I've found nothing very helpful and which explains the procedure step by step. Different microservices must be able to communicate with one another. I've already tried django microservices explain by Pypi but no good results. So if someoene can help me with the procedure or templates for microservices I'll be grateful. PS. My OS is windows7 64bits and I can't use docker on it. Thank you for your help... -
Python Create Geographic Heat Map
I'm working on a project using Python(3.6) and Django(2.1) in which I need to create a Geographic Heat Map like the picture below: I'm retrieving the data directly from Database using Django queries, which is in the form of default QuerySet of Django. I have googled a lot but couldn't find any solution to generate this kind of Map. -
Need every time client id and client secret for access token in django?
I am following the below link to learn about oauth authentication https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html Do i need to give client id and client secret code to access those api? if yes, how can i access from front end? please help to findout. thanks in advance -
run django microservice with while loop?
I have a django app running as a microservice. Which has a function which does the following: Checks for filenames matching *.json in a directory. for each file: processes json data and converts to xml. saves xml in target directory. Exits function. Is there any reason i shouldn't do this to keep it running on a cycle: While True: main_function() The previous developer was using threading which i think is making things far too complicated given there's no need to optimise performance. -
Django add middleware that show form on each request
I am new to this django middleware I worked with django middleware by adding login page on each selected requested page. But now I want to show a html form as user request any page. So what should I use process_view or process_response to call the template (i.e html form). -
Django Serilizer: Getting an ordered dictionary in embeded serializer
I'm one serializer inside another to show information from one model, and selected fields from another in the same response. This looks like this: class SimpleRouteClientConstraintSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField() def get_name(self, obj): default_constraint = RouteDefaultConstraint.objects.get(pk=obj.route_default_constraint_id) return default_constraint.name class Meta: model = RouteClientConstraint fields = ('name', 'value') class RouteSerializer(serializers.ModelSerializer): ... # Calling first serializer here routeClientConstraints = SimpleRouteClientConstraintSerializer(many=True, required=False) ... class Meta: model = Route fields = (..., 'routeClientConstraints', ...) depth = 1 When running the RouteSerilalizer, i want a response: { 'id':1, 'some_other_params': '...', 'routeClientConstraints': [{ 'name': 'my name' 'value': 'confused' }, ... ] } If i use the serializer as in the code above, I get 'routeClientConstraints': [ OrderedDict([ ('name', 'Minimum life boats'), ('value', '6') ]) ] I tried changing the serializer to: routeClientConstraints = SimpleRouteClientConstraintSerializer(many=True, required=False).data, which i expected would give me json format, but i got this: 'routeClientConstraints': [ OrderedDict([ ('id', 1), ('value', '6'), ('created_at', '2018-11-10T14:17:39.263848Z'), ('updated_at', '2018-11-10T14:17:39.263861Z'), ('route_default_constraint', 1), ('route', 1)]) ] How do i return a list of dictionaries? -
Do frameworks slow down the system?
Do frameworks slow down the system? I know this is a silly question but is it true that using different frameworks in front-end and back-end slow both the server or the client? Thanks in advance! -
How to connect js script from html to Django static
I have new Django project with frontend, initially written not for Django at all, so I cannot connect this script: <script> document.body.appendChild(document.createElement('script')). src='js/main_script.js?r='+Math.floor(Math.random()*99999999999999999999); </script> The file js/main_script.js is located in static folder, other js scripts are loaded as intended. And as I understand this script prevents caching for some reason. So, what am I missing in that part? Thanks in advance for any clarifications -
Django run on Docker Toolbox with WSL
I try to run my django project on local machine (on which I'm using WSL) using docker without using nginx or apache but with postgres as db and simple python manage.py runserver It seems that Docker itself works fine, I am able to create and run containers, logs show that all is up and running, I can ssh to both container with app and database but I can't reach it via my browser. Internet says that I need to set up propertly network on VM so I did: I'm setting my envs like that export DOCKER_TLS_VERIFY="1" export DOCKER_HOST=tcp://192.168.99.100:2376 export DOCKER_CERT_PATH='/path/to/mounted/dir/.docker/machine/machines/default' export DOCKER_MACHINE_NAME="default" export COMPOSE_CONVERT_WINDOWS_PATHS="true" Some tutorials says that instead of DOCKER_HOST=tcp://192.168.99.100:2376 it should be DOCKER_HOST=tcp://localhost:2376 (I know that documentation says port 2375 but for some reason toolbox choose 2376 when it was installing) but with second scenario WSL is unable to find docker deamon and any command's throwing an error: > docker info Cannot connect to the Docker daemon at tcp://localhost:2376. Is the docker daemon running? For a moment I thought that this might be a problem but I found many other tutorials where first config was used. I've tried also running python manage.py runserver 0.0.0.0:8000 python manage.py runserver 127.0.0.1:8000 … -
Extract only values without key from QuerySet and save them to list
I have problem with getting only values from QuerySet. I have my table: class Temperature(models.Model): id = models.IntegerField(primary_key=True) # AutoField? name = models.TextField(blank=True, null=True) value = models.IntegerField(blank=True, null=True) time = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'temperature' and in views.py: class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): labels = list(Temperature.objects.using('sensors').values('time')) temp_values = list(Temperature.objects.using('sensors').values('value')) data = { "labels": labels, "temperature": temp_values, } return Response(data) and with console.log() in html file I'm checking values, currently they are: But I want to retrive only value, without key. For e.g. : -
JSON object sent from Javascript to Django Views is empty
I'm trying to send some data from Javascript to Django through ajax. Here is my JS code: var json_name = {'name': 123} $.ajax({ method: 'POST', url: 'my url', contentType: "application/json", headers: { 'Content-Type':'application/json', 'X-CSRFToken': "{{ csrf_token }}" }, data: JSON.stringify(json_name), success: function (data) { //this gets called when server returns an OK response alert("it worked!"); }, error: function (data) { alert("it didnt work"); } }); Here is my Views.py: def myview(request): if request.is_ajax(): request_data = request.body # data = json.loads(request.body) print(request_data) # print(data) return render(request, 'candidate/view.html') else: return render(request, 'candidate/view.html') I get the output as b'' When I try to include these lines: data = json.loads(request.body) print(data) I get this error: TypeError: the JSON object must be str, not 'bytes' I took some reference from here Can someone help me with this? If you need any additional information to solve this, I'll be happy to share. -
Multi-page Django form with several models and views
I'm working on an existing system that has several forms that fill a group of models on Django, but they are related to one another and are split across some tab components to fill. My objective is to make several fields required and a way to get that info anywhere on the system, if X form was already completely filled with the required fields or not. There is a validation on the forms, but it only happens if the user actually presses the save button, if he simply leaves the page or doesn't even enter that tab, the system ignores it. Each form when completed is saving on the database that part individually, and that's good, because the user may not have all the info at once, but I need a way to alert: If the user didn't fill all the forms to let him know that it will not be validated by an admin until he does so. A flag so that the admin knows that the user didn't complete everything yet and doesn't waste time with it. I tried to make a custom save function on the models, that would save a flag based if some values were … -
The requested URL /manifest.json was not found on this server
While configuring gcm using izooto, I've placed the files in the root folder and added the read permissions for all the users. But, the file is not accessible enter image description here I'm using django, nginx on server. I've tried restarting the server. -
Same Django cronjob with different parameter
I have a base Django cron class which do a work periodically. Same work is done for three different parameters as follows : class FooCronJob(CronJobBase): def do(self): for par in ['par1', 'par2', 'par3']: # Do same thing for each parameter I want to parallelize cronjob for these three parameters, meaning that I want to have 3 cronjobs which do the base cronjob for each parameter. What is the best way to do this without replicating code? I'm using django-cron package with python3.