Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
angularjs not allow to do default Submit form
I use angular js on my page. if I add app.controller('myCtrl', function ($scope, $http) { $scope.deleteDiscount = function (discountID) { console.log(discountID); createSwal("warning").then((result) => { if (result.value) { $http.delete(`/api/discount/${discountID}/delete/`).then(res => { createSwal('success').then(() => { location.reload() }) }).catch(err => { }); } }); }; }); my delete API work correct but I have a form that do Submit after a click on submit button this submit not post anything to my backend But if I remove app.controller and angular from page submit button work correctly and post form. and I use this solution prevent default on submit :- Angularjs and change the button submit to input type='submit' but it doesn't work for me. how to change code to have both submit the form as regular way and use angular for do other work -
Virtualenv, WSGI Daemon erorr. permission denied : mod_wsgi, uid
I checked some similar problems. ex) mod_wsgi unable to connect WSGI daemon process but it did't work for my problem at least I think. My error is same that link. (13)Permission denied: mod_wsgi (pid=6402): Unable to connect to WSGI daemon process 'djangoServer' on '/etc/httpd/run/wsgi.6399.0.1.sock' as user with uid=99. So I insert socket-user=#99 but it doesn't work. user=#99 group=#99 also failed to resolve. System is Centos7, python2.7.5, apache2.4.6 And Virtualenv is django app 3.0.3, python 3.6.8 My django.conf is # WSGISocketPrefix /var/run/wsgi <VirtualHost *:80> DocumentRoot /usr/rest_auth ServerName djangoServer WSGIDaemonProcess djangoServer user=#99 group=#99 python-path=/usr/myvenv/lib/python3.6/site-packages WSGIProcessGroup djangoServer WSGIScriptAlias / /usr/rest_auth/rest_auth/wsgi.py <Directory "/usr/rest_auth/rest_auth"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /assets/ /usr/rest_auth/static/ <Directory /usr/rest_auth/static> Allow from all </Directory> </VirtualHost> and wsgi.py is import os, sys from django.core.wsgi import get_wsgi_application path= os.path.abspath(__file__+'/../..') if path not in sys.path: sys.path.append(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rest_auth.settings") application = get_wsgi_application() I tried to solve it via this link. https://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGISocketPrefix.html First move, I used WSGISocketPrefix inside <VirtualHost></VirtualHost> apache say, WSGISocketPrefix cannot use in VirtualHost. So I moved WSGISocketPrefix outside VirtualHost. This way I got more errors than socket-user and I think it's caused by the sqlite version issue. This is last line errorlog. django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). … -
Django Class Based Views TemplateView perform redirect if user is logged in
I'm rewriting my function views to class based views, the previous login page below def login(request, template_name="login.html"): context = {} if request.user.is_authenticated: return HttpResponseRedirect(reverse('home')) return render(request, template_name, context) would check to see if your already logged in, if yes would redirect you to the homepage how can i do the same with a templateview below? class LoginView(TemplateView): template_name = "login.html" -
Enter a valid date error received in django form
I've seen a lot of questions like this one but not specifically for generic class views. I get the error "Enter a valid date" but only when I set the date to be 24/02/1992 for example because it is taking month/day/year. If I set it to 02/02/1992, it works. I need it to accept day/month/year. I have a CreateView like this: class ContractGenerateView(CreateView): model = Prestamo form_class = PrestamoFormCreate template_name = 'usuarios/generateContract.html' def get_context_data(self, **kwargs): data = super(ContractGenerateView, self).get_context_data(**kwargs) data['form'].fields['fecha_primera_cuota'].widget.attrs = {'class': 'datepicker_primera_cuota'} data['form'].fields['fecha_primera_cuota'].widget.format = '%d/%m/%Y' data['form'].fields['fecha_primera_cuota'].input_formats = ['%d/%m/%Y'] with a simple form class PrestamoFormCreate(forms.ModelForm): class Meta: model = Prestamo fields = ( 'moneda', 'partner', 'fecha_primera_cuota', 'frecuencia', 'plazo_mensual', 'fecha_desembolso', 'cupo', 'porcentaje_cuota_inicial', 'interest_rate', 'interes_moratorio', 'fee_abaco', 'cuota', 'fecha_final_contrato', 'metodo_pago') and a simple javascript in my template: $(function () { $(".datepicker_primera_cuota").datetimepicker({ timepicker:false, format: 'd/m/Y', }); }); Thank you -
SMTP Authentication Error: Username and Password not accepted:
My email and password is correct but i'm not able to send email using my script enter code here. import smtplib content ="hello" mail = smtplib.SMTP("smtp.gmail.com",587) mail.ehlo() mail.starttls() mail.login('mymail@gmail.com','password') mail.sendmail('mymail@gmail.com','destination@gmail.com',content) mail.close() -
GeoDjango, Cordinates from Google maps are getting plotted wrong on leaflet using PointField
Please help me out in solving this issue. class RecievingImages(models.Model): """Original and Masked Images""" name = models.CharField(max_length = 100, unique = True, primary_key=True) cordinate_X = models.FloatField() cordinate_Y = models.FloatField() point = models.PointField(srid=4326, geography=True, default='POINT(0.0 0.0)') def __str__(self): return self.name class Meta: verbose_name_plural = 'Image Mapping' I have coordinates that I got from google maps API Example here cordinate_X : 21.2166277 cordinate_Y : 72.7763859 Technically, These coordinates are of Gujrat, India actual link of the coordinates Now to plot on leaflet I converted that into point field with reference to this link https://stackoverflow.com/a/48293443/7999665 from django.contrib.gis.geos import Point for l in RecievingImages.objects.all(): ... l.point = Point(x=l.cordinate_X, y=l.cordinate_Y, srid=4326) ... l.save() Now when I went back to Django admin page it's marking the coordinates wrongly somewhere in Sea Thanks for your time. Regards Update After a good amount of googling, I found that there could be an issue of srid used that is, google maps might be using '3587' and I have used '4326' I tried to change this but am getting an error. raise NotSupportedError('PostGIS only supports geography columns with an SRID of 4326.') django.db.utils.NotSupportedError: PostGIS only supports geography columns with an SRID of 4326. The database I have used is PostGIS. -
Optimizing a django query while hitting the database
Currently, the time taken by the api to provide the response takes approx 8-9 secs. However, I want to optimize it for less than 2 secs. def create(self, request, *args, **kwargs): user = request.user cities = City.objects.filter(owners=user,citystatus__status__in=["A","B","C"],client__isnull=False) res = [] for r in cities: res.append(self.get_cities(r)) return Response(res) However, I have tried to optimize the code a little by using annotate. Now, I am unable to optimise it any more further. Any leads would be helpful. -
Create Django Model from a list of dictionaries
I want to create a model from a list of dictionaries (i.e) it should be similar to this query result = MyModal.objects.all() I know that we can create an instance of a model like this MyModal(**data_dict), I want something similar so i can pass in a list of dictionaries. data_list = [{name: 'abc'}, {name: 'xyz'}] # result = "Logic to create instance for 2 objects" Ping me in comments if more explanation is needed. -
__init__() got an unexpected keyword argument While overiding DJANGO CreateView
Hello all I have defined the URL something like this: path('new_checkin/<int:room_id>',NewCheckInCreateView.as_view(),name='new_checkin'), And i want to fetch this room_id and initialize the data based on this room_id in template. I'm using django createview and the how i try to do is , views.py class NewCheckInCreateView(CreateView): template_name = 'my_template' model = my_model form_class = NewCheckInForm def get_form_kwargs(self): kwargs = super(NewCheckInCreateView, self).get_form_kwargs() //Here i try to update the kwargs kwargs.update(self.kwargs) return kwargs For the initialization of the form . I defined the ModelForm like this : class NewCheckInForm(ModelForm): class Meta: model = my_model fields = ['room',] def __init__(self, room_id=None,*args, **kwargs): super(NewCheckInForm, self).__init__(*args, **kwargs) room_obj = Room.objects.get(id=room_id) if room_obj: self.initial['room']= room_obj While i run this code I get the errors like this ; TypeError at /booking/new_checkin/7 init() got an unexpected keyword argument 'room_id' I search for many of the tutorials and blogs for this .But any one of the tricks not worked for me . Why this error may be raising , I would be glad id someone answer my question. -
Django adding dropdown menu that pushes content down on selection
Using Django, I am trying to create a dropdown menu that pushes the content below it down, when you select it. I have been using this W3 site as a guide as it's exactly what I'm after in terms of functionality. I am struggling to get this to work. I suspect my problem is javascript related but I have zero experience in this area. Resources below if you can feel it in your heart to assist: Local system structure = https://imgur.com/a/bzYSntm (excluded irrelevant apps) JS file = dropdown-menu.js var dropdown = document.getElementsByClassName("dropdown-btn-me"); var i; for (i = 0; i < dropdown.length; i++) { dropdown[i].addEventListener("click", function() { this.classList.toggle("active"); var dropdownContent = this.nextElementSibling; if (dropdownContent.style.display === "block") { dropdownContent.style.display = "none"; } else { dropdownContent.style.display = "block"; } }); } Relevant CSS = main.css file /* this class is the self-made drop-down box in sidenav */ .dropdown-nav { height: 100%; width: 200px; position: fixed; z-index: 1; top: 0; left: 0; background-color: #111; overflow-x: hidden; padding-top: 20px; } /* styling for the self-made drop-down box in sidenav */ .dropdown-nav a, .dropdown-btn-me { padding: 6px 8px 6px 16px; text-decoration: none; font-size: 20px; color: #818181; display: block; border: none; background: none; width:100%; text-align: left; cursor: … -
Send email with django + gunicorn + nginx get timeout
I'm trying to deploy an django project in AWS with gunicorn + nginx but I'm getting timeout error. My email backend uses AWS SES with SMTP authentication. The first 2 emails are send normally, after these I'm getting this error. The account is already unblock restriction for sending email. Any idea? -
ValueError: attempted relative import beyond top-level package, migrations Django
Going crazy with this error. I have a file directory: backend - backend - file1 - file2 - restaurant - models - users - file4 - manage.py In Django I have an import in file4 as follows from ..restaurant.file3 import Restaurant. This works fine in Django, it knows what and where Restaurant is. Problem is when I run python manage.py makemigrations i get the error ValueError: attempted relative import beyond top-level package . I tried putting the entire package in another toplevel package that also contained the manage.py file so it looked like, but this did not work. toplevel backend - backend - file1 - file2 - restaurant - models - users - file4 - manage.py I have tried every syntax and keep getting the same error. I have added init.py files everywhere, then removed them everywhere. I feel like this should not be this difficult. I remember in Python2 I swear I could just do ..restaurants and it would work fine. -
i have code in django application, and iwant reuse the same code to save the result in project it self
from xlwt import Workbook def invoice_report(request,slug): ..... elif 'download' in request.GET: if str(request.GET.get('download')).lower() == 'true': response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="Report.xls"' wb.save(response) return response .... here i am trying t save result response in local directory as below. but its not working ''' from xlwt import Workbook def result_download(request): result_response = invoice_report(request,slug) if result_response: file = open(folder_name + '/' + str(aircraft.msn) + 'report.xls', 'wb')file.write(result_response.rendered_content) file.close() return response '''' -
Django DateTime field in string after DRF update
I have a serializer in Django using DRF which has an update capability. I want to be able to update a DateTime field and during that update it gets passed to a function. I am having a problem since it gets read as string first. #models.py class Mission(models.Model): name = models.CharField(max_length=45) capture_time = models.DateTimeField(blank=True, null=True, unique=True) #serializers.py class MissionSerializer(serializers.ModelSerializer): capture_time = serializers.DateTimeField() class Meta: model = Mission fields = '__all__' def to_internal_value(self, data): return data ... @transaction.atomic def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.capture_time = validated_data.get('capture_time', instance.capture_time) instance.save() ... do_something(mission_key=instance.pk) return instance #some_function.py def do_something(mission_key): mission = Mission.objects.get(id=mission_key) print("CAPTURE_TIME", mission.capture_time, type(mission.capture_time)) What gets printed is in string format. CAPTURE_TIME 2019-12-11T03:22:20Z <class 'str'> -
Compare two django's DateTimeField on signal
I want to use a signal to check the values of my class before it is saved in the database. I have the following function @receiver(pre_save, sender=A) def on_pre_save_a(sender, **kwargs): if sender.start_date > sender.end_date: raise Exception('Error with dates') and my A class looks something like this class A(models.Model): start_date = models.DateTimeField() scheduled_end_date = models.DateTimeField() But when I try to add a new A object in the admin page, an exception is raised, saying that '>' not supported between instances of 'DeferredAttribute' and 'DeferredAttribute' What would the best to compare these two DateTimeField be? And is this the best way of doing this kind of checks? Thank you -
Handling Multiple Concurrent Request in Django, Gunicorn, Nginx
0 I am facing some issue regarding multiple concurrent request handling in my site. To explain in details - I have a django view which recieves file from the request and then call an api and do some calculation and finally send response. Normally the site works fine but while getting 100-150 request at the same time the site becomes very slow. After some research I found that Django is synchronous and gunicorn deligate requests to its workers that means at a time the server can process the number of worker amount of requests and the other requests are queued. In my case worker number is 3. I have found that gunicorn can use asynchronous worker class like gevent which doesn't wait for the request to finish and receives another request. But after changing gunicorn configuration to --worker-class=gevent and --worker-connection=1000 my site is not responding for that specific view only after I upload files. What could be the issue here? My goal is to recieve a request, start processing it (the thrid party api call and the calculation on my server) and receive another request even if the previous request is not finished processing. What should I do? Some thing … -
How to show the sub menu of sub menu in the <option> format?
I want to show the sub menu of some particular sub menu only in this format.For example I have created some menus and inside these menus there are sub menus.Which are working fine but here I want to show the sub menu of some particular sub menu only in this format instead of ul li tag. How can I achieve it ? <select class="custom-select"> <option selected>abc</option> <option value="1">def</option> <option value="2">xyz</option> </select> -
How can I configure django settings for SMTP relay service. (https://support.google.com/a/answer/2956491?hl=en)
I have following settings. EMAIL_PORT = 587 EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = 'service_account@organization.org' EMAIL_HOST_PASSWORD = 'service.accout.password' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBacken SERVER_EMAIL=no-reply.application@organization.org DEFAULT_FROM_EMAIL=no-reply.application@organization.org Our intention is to use dummy no-reply addresses. i.e. (no-reply.application@organization.org) that don't really exist. It almost worked with the current setup, but as the outgoing e-mails were missing the FROM address (or had a non @organization.org address set), the smtp-relay server was replying with not authorized. Is there a way to configure this in the settings.py files? -
How do I change a value of a BooleanField in Django?
The function: def post_publish(request, pk): post = get_object_or_404(Post, pk=pk) post.publish() return redirect('post_detail', pk=pk) The model class: class Post(models.Model): title = models.CharField(max_length=256) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) neg_sentiment = models.BooleanField(default=False) def publish(self): self.neg_sentiment = True self.save() def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.pk}) def __str__(self): return self.title I'm trying to get BooleanField to change, but it still remains default=False -
Django saving some fields to the DB but not others
I'm trying to save some data through a form and I'm using a formset for that. It is an invoice which needs to save, among other things, a product and its quantity(let's call it detail). I was able to render everything in one place (this wasn't simple) and to save the invoice and the detail to the DB. For some (unknown to me) reason, detail table is saving the Product ID but not the Invoice ID. This is my models.py class Detalle(models.Model): factura = models.ForeignKey(Factura, null=True, on_delete=models.CASCADE) producto = models.ForeignKey(Producto, on_delete=models.CASCADE) cantidad = models.PositiveIntegerField(default=1) subtotal = models.DecimalField(max_digits=9 , null=True, decimal_places=2) class Factura(models.Model): fecha = models.DateField(default=datetime.date.today) numero = models.CharField(max_length=10, default='0000000000') proveedor = models.ForeignKey(Proveedor, on_delete=models.CASCADE) productos = models.ManyToManyField(Producto, null=True, blank=True) total = models.DecimalField(max_digits=9 , null=True, decimal_places=2) And this is my views.py def factura_new(request): DetalleFormSet = formset_factory(DetalleForm, extra=2) if request.method == "POST": factura_form = FacturaForm(request.POST) detalle_formset = DetalleFormSet(request.POST) if factura_form.is_valid() and detalle_formset.is_valid(): factura = factura_form.save(commit=False) factura.save() for detalles in detalle_formset: detalles.save() return redirect('factura_detail', pk=factura.pk) else: return redirect('factura_error') else: factura_form = FacturaForm() detalle_formset=formset_factory(DetalleForm, extra=2) return render(request, 'factura/factura_edit.html', {'factura_form': factura_form, 'detalle_form': detalle_formset} ) I tried adding to the for something like: detalles.factura_id = factura.pk, factura.id prints OK, but it won't save the number to the … -
How to set authenticated user to serializer?
I created simple CreateAPIView using django rest framework. class CreatePostAPIView(generics.CreateAPIView): serializer_class = serializers.PostSerializer permission_classes = [IsAuthenticated] class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' class Post(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, null = True, blank = False) spot = models.ForeignKey(Spot, on_delete = models.CASCADE, null = True, blank = False) comment = models.TextField(null = True, blank = False) Model Spot has three fields user spot comment From client, spot and comment is sent using http POST request param as from of JSON. However user does not come with http POST request param but I need to get user from django's authenticated user(like request.user). I know I can get user from request.user but how can I set the user to serializer? -
Django Invalid form: this field is required
I keep getting an error where a form is invalid. I have a few print statements in my view, and they indicate that the query field is not being submitted - I included some output at the bottom of this post. Why is the query not submitting? Is it because I am using GET to submit the form? Here is my forms.py: from django import forms class SearchForm(forms.Form): query = forms.CharField(label='Search', max_length=200) views.py: from django.shortcuts import render from django.http import HttpResponse from . import pull from .forms import SearchForm def search(request): if request.method == "GET": form = SearchForm(request.GET) print(request.GET) print(form) if form.is_valid(): query = form.cleaned_data['query'] print(query) results = pull.main(query) print(results) return render(request, 'book_search/results_copy.html', {'form': form, 'results': results}) else: print("invalid") form = SearchForm() return render(request, 'book_search/results_copy.html', {'form': form}) else: return HttpResponse("Invalid request type") results_copy.html: <html> <head> </head> <body> <form method="GET" action=""> {% csrf_token %} <input type="text" value=""> <button type="submit">Search</button> </form> <p>Text after form</p> {{ results|safe }} <table> {% for row in results %} New table row <tr> {% for value in row %} <td>{{ value.0 }}</td> {% endfor %} </tr> {% endfor %} </table> </body> </html> some output lines: [07/Feb/2020 02:55:17] "GET /search/?csrfmiddlewaretoken=RKdAkUxI7ax4Z2Nw05FSUySADe9KAlqMijBeVsHv6uRuPy3DfS6UUnlNXoj6E8mM HTTP/1.1" 200 374 <QueryDict: {}> <tr><th><label for="id_query">Search:</label></th><td><ul class="errorlist"><li>This … -
initial migrations file into virtualenv
I am trying to setup a virtual envirorment on my windows 10 laptop in cmd for a homework assignment and I'm having problems with the instructions given. I was able to get the enviroment up and running and download the requirements, but now the instructions say to Run the initial migrations with: ./manage.py migrate When I try to run the code given, I get an error saying that '.' is not recognized as an internal or external command, operable program or batch file. From the research I did the instructions that they give are for a different command language (from what I found it said Linux, but I'm preaty sure thats an operating system). I have tried looking up initial migrations with virtualenv, but I couldn't find information related to my situation. I'll post the full instructions below. Does anyone know how I can proceed? In the root directory, where manage.py resides, do the following (all commands run from this dir) Set up a virtual environment with virtualenv venv (virtualenv installation guide - note you may need to use sudo with the installation like sudo pip install virtualenv) Activate virtualenv by with . venv/bin/activate Install pip requirements by with pip … -
Makemigrations doesn't respect to_field parameter when ForeignKey referring to a non-"id" primary key
class Modelgroup(models.Model): modelgroup = models.CharField(max_length=64, primary_key=True, db_column='modelgroup') class UserFilter(models.Model): user = models.ForeignKey(User, models.DO_NOTHING) modelgroup = models.ForeignKey(Modelgroup, models.DO_NOTHING, \ to_field='modelgroup', db_column='modelgroup') I'm trying to add the UserFilter model to a project with the modelgroup foreign key pointing to the Modelgroup table which doesn't have the standard ID field. When I run manage.py makemigrations on that code I get operations = [ migrations.CreateModel( name='UserFilter', fields=[ ... ('modelgroup', models.ForeignKey(db_column='modelgroup', on_delete=django.db.models.deletion.DO_NOTHING, to='core.Modelgroup')), ... ], ), ... ] Which lacks of the to_field parameter. And when I run manage.py migrate on it I get django.db.utils.ProgrammingError: column "id" referenced in foreign key constraint does not exist Important When I replace primary_key=True by unique=True the to_field parameter works as expected. Any workaround? -
CSS file being read as HTML file
I'm trying to link a css stylesheet to my django html template but it keeps being read as an html file with the error: 127.0.0.1/:1 Refused to apply style from 'http://127.0.0.1:8000/static_cdn/css/base-template.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. This is my base.html file and I know the path is correct because VS Code directs me to the file when I left-click on the link. <head> <link type="text/css" rel="stylesheet" href="../../static_cdn/css/base-template.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>GuitarShop</title> </head> Here is my directory: Project Folder guitarshop > templates > base.html static_cdn > css > base-template.css The reason why I am storing the css file in the static_cdn folder instead of a static folder in the templates folder is because when I do so, the command "python manage.py collectstatic" doesn't collect the file folder so I get the following error: GET http://127.0.0.1:8000/static/base-template.css net::ERR_ABORTED 404 (Not Found) Please help!