Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't access Django middleware at docker venv
i currently build my Django app with docker which works great so far but if i try to use my self-made middleware inside the container, Django is simply not able to find the ressources at the venv inside the docker container. if i deploy the app outside of docker the middleware gets recognized without any problems. is there maybe an issue with my setup.py of the middleware? import os import sys import subprocess from distutils.core import setup, Command with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f: readme = f.read() setup(name="ssengine", description='Django middleware that GPG signs HTML pages.', long_description=readme, maintainer="venom", version="0.1.0", packages=["ssengine"], license="GNU Affero General Public License v3 or later (AGPLv3+)", classifiers=[ 'Development Status :: 5 - Pre-Production', 'Framework :: Django', 'Environment :: Web Environment', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Security', ], ) at my requirements.txt im installing the middleware like this: -e git+http://zzz.xxxxxxx.yyy/venom/ssengine.git#egg=ssengine the setup log also shows that the middleware has been installed correctly... I really have no clue where else i could look. I Also deleted all relevant … -
Django update model in shell not saving
I´m trying to update the data of an existing model with a csv. I read the file and assign the values with no problem. If I try `MyModel.update() everything runs with no error but the data is not saved. with open('Productosold.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: p = ProductosBase.objects.filter(codigo_barra = row['codigo_barra']) p.region=row['region'] p.producto_ing=row['producto_ing'] p.packaging_ing=row['packaging_ing'] p.precio_compra=row['precio_compra'] p.uom=row['uom'] p.units_inner=row['units_inner'] p.inner_master=row['inner_master'] p.tier=row['tier'] p.precio_lista_internacional=row['precio_lista_internacional'] p.update() I usualy upload new data using the MyModel.save() method and have no problem. Now, if I use that I get "Queryset has no attribute save". p.save() If I print some of the p.values I can see they are populated correctly from the csv file. What I´m doing wrong? Thanks in advance! -
Form clean method not retreiving input data
I have a clean method to validate data of mine. The if statements are not running because when I try to retrieve the form inputs, it returns as NoneType, even though I filled out info for that input. I am unsure what is causing this and would appreciate any help. forms.py def validate_date1(value): if value < timezone.now(): raise ValidationError('Date cannot be in the past') def validate_date2(value): if value < timezone.now(): raise ValidationError('Date cannot be in the past') class LessonForm(forms.ModelForm): lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_datetime_start = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'}), validators=[validate_date1]) lesson_datetime_end = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], required=False, widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'}), validators=[validate_date2]) lesson_weekly = forms.BooleanField(required=False) class Meta: model = Lesson fields = ('lesson_instrument', 'lesson_datetime_start', 'lesson_datetime_end', 'lesson_weekly') def clean(self): cleaned_data = super().clean() lesson_datetime_start = cleaned_data.get('lesson_datetime_start') lesson_datetime_end = cleaned_data.get('lesson_datetime_end') if lesson_datetime_start >= lesson_datetime_end: raise ValidationError('Start time cannot be after end time') if lesson_datetime_start.date() != lesson_datetime_end.date(): raise ValidationError('Start date and end date have to be the same') return cleaned_data -
Django: Authentication Form translated only locally?
I'm using the default Authentication form from Django. This is the default implementation by Django of AuthenticationForm: from django.contrib.auth.forms import AuthenticationForm I've translated the default error_messages to Spanish: error_messages = { 'invalid_login': _( "- Por favor, ingrese un nombre de usuario y contraseña correctos. " "- Diferencie entre minúsculas y mayúsculas." ), However, when the app is uploaded to production (Heroku) this changes are not visible (it's like it has been only applied locally). Why? class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True}), label="Usuario") password = forms.CharField( label=_("Contraseña"), strip=False, widget=forms.PasswordInput, ) error_messages = { 'invalid_login': _( "- Por favor, ingrese un nombre de usuario y contraseña correctos. " "- Diferencie entre minúsculas y mayúsculas." ), 'inactive': _("Esta cuenta no está activa."), } def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg. """ self.request = request self.user_cache = None super().__init__(*args, **kwargs) # Set the max length and label for the "username" field. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) self.fields['username'].max_length = self.username_field.max_length or 254 if self.fields['username'].label is None: self.fields['username'].label = capfirst(self.username_field.verbose_name) def … -
How do I create a table without repeating the header?
I am working on a page that outputs the member's information in a table if the member meets a certain criteria. The problem I'm coming across is that the table header keeps repeating itself if there is more than one member that meets the criteria. Here's the code <div class="card"> <div class="card-header bg-transparent"> <h4>Members who list {{ instrument.name }} as their primary instrument:</h4> </div> <div class="card-body"> {% if not primary_users %} <h5>There are currently no members who list {{ instrument.name }} as their primary instrument.</h5> {% else %} <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Name</th> <th>HCMN Rating</th> <th>Email</th> <th>Location</th> </tr> </thead> {% for member in primary_users %} <tbody> <tr> <td><a href="{% url 'users:individual_member' member.id %}">{{ member.first_name }} {{ member.last_name }}</a></td> <td>{{ member.rating }}</td> <td>{{ member.email }}</td> <td>{{ member.area }}</td> </tr> </tbody> </table> </div> {% endfor %} {% endif %} </div> </div> And here is a screenshot of the problem I am talking about: -
Adding Captcha to a django login form
I would like to add Captcha authentication to my Django login. I already know how to authenticate the form but the problem is that i don't have a login View on my views.py, i'm using the login view of a module that i integrated on my project. The login view that i'm using is right here, and basically i just imported it on my project and that view handles the whole login part. Now how can i add a captcha authentication part to that view? I know that the first thing i should do is inherit the module's view on my own views.py file, but i don't really know how to go from here. I already defined the authentication logic of the Captcha form, so the only thing i need to figure out is how to integrate the following code into the login view that i'm using: def captcha_auth(request): if request.method == "POST": ''' Begin reCAPTCHA validation ''' recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': 'KEY', 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() ''' End reCAPTCHA validation ''' if result['success']: //In the following lines i'll add authentication for the user else: messages.error(request, "Please fill the captcha form") -
i want to make dynamic value in python
i have important project guys so . how can i make dynamic print view that variable change every second based on user input for example if user make input ex: 100 i want 100 to be 101 and 102 in same line and print on screen using django + python3 is it possible and what is other options plz :) i have important project guys so . how can i make dynamic print view that variable change every second based on user input for example if user make input ex: 100 i want 100 to be 101 and 102 in same line and print on screen using django + python3 is it possible and what is other options plz :) -
NoReverseMatch Because Not Found 1 Pattern Base.html
I understand that my template is not defined, so I need to pass the template but the template I want to use the url is the base.html, so how to pass the model? Model Name: Quiz Url: {% url 'teachers:quiz_results' quiz.pk %} -
How do I change my template so dynamic url works in Django?
I am making a dynamic URL in Django. These are the steps I followed: First in urls.py path('products/<int:my_id>/', views.products, name='products'), Next, in views.py I added products view as defined below def products(request, my_id, *args): obj = Product.objects.get(id=my_id) custom_context = { 'title': 'products', 'object': obj } return render(request, 'products.html', custom_context) then created its associated products.html file {% extends 'base.html' %} {% block content %} <h1>Products Page</h1> {{ object.title }} {{ object.description }} {{ object.price }} {% endblock content%} Once I type in addressbar something like localhost:8000/products/1/ it shows this error page for me: I wish the image is clear enough to see. I saw that error and according to my solution I changed my structure of products.html file to this <!DOCTYPE html> <html lang="en"> <body> <h1>Products Page</h1> {{ object.title }} {{ object.description }} {{ object.price }} </body> </html> then I saw it worked pretty fine as expected! which means that there are no problems in urls.py, views.py but only in my .html template. Can you please tell me what is the problem? Thank you so much -
installing mod_wsgi in xampp server in windows 10 to host django on apache server
I want to host my django app on apache server and use mysql for database. I tried google to find a way of doing this and I found wherever i mention apache and django there comes this mod_wsgi term, Firstly i don't understand this but from the docs i got to know this is something which helps to setup django on top of apache server. I tried to understand but still i m clueless. Can anyone please help me to setup this on my django app and deploy on apache server. Thanks in advance for any help. -
Gunicorn is not running. No module named bind
Here is the error: enter image description here Here is the gunicorn.service configuration enter image description here -
Update And Delete Users in Django Rest Framework
I have a working register API in my DRF backend. I want to be able to perform updates on user profiles with PUT requests. How can I write a method that validates the user and updates the user with the matching id? I also want write a method that handles the DELETE requests and deletes the user with the id matching the request. # serializers.py class RegisterSerializer(ModelSerializer): class Meta: model = User fields = ( 'account_type', 'id', 'username', 'name', 'email', 'phone', 'country', 'city', 'adress_1', 'adress_2', 'zip_code', 'photo', 'password', ) ... def create(self, validated_data): user = super(RegisterSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user # api.py class RegisterAPI(CreateAPIView): permission_classes = (AllowAny,) serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) token = Token.objects.create(user=serializer.instance) token_data = {"token": token.key} return Response({ "token": token.key, "user": {**serializer.data} }) # urls.py urlpatterns = [ ... path('api/auth/register', RegisterAPI.as_view()), ... ] -
How to store a complex number in Django model
I need to store a complex number in a Django model. For those who forget, that simply means Z=R+jX where R and X are real numbers representing the real and imaginary components of the complex. There will be individual numbers, as well as lists that need to be stored. My searches so far haven't provided a good solution for lists, so I intend to let the database handle the list as individual records. I see two options for storing a complex number: 1) create a custom field: class Complex(models.CharField) This would allow me to customize all aspects of the field, but that is a lot of extra work for validation if it is to be done properly. The major upside is that a single number is represented by a single field in the table. 2) let each complex number be represented by a row, with a float field for the real part, R, and another float field for the imaginary part, X. The downside to this approach is that I would need to write some converters that will create a complex number from the components, and vice versa. The upside is that the database will just see it as another … -
For loop inside views return only first n
have two models and the second model has foreign key related to first model.using templates i can make the for loop for first model fine, but I could not make the nested loop for the second model inside templates. I have tried to write the for loop inside views.py file but it is only return the first n only? i do not know why -
Django 1..8,python 2.7, Empecher l'accès à une page par l'url
Bonjour, J'aimerais empêcher l'accès à une page par l'url. Je m’explique mon url est sous la forme 127.0.0.1/application/comp/filtre-A. l’accès nécessite un login (@login_required). Le problème est que l'utilisateur peut saisir manuellement l'url 127.0.0.1/application/comp/filtre-B pour y accéder. j'ai tenté un {% csrf_token %} dans le template mais ça marche pas. Pouvez vous m'aider SVP Merci. -
List in two functions in python
I have two functions, I need the list from first function be read for the second, the two is in the same view on django app, and they make two different templates. def gerar_graficos(request): descricao = None descricao2 = None if request.method=='POST': descricao = request.POST['descricao'] descricao2 = request.POST['descricao2'] conn = cx_Oracle.connect('banco de dados') cur = conn.cursor() cur.execute(consulta.format(descricao, descricao2)) teste = list() teste2 = list() teste3 = list() teste4 = list() d = 0 for line in cur: teste.extend(line) for indice, c in enumerate(teste): #if c + 0 == c: teste3.extend([c - 10000]) #else: d = 0 cur.execute(consulta.format(descricao, descricao2)) for coluna in cur: teste2.extend(coluna) for indice2, c in enumerate(teste2): if indice2 >= d: teste4.extend([c]) y_axis = teste3 x_axis = teste4 width_n = 0.001 bar_color = 'yellow' cur.close() conn.close() context = { 'descricao': descricao, 'descricao2': descricao2 } return render(request, 'core/graficos_list.html', context, teste3, teste4) Pass the lists teste3 and teste4 for this function: def index(request, graficos): fig = Figure() ax = fig.add_subplot(1,1,1) ax.plot(graficos[3], graficos[4]) ax.grid() buf = io.BytesIO() canvas = FigureCanvas(fig) canvas.print_png(buf) response=HttpResponse(buf.getvalue(), content_type='image/png') return (response) -
Initial value of inputs in Django not working
I defined an initial value to my title field, but once I execute it, it shows no error and the initial value is not showing in my field how do I solve it? Thanks def form_view(request): if request.method == "POST": initial_data = { 'title': 'default title' } form = ProductForm(request.POST, initial=initial_data) if form.is_valid(): form.save() form = ProductForm() else: form = ProductForm() return render(request, "form.html", {"form": form}) -
Template Parse Erros Angular "<" (" with Django REST framework
I've been trying to create a DRF API with an Angular front end for an existing project that I have. I've created a serializer for User and Device. I tried removing multiple pieces of the HTML component, managing to result in a different error, StaticInjectorError(AppModule -> DevicePostService). I'm still pretty new to Angular so what it seems like the error is coming from is the fact that my devicepostservice is not getting served to the web page for some reason. Console error: [Error] Error: Template parse errors: Unexpected character "<" (" <div class="col-sm-4"> <button (click)="login()" class="btn btn-primary">Log In</button [ERROR ->]</div> <div class="col-sm-12"> <span *ngFor="let error of _userService.errors.non_field_errors""): ng:///AppModule/AppComponent.html@15:2 Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (" <div class="col-sm-4"> <button (click)="login()" class="btn btn-primary">Log In</button [ERROR ->]</div> <div class="col-sm-12"> <span *ngFor="let error of _userService.errors.non_field_errors""): ng:///AppModule/AppComponent.html@15:2 Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (" <span *ngFor="let error of _userService.errors.non_field_errors">{{ error }}<br /></span> </div> [ERROR ->]</div> <div class="row" *ngIf="_userService.token"> <div class="col-sm-12">You are logged in as {{ "): ng:///AppModule/AppComponent.html@19:0 _preparseLoadedTemplate (vendor.js:24658) normalizeTemplate (vendor.js:24635) loadDirectiveMetadata (vendor.js:26827) … -
How to save array date in django?
How to save array date in django? I have an array and need to save it. "fields": { "description":"Medida", "name": "medida", "tipo": "tipo" } Produto.objects.create(fields) It does not work. -
Receiving Django error instead of form invalid error
I have a form with various validators regarding datetime inputs. All the validators except 1, work and send a message.error to the user when the form doesn't pass. However, one of the validators redirects to the Django error page saying '>=' not supported between instances of 'NoneType' and 'NoneType', instead of just sending a message.error to the user. I would appreciate any help in figuring out why my validate_date1 and validate_date2 are showing a Django error instead of just not passing and sending a user a message error. forms.py def validate_date1(value): if value < timezone.now(): raise ValidationError('Date cannot be in the past') def validate_date2(value): if value < timezone.now(): raise ValidationError('Date cannot be in the past') class LessonForm(forms.ModelForm): lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_datetime_start = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'}), validators=[validate_date1]) lesson_datetime_end = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], required=False, widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'}), validators=[validate_date2]) lesson_weekly = forms.BooleanField(required=False) class Meta: model = Lesson fields = ('lesson_instrument', 'lesson_datetime_start', 'lesson_datetime_end', 'lesson_weekly') def clean(self): cleaned_data = super().clean() lesson_datetime_start = self.cleaned_data.get("lesson_datetime_start") lesson_datetime_end = self.cleaned_data.get("lesson_datetime_end") if lesson_datetime_start >= lesson_datetime_end: self.add_error(None, 'End time must be later than start time') if lesson_datetime_start.date() != lesson_datetime_end.date(): self.add_error(None, 'Dates have to be the same') return cleaned_data … -
FieldError at / Related Field got invalid lookup: icontains
I wanted to do a filter through some blogs and make a search bar out of it but im getting a FieldError at / Related Field got invalid lookup: icontains from django.db.models import Q def foo(request): Blog.objects.filter(Q(title__icontains=search_term_extract)|Q(author__icontains=search_term_extract)) -
CBSE Computer Science With Python (2019 Syllabus)
How to install and configure python 3.6.4 with mysql 5.5.x under django 2.x.x framework? -
how to return response message with 400 bad request status code from django restframwork?
Code in Python Django: if len(error) < 1: return Response(status=HTTP_200_OK) else: return Response({"data":error}status=HTTP_400_BAD_REQUEST) code in javascript if(response.status===200){ alert("ok") }else if(response.status===400){ alert("not ok") } It returns the code when it is 200 ok, but returning nothing when it is 400 bad request. In fact, nothing seems replying message except 200_ok code. Is there any solution for that? -
nginx reverse proxy to apache mod_wsgi django app
Been trying to do this for a while and haven't found something that works. I have a Django app deployed via Apache & mod_wsgi. Apache listens on port 8080 and everything works fine when I access example.com:8080 I have Nginx listening on port 80 serving a static site at /. I'm trying to configure Nginx reverse proxy to Apache (Django) such that when I access example.com/app it should take me to the Django app. This is my configuration so far: location /app/ { proxy_pass http://localhost:8080/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } I have tried using/not_using the trail slash both after app and the proxy_pass address. However, I am always getting a 404 Not Found error. Can someone please help me to correctly set the reverse proxy in Nginx? Thanks in advance -
How to put python3 manage.py runserver in a Bash Script
Here is my Bash script it's very simple. I added it to the init/d folder so it works upon rebooting my computer. I create directories and so that part of the script is working; However my server won't run. I'm trying to avoid having to type out: sudo python3 manage.py runserver ...everytime I want to run my Django website; I want it to automatically start upon boot up. #!/usr/bin/env bash #!/usr/bin/env python # /etc/init.d/replicatorService ### BEGIN INIT INFO # Provides: replicatorService # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start daemon at boot time # Description: Enable service provided by daemon. ### END INIT INFO for i in {1..12} do if [ ! -d "/media/drive$i" ]; then mkdir "/media/drive$i" fi done sudo python3 Documents/Replicator/dfp/dfp-rep/manage.py runserver