Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i add filter to all querysets at the end of sql-query?
If i add filter in manager, sql-query to the database will be too long, because my filter will be at start of sql-query. I need to add this filter at the end, after all other filters and changes. -
how a django can a handle multi server - multi client?
How can I solve this very big problem? Multi-threading may help? The problem is that if multiple clients try to log in, when the server receives the first response from several IdP, all the users will show my page as logged in with the credential of the first user or several users. In the meanwhile my server starts listening for the IdP response. When the user logs in the in IdP page, the IdP sends data to my server, that handles them and shows my page to the user. -
ValueError at / ModelForm has no model class specified
I created a Todo list app.When I try to add item to list I get an error like this; ModelForm has no model class specified.How can I solve this? models.py from django.db import models class List(models.Model): item = models.CharField(max_length = 200) completed = models.BooleanField(default = False) def __str__(self): return self.item + ' | ' + str(self.completed) forms.py from django import forms from .models import List class ListForm(forms.ModelForm): class Meta: model:List fields: ["item", "completed"] views.py from django.shortcuts import render,redirect from .models import List from .forms import ListForm from django.contrib import messages def home(request): if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() all_items = List.objects.all messages.success(request, ('Item has been added to list')) return render(request, 'home.html', { 'all_items': all_items}) else: all_items = List.objects.all return render(request,'home.html',{'all_items': all_items} ) -
Can not save django model object
Have one request with new value for one field. Than getting this value, setting it to the model object. And during saving have next error: TypeError: expected string or bytes-like object here is all Traceback: Traceback (most recent call last): File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\braces\views\_access.py", line 102, in dispatch request, *args, **kwargs) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\admin\PycharmProjects\squirrel_web\webinterface\webinterface-master\core\views.py", line 283, in post pprint(company.save()) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\base.py", line 808, in save force_update=force_update, update_fields=update_fields) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\base.py", line 838, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\base.py", line 905, in _save_table forced_update) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\base.py", line 955, in _do_update return filtered._update(values) > 0 File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\query.py", line 664, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\sql\compiler.py", line 1204, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\sql\compiler.py", line 876, in execute_sql sql, params = self.as_sql() File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\sql\compiler.py", line 1170, in as_sql val = field.get_db_prep_save(val, connection=self.connection) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\fields\__init__.py", line 770, in get_db_prep_save prepared=False) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\fields\__init__.py", line 1459, in get_db_prep_value value = self.get_prep_value(value) File … -
Is it possible to open a new page (and let the client side see it) using selenium and python on linux server side? (Without --headless option),
I have a code that is running ok on a linux server. On the code, i used Linode, python, django and selenium. I have no problem when using the '--headless option'. opts = FirefoxOptions() opts.add_argument("--headless") Using headless, the code do what is suposed to do. But there is a specific case that i need to open a new page and let the client see it. So i cant use '--headless option'. And i cant figure out a way to do that. Some tips? Is there a way to run selenium and python on a linux server side, without the '--headless' option? -
Django-simple-history how to append extra info/object to historical record?
I'm looking for a way to change extra field in historical record. I have a model Invoice and Balance. class UserBalanceHistoricalModel(models.Model): """ Abstract model for history models tracking the IP address. """ invoice = models.ForeignKey('Invoice', null=True, blank=True, on_delete=models.SET_NULL, verbose_name='Faktúra') class Meta: abstract = True class UserBalance(TimeStampedModel): objects = UserBalanceManager() user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_balance', verbose_name='Užívateľ') balance = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name="Eur na konte") history = HistoricalRecords(bases=[UserBalanceHistoricalModel, ]) class Invoice(models.Model): ... Everytime when Invoice object is created, the UserBalance.balance is modified and historical record is automatically created. I want to add this Invoice object to the historical record but it doesn't work. The invoice_id is None. In [10]: u = User.objects.first() In [11]: i = Invoice.objects.first() In [12]: balance = u.user_balance In [13]: balance.balance = 45 In [16]: balance.history.invoice = i In [18]: balance.save() In [28]: balance.history.all().values_list('invoice_id',flat=True) Out[28]: <QuerySet [None, None, None, None]> Do you know what I'm doing wrong? -
Flask in Docker container access localhost
On my localhost I have a Django application running on port 8000. A Docker compose sets up different containers, among them a Flask application with the config: redirection-service: container_name: redirection-service build: context: "..." ports: - 5000:5000 links: - redis In the flask application I use a requests call to access an endpoint of the Django application on the localhost: backend_url = 'localhost:8000/...' requests.post(backend_url, data={}, allow_redirects=True, verify=False) But I get the error requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /.../ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f4d706f7588>: Failed to establish a new connection: [Errno 111] Connection refused',)) -
Captcha verification Python Django
I am getting Invalid captcha response for below set up. Contact form worked perfectly fine, I added rule that verifies captcha, I checked secret keys and still getting Invalid Captcha even after solving it. Below is my setup: views.py def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def grecaptcha_verify(request): response = {} data = request.POST captcha_rs = data.get('g-recaptcha-response') url = "https://www.google.com/recaptcha/api/siteverify" params = { 'secret': settings.RECAPTCHA_SECRET_KEY, 'response': captcha_rs, 'remoteip': get_client_ip(request) } verify_rs = requests.get(url, params=params, verify=True) verify_rs = verify_rs.json() response["status"] = verify_rs.get("success", False) response['message'] = verify_rs.get('error-codes', None) or "Unspecified error." return response def contact(request): if request.method == 'POST': if grecaptcha_verify(request) == "success": subject = request.POST.get('subject') message = request.POST.get('message') email = request.POST.get('email') if subject and message and email: try: send_mail(subject, message, email, ['myemail@gmail.com'],fail_silently= True) except BadHeaderError: return HttpResponse('{Bad Header}') return greatsuccess(request) else: return HttpResponse('{Invalid Form}') else: return HttpResponse('Invalid Captcha') return render(request, 'personal/contact.html') My template: <div class="form-area"> <form role="form" method="POST"> {% csrf_token %} <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" maxlength="70" required> </div> <br> <div class="form-group"> <input type="email" class="form-control" id="email" name="email" placeholder="Email" required> </div> <div class="form-group"> <textarea class="form-control" type="textarea" id="message" name="message" placeholder="Message" maxlength="300" rows="7"></textarea> </div> <button type="submit" name="submit" class="btn btn-m btn-secondary">Submit</button> <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" … -
how to convert pdf to json in Django
I am trying to pdf file to Json file in Django but I did not get, please any can help me, how to convert pdf to Json file .afer I want to convert Json file to excel file please help me. -
Django, python, redis sorting
I used redis to sort out the most viewed items in a project I am working on. I would like to sort out only the most viewed for the day and out the overall most viewed. In other words, viewing count should restart everyday. Here is my code @login_required def image_ranking(request): image_ranking = r.zrange('image_ranking', 0, -1, desc=True[:110000] image_ranking_ids = [int(id) for id in image_ranking] most_viewed = list(Image.objects.filter(id__in=image_ranking_ids)) most_viewed.sort(key=lambda x: image_ranking_ids.index(x.id)) paginator = Paginator(most_viewed, 24) page = request.GET.get('page') try: most_viewed = paginator.page(page) except PageNotAnInteger: most_viewed = paginator.page(1) except EmptyPage: if request.is_ajax(): return HttpResponse('') most_viewed = paginator.page(paginator.num_pages) if request.is_ajax(): return render(request, 'images/image/ranking_ajax', {'section': 'images', 'most_viewed': most_viewed}) return render(request, 'images/image/ranking.html', {'section': 'images', 'most_viewed': most_viewed}) -
Is it possible to make a PUT request on list view, using ModelViewSets?
My goal is to handle a PUT request that contains multiple jsons. In simple words, I just want to be able to update multiple items with 1 PUT request. I tried to override the update() method in my ModeViewSet, but as I saw in my tests, the following request: (example) response = self.client.put('/collections/', [{'id':1, ...}, {'id':2, ...}]) didn't even go into the update method's code. Instead, it returned a 'method not allowed' error. I looked for this issue and I found out that, by default, drf supports PUT requests only on detail views. I also found this answer here on stack overflow, but I would prefer to see if it can be done without using a 3rd-party package. So, is there a proper solution without using a 3rd party package? Is it possible to make it work using ModelViewSets or should I use something different? -
XMLHttpRequest Synchronous Error in Bootstrap modal and Django
The program open Bootstrap Modal and load Django Form to create new permission, this is works. But when i want in the form add new Ajax call to load dynamically elements in Django ChoiceField appears the error and browser not finish the call never. I open browser inspect console and appears XMLHttpRequest error url.py: path('permisos/', general_views.permission_list,name='permission_list'), path('permisos/crear', general_views.permission_create, name='permission_create'), path('permisos/<int:id>/editar', general_views.permission_update, name='permission_update'), path('permisos/<int:id>/detalle', general_views.permission_detail, name='permission_detail'), path('permisos/<int:id>/borrar', general_views.permission_delete, name='permission_delete'), path('permisos/crear/cargar_elementos/', general_views.permission_load, name='ajax_load_permissions'), never get to call this function from ajax views.py: def permission_load(request): type = request.GET.get('type') if type == 2: # object list = ['general', 'billing', 'accounting'] elements = ContentType.objects.filter(app_label__in=list) elif type == 3: # instance list = ['general', 'billing', 'accounting'] content_type = ContentType.objects.filter(app_label__in=list) elements = general_models.content_type.model.objects.all() elif type == 4: # attribute list = ['general', 'billing', 'accounting'] content_type = ContentType.objects.filter(app_label__in=list) elements = general_models.content_type.model.objects.all() # get instance atributtes else: # module elements = general_models.Modules.objects.all() # other aspect is that i dont know how to load view result in the html choicefield response = { 'element': elements } json = simplejson.dumps(response) return HttpResponse(json, mimetype="text/json") forms.py: class CustomPermisisonForm(forms.Form): name = forms.CharField() ACTION_TYPE = ((1, ('Ver')),(2, ('Añadir')),(3, ('Modificar')),(4, ('Borrar'))) action = forms.MultipleChoiceField(choices=ACTION_TYPE, label='Acciones', initial=1, widget=forms.SelectMultiple()) PERMISSION_TYPE = ((1, ('Módulo')),(2, ('Objecto')),(3, ('Instancia')),(4, ('Atributo'))) type = … -
Django drf requests seem to be restarting when taking a long time
I'm using Django with DRF and I have a viewset that writes info to a csv file and then sends the link to the user. The function works correctly when the data retrieved is not too big, so when the response time is reasonable everything works ok. The problem is when the request takes a longer time. It seems like it simply restarts from the request call all by itself def get_operations(self, request): logger.info("Starting export request...") #[...business logic to retrive the data ...] file_url = settings.MEDIA_PREFIX_PATH + file_path logger.info("Saving response in %s", file_absolute_path) f = open(file_absolute_path, "w+") all_operations = operations.all() i = 0 for operation in all_operations: i = i + 1 #code to show progress in the log if (i / len(all_operations)*1000) % 5 == 0: logger.info("Progress: %d ", (i / len(all_operations)*100)) f.write("%s,%d,%d,%d,%s,%s\n" % (operation.datetime, operation.amount, operation.field2, operation.field3, operation.field5, operation.field6)) logger.info("Response saved, sending link %s", file_url) return Response(file_url) In the log, this is what I'm getting INFO 2018-11-26 11:23:33,525 Starting export request... INFO 2018-11-26 11:23:34,223 Response retrieved : 17010 records INFO 2018-11-26 11:23:34,225 Saving response in /tmp/generated_csv/1543231414.2250094.csv INFO 2018-11-26 11:23:42,825 Progress: 10 INFO 2018-11-26 11:23:51,161 Progress: 20 INFO 2018-11-26 11:23:59,072 Progress: 30 INFO 2018-11-26 11:24:07,694 Starting export request... INFO … -
Moving HTML Forms Over To Django 2.1
I have a number of forms for a website which have been prewritten. I am required to keep these as they are and not modify them. I am also required to move these to a Django 2.1 back end, which appears to have a built in form generation system, which doesn't appear to be compatible with the forms in themselves (I.E. The Jinja Scripting for forms appears to auto generate the forms without having any real choice in the matter). I cannot find any documentation on how to move pre existing forms into Django, and I have no idea how. Thanks for helping me. -
Django update all Users field Decimal
from decimal import Decimal from apps.main.models import User from django.db.models import F User.objects.all().update(freeze_balance=F('freeze_balance') + Decimal(F('balance') / 8300)) ERROR -> TypeError: conversion from CombinedExpression to Decimal is not supported How to write an ORM request (sorry for bad English) -
djngo form contains ">" symbol at the beginning , how to remove it?
> Username* Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. screenshot of the page : screenshot -
Which cloud is best for open edX
I want to deploy my open edX devstack. I just want which cloud is best for open edx and why? AWS or Azure. -
Checkout process for django-oscar is not working properly
I have created a eCommerce site using django oscar. When i click on proceed to checkout, after filling shipping address it redirect directly to /checkout/preview/ page it is not going to /checkout/payment-details/ do i need to do any changes in settings or code. -
ImportError at / when deploying application to Azure Cloud
I have a boilerplate application, that I wanted to deploy on Azure. Locally it runs fine, but when I deploy to Azure cloud, I get: ImportError at / cannot import name 'views' from 'eve' (unknown location) I tried changing the import to my eve app.. but I get same error. Here is my traceback: http://dpaste.com/3Q23GMD -
Problems connecting Django project to Oracle
I'm working on PyCharm on a django project version 1.11. I set up the credentials in settings.py: 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xe', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': '000.000.000.000', 'PORT': '1521', Obviously not those are not the real credentials. The fact is that PyCharm is already connected to the database, i can see the tables, create new ones etc with the Database Navigator of PyCharm. However, when I try to start the server of django I get this error: error in Terminal Moreover, I already have Instant client installed, I'm working on Mac OS Mojave I would really appreciate if you can help me -
Django asymmetric relationship: return intersect
I'm using Django 2.1.3 with Python 3.6.6. I have two models, a custom User model and a Connection model to track relationships between users, defined as follows: from django.db import models from django.contrib.auth.models import class User(AbstractUser): # (additional fields) connections_sent = models.ManyToManyField( 'self', through='Connection', # through_fields=('from_user', 'to_user'), related_name='connections_received', symmetrical=False, ) def __str__(self): return self.email def add_connection(self, user): connection, created = Connection.objects.get_or_create( from_user=self, to_user=user, ) return connection def remove_connection(self, user): Connection.objects.filter( from_user=self, to_user=user, ).delete() return class Connection(models.Model): from_user = models.ForeignKey(User, related_name='from_users', on_delete=models.CASCADE) to_user = models.ForeignKey(User, related_name='to_users', on_delete=models.CASCADE) class Meta: unique_together = ('from_user', 'to_user') def __str__(self): return "Connection from {} to {}".format(self.from_user, self.to_user) The idea is that (similar to LinkedIn), Users can send connection requests to other users (connections_sent), which the receiving user must confirm before further interaction can occur. I would like to define a function User.get_confirmed_connections(self) which filters connections_sent so that only confirmed connections are returned. I.e. it should return the intersect between connections_sent and connections_received. Can this be done with filters? -
success url to the current url
Im using django class based view and forms.I want the view to stay on the same page after a new message has been submitted. The url is like localhost:8000/chat/messages/username/ where 'username' is the username of the user to which the message is being sent class ThreadView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'thread.html' form_class = ComposeForm success_url='/' def get_queryset(self): return Thread.objects.by_user(self.request.user) def get_object(self): other_username = self.kwargs.get("username") obj, created = Thread.objects.get_or_new(self.request.user, other_username) if obj == None: raise Http404 return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): thread = self.get_object() user = self.request.user message = form.cleaned_data.get("message") ChatMessage.objects.create(user=user, thread=thread, message=message) return super().form_valid(form) Rn now if i give success_url='./' Its going to locahost:8000/chat/messages/ which results in a 404 error -
Django Crispy forms not using bootstrap 4 to build Accordion
I'm using crispy-forms app for django to bootstrap forms. I'm using bootstrap 4 have no problems when just using the {form|crispy} output but now I want to add an accordion and crispy is generating the HTML for bootstrap 3 instead of 4. I've included in the settings.py the line: CRISPY_TEMPLATE_PACK = 'bootstrap4' My view.py looks like this: from app.models import Model1 from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit from crispy_forms.bootstrap import Accordion, AccordionGroup class Model1Create(CreateView): model = Model1 fields = ['field1', 'field2', 'field3'] template_name = "model1_form.html" def get_form(self, form_class=None): form = super().get_form(form_class) form.helper = FormHelper() form.helper.add_input(Submit('submit', 'Creates', css_class='btn-primary')) form.helper.layout = Layout( Accordion( AccordionGroup('First Group', 'field1' ), AccordionGroup('Second Group', 'field2', 'field3' ) ) return form Any ideas why this is happening? Or what should I do to force bootstrap 4 html? Thanks in advance for the help! -
Issues to fully delete a hash key in redis
i'm using Redis with Python and Django and i have some trouble with the delete of Redis. I create hash key to store multiple informations about a vehicule, but the user is finished with it, i'm deleting the key with : r = redis.StrictRedis(host=settings.REDIS_AD, port=settings.REDIS_PORT, db='14') key = 'TEST_GMA' r.delete(key) Most of the time the hash gets deleted, but sometimes it only erase part of the hash and i don't understand why since it seem to be very random. -
how can i get username when he/she signup in django?
i want the username when the user signUp class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' i need to access the username of the user who has been signed up .