Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically creating a dictionary in python
I want to dynamically build a dictionary based on the string. I have 5 strings: ABC ABC BCD DEF ABC BCD FGH ABC BCD FGH IJK ABC DEF GHI I want to create this into a dict: dict = { "ABC" : { "BCD": {"DEF": {}, "FGH":{IJK}}, "DEF": {"GHI"}, } } This is what I have tried so far, but I'm not sure how to create the new key if there is a key error. # orgs = list of string from about for org in orgs: org_path_sp = org .strip().split() org_cur = org_dict for org_el in org_path_sp: try: org_cur = org_cur[org_el.strip()] except KeyError: pass # create the new entry -
Override save() method does not update the record
It's about a model which I added a new field that intend to update automatically, but it does not work. This is the part of the model involved: class ExpedienteDPI(): folio = models.CharField(max_length=13) fecha_tramite = models.DateField(null=True, blank=True) fecha_notificacion_aclaracion = models.DateField( 'TRÁMITE: Notificación', help_text='Fecha de notificación de aclaración al ciudadano AC', null=True, blank=True ) # muchos campos mas # Siguen solo campos calculados delta_notificar = models.SmallIntegerField( help_text="Delta entre tramite y notificación", editable=False, null=True ) completo = models.PositiveSmallIntegerField(editable=False, null=False, default=0) This model overwrites the model's save() method to do some calculations in order to fill fields that are not editable, including completo. def save(self, force_insert=False, force_update=False): self.delta_notificar = delta(self.fecha_tramite, self.fecha_notificacion_aclaracion) # Muchos campos calculados if self.entidad == 29 and \ self.fecha_tramite and \ self.fecha_entrevista and \ self.fecha_envio_expediente and \ self.fecha_notificacion_aclaracion: self.completo = 1 else: self.completo = 0 super(ExpedienteDPI, self).save(force_insert=False, force_update=False) In this example, the save () method works as expected for the delta_notifcar field calculating the difference between two dates, but it does not work for thecompleto field. I have tested the conditions of completo in a Django's shell, with this: for x in ExpedienteDPI.objects.all(): if x.entidad == 29 and \ x.fecha_tramite and \ x.fecha_entrevista and \ x.fecha_envio_expediente and \ x.fecha_notificacion_aclaracion: if … -
django redirected view not rendering
I defined the following views from django.shortcuts import render, redirect, HttpResponse from .forms import UploadFileForm from .models import LoadedData def loaded_data(request): return HttpResponse("File successfully uploaded") def collect_data(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): instance = LoadedData(data=request.FILES['file']) instance.save() return redirect('loaded_data') else: form = UploadFileForm() return render(request, 'pages/app_load_data.html', {'form': form}) But for some reason the the view loaded_data doesn't display anything. It simply stays on the same page after saving the file into the database, What I am doing wrong here? -
Why it is failed when I want to use web application by Django models.ForeignKey to get data connection?
(ll_env) C:\jiaguo\learning_logs>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, learning_log, sessions Running migrations: Applying learning_log.0003_entry_topic...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\migrations\migration.py", line 122, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards field, File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 306, in add_field self._remake_table(model, create_field=field) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 178, in _remake_table self.effective_default(create_field) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\backends\base\schema.py", line 240, in effective_default default = field.get_db_prep_save(default, self.connection) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\models\fields\related.py", line 936, in get_db_prep_save return self.target_field.get_db_prep_save(value, connection=connection) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\models\fields\__init__.py", line 767, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\models\fields\__init__.py", line 939, in get_db_prep_value value = self.get_prep_value(value) File "C:\jiaguo\learning_logs\ll_env\lib\site-packages\django\db\models\fields\__init__.py", line 947, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' -
Django form with inline/nested data
I'm trying to create an editor for a question whereas the question can have multiple files associated with it. I've tried to get it to work with inline_formsets but I can't seem to get it working properly. models.py def Question(models.Model): title = models.CharField('Title', max_length=200) ... def AdditionalData(models.Model): question = models.ForeignKey(Question, related_name='additionalData`, on_delete=models.CASCADE) upload = models.FileField('Data', upload_to=...) forms.py class QuestionForm(forms.ModelForm) class Meta: model = Question fields = '__all__' # for example purposes only AdditionalDataFormset = forms.inline_formset_factory(models.Question, models.AdditionalData, fields=('upload',), extra=1) views.py class EditQuestion(DetailsView): def get(request, pk, **kwargs): question = get_object_or_404(Question, pk=pk) question_form = QuestionForm(instance=question) additional_data_formset = AdditionalDataFormset(instance=question) context = { 'question_form': question_form, 'additional_data_formset': additional_data_formset } return render(request,'editor.html', context) Lastly, part of my template editor.html <form method="post" action='url...'> {% csrf_token %} <fieldset> {{ question_form|crispy }} </fieldset> {{ additional_data_formset.management_form }} {{ additional_data_formset.non_form_errors }} <fieldset> {% for additional_data in additional_data_formset %} {{ additional_data|crispy }} {% endfor %} </fieldset> <button type="submit" class="save btn btn-default" value="Submit">Submit</button> </form> For some reason when I'm using inline formsets the "Submit" button does not work (nothing happens when I click it). When I attempt to force submit the form (via jquery onclick submit button) this error is thrown: 'ManagementForm data is missing or has been tampered with' I can't seem to … -
django-angular example error
We hope this thread will help users running the django-angular package for Python. At the moment, we are following the example: django-angular We are able to get the demo running, but have an error loading some of the static files. The creator of the package is saying this is related to Django, and not the package its self, even though we are running the example "out of the box" without making changes. Here is the error: And what we see: The example should look like this: working example What we have tried: At the moment, all dependencies including angular have been installed. We're thinking maybe something isn't mapped correctly in the urls.py file. Any advice would be appreciated, and hopefully this thread will help others using this package. -
set_cookie with authtoken for redirect does not work Django React
This question regards both Django and React. I need to redirect to the react part of my website and would like to keep the user logged in. I try to do so by finding their token.key, setting it as a cookie and redirecting them to the react URL. This is my transfer view in Django: def transfer(request): token = Token.objects.get(user_id=request.user.pk) response = redirect(event_listing_link) token_name = 'authTok' token_value = token.key response.set_cookie(token_name, token_value) return response I get the correct token value (I tested with Postman), the event_listing_link works, and I get no server errors. However, my cookie.load("authTok") call in React does not seem to work. This is my React code to load the cookie and try a call with permissions: export function getEventListings() { return (dispatch, getState) => { const state = getState(); const tok = cookie.load("authTok"); dispatch({ type: Constants.GET_EVENT_LISTINGS }); return api.getEventListings(tok) .then(response => { ... }) .catch(err => { alert("It appears as though your session has expired"); console.log("error is " + err) history.push("/") }); } } I get the alert "It appears as though your session has expired" every time. Note: I think it's something wrong on the backend because I have a normal React login option which loads the … -
GET request in Django
I have a doubt. When is a GET request sent. I mean, I have seen a lot of people using if request.method == 'GET', when they render the form for the first time, but when the form is submitted, they do a `POST' request. While they explicitly mention when defining the form in html that the method will be 'POST', they don't do the same for 'GET' request which is made when an empty form is requested. How does django know it's a GET request? And, why is it done so? Thanks, -
How to use multiple django-markdownx editors on the same page?
I have followed http://neutronx.github.io/django-markdownx/js/docs/markdownx.html#MarkdownX docs but can't get it done properly. What is the correct way to setup two or more editors in the same page? -
How can I use Django.db.models Q module to query multiple lines of user input text data
How would I go about using the django.db.models Q module to query multiple lines of input from a list of data using a <textarea> html input field? I can query single objects just fine using a normal html <input> field. I've tried using the same code as my input field, except when requesting the input data, I attempt to split the lines like so: def search_list(request): template = 'search_result.html' query = request.GET.get('q').split('\n') for each in query: if each: results = Product.objects.filter(Q(name__icontains=each)) This did not work of course. My code to query one line of data (that works) is like this: def search(request): template = 'search_result.html' query = request.GET.get('q') if query: results = Product.objects.filter(Q(name__icontains=query)) I basically just want to search my database for a list of data users input into a list, and return all of those results with one query. Your help would be much appreciated. Thanks. -
SMTPServerDisconnected at /blog/mail/
views.py from django.core.mail import send_mail def send(request): subject = 'hi' message = 'hello' from_emaill = 'chidanandanayak06@gmail.com' recipiant_list = ['chidanandanayak06@gmail.com','shuryansh.hot@gmail.com'] send_mail(subject,message,from_emaill,recipiant_list) return render(request,'mail.html') urls.py path('mail/',views.send, name= 'sendmail') My server EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'chidananda' EMAIL_HOST_PASSWORD = '**********' EMAIL_POST = 587 EMAIL_USE_TLS = True I dont know why its abnormally getting disconnected! Same thing happening with another project also. -
Django Rest Framework Disable CORS
I have a Django Rest Framework API that I need to restrict to only accept requests from a single host. I've tried installing django-cors-headers with the settings below but the API still accepts requests from any host. Settings: CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'mydomain.com', ) CORS_ALLOW_METHODS = ( 'GET', ) Example DRF Endpoint: @api_view(['GET']) @permission_classes([AllowAny]) def test_endpoint(request): ... return response Is the AllowAny permission class the issue? If so, how would one restrict access to this endpoint? -
Openshift Find Static Files From Django App
I am trying to add a css file to my django application which I am deploying on openshift. Currently, I am able to have the css file work when running locally with debug and all that. However, when I deploy my application to openshift, the css file does not have any effect. Many of the other questions online seem to be referring to old versions of django and openshift (lots of references to a wsgi folder that doesn't seem to be standard anymore and triggering collectstatic manually) My understanding with the current django/openshift relationship is that I do not need to do collecstatic manually as I am using the django-ex template from openshift, and during the build process the collectstatic command is run automatically, the ouput of which I can see in the logs. Notably, I can see that my style.css file for my application gets copied into STATIC_ROOT in that log. My project structure from my project root is thus: . ├── db.sqlite3 ├── djangoWrapper │ ├── __init__.py │ ├── settings.py │ ├── templates │ │ └── djangoWrapper │ │ └── index.html │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── gitlab-ci.yml ├── ldap │ ├── admin.py │ … -
Model not getting updated in django
active = request.POST['isactive'] if active == 'True': user_profile.user.is_active = False elif active == 'False': user_profile.user.is_active = True user_profile.user.save() Hi, I am trying to update user status over a toggle button; user status gets updated in the database but does not reflect on User Interface.Have also tried transaction commit but no luck. Please help with a solution to solve this issue Thank you! -
django admin stops working after django-modeltranslation sync_translation_fields
I have a Django project with some models already created, and I want to incorporate django-modeltransalation on them. I installed the module and created the translation.py in one of the apps and ran python manage.py sync_translation_fields, and everything seemed to be fine, but django admin tool stoped working and rises this error for the only translated model: Something's wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user. And with all other models of the same application I get this error: TypeError: _clone() got an unexpected keyword argument '_rewrite' [18/Jun/2018 16:25:50] "GET /es/admin/GeneralApp/airport/ HTTP/1.1" 500 394793 The admin tool works fine with other applications. -
An error when the Django connect to Mysql with mysqlclient
The fellow are details, someone can help, thanks in advance. enter image description here enter image description here -
How to save the current User in models while posting?
How to save the current User in models while posting? class Post(models.Model): author = models.ForeignKey('auth.User') #Please tell me how to save the current user here title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse("post_detail", kwargs={'pk': self.pk}) def __str__(self): return self.title -
in python, is the function that its name is full-uppercase different from the common function?
in python, is the function that its name is full-uppercase different from the common function? just like "django.db.models.CASCADE": def CASCADE(collector, field, sub_objs, using): collector.collect(sub_objs, source=field.remote_field.model, source_attr=field.name, nullable=field.null) if field.null and not connections[using].features.can_defer_constraint_checks: collector.add_field_update(field, None, sub_objs) -
Are WGSI and non-WSGI Django apps designed/written differently?
I'm new to Python and Django. This is a very basic question, but I can't find a straight answer: When writing my Django app, do I have to design the app itself differently if it's going to support WSGI? In other words, is WSGI purely a deployment decision, or does the app itself have to support WSGI by design? Can I just write an app without thinking about whether it's WSGI or not and flip a WSGI switch later on, or does WSGI stuff go deeper? -
request.FILES empty uploading image on Django
Here is my HTML sending the request, printing request.FILES return <MultiValueDict: {}>. Also i would ask how can i save my charged picture (is ok to only form.save()?) <form action="send_news" method="POST" encrypt="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <p> <label for="news_title">Your name: </label> <input id="news_title" type="text" name="news_title" value="newtitle"> </p> <p> <label for="news_small_description">Your name: </label> <input name="news_small_description" id="news_small_description" value="news_small_description"> </p> <p> <label for="news_description">Your name: </label> <input name="news_description" id="news_description" value="news_description"> </p> <p> <label for="news_image">Your name: </label> <input id="news_image" type="file" class="" name="news_image"> </p> <input type="submit" value="Submit" /> </form> And here is my API in my views.py: @api_view(['POST']) def send_news(request): print(request.FILES) form = NewForm(request.POST,request.FILES) if form.is_valid(): newstitle = form.cleaned_data['news_title'] newssmalldescription = form.cleaned_data['news_small_description'] newsdescription = form.cleaned_data['news_description'] newsimage = form.cleaned_data['news_image'] form.save() return HttpResponse('home') my forms.py : class NewForm(forms.ModelForm): class Meta: model = New fields = ('news_title', 'news_small_description', 'news_description','news_image',) and my models.py: class New(models.Model): news_title = models.CharField(max_length=100,blank=False,verbose_name="Titolo news") news_small_description = models.TextField(default=None,null=True,blank=True,verbose_name="Descrizione breve") news_description = models.TextField(default=None, null=True, blank=True, verbose_name="Descrizione") news_image = models.ImageField(default=None, blank=True, null=True, verbose_name="Immagine") news_date = models.DateTimeField(auto_now=True, null=True, verbose_name="Data news") class Meta: verbose_name = "New" verbose_name_plural = "News" printing request.FILES return <MultiValueDict: {}>. Also i would ask how can i save my charged picture (is ok to only form.save()?) -
Django + MongoDB - Best setup approach to handle heavy load
I created a User management API. Below are current implementation settings for my project setup.. django==1.9 djangorestframework==3.3.3 mongoengine==0.9 pymongo==2.7 django-rest-framework-mongoengine I want to use latest Django but mongoengine does not support it. I read somewhere, to use Djongo and looked into the details of it, but I have few questions. My APIs are being consumed by a booking website's frontend, hence the load will be huge. Will Djongo be able to handle that? My current code is written in a way to use mongoengine, which means that use model is improvised. Do I have to change the code to consume Djongo? How effective is Djongo as compared to mongoengine? Is there another way to achieve this objective? People who have used Djongo, can you please help me? -
Deploying a server-less Django app?
Originally the requirements were to have an outward facing application and we were going to use a server. However, now all the code is done and long term vision has changed... The requirements are to have an inward facing application without a server (physical or remote). The team that will be using the application will be 5 users on the same network and each is to have the app individually installed on their desktop. My question is what is the best way to deploy this application to everyone's machine as a package they can easily install themselves. How can the application always be running on everyone's machine without typing python manage.py runserver? -
Django profiling tests
So I found this article from 2016 detailing how to create a custom test runner that captures the time it takes to run tests in Django: runner.py: from unittest.runner import TextTestResult from django.test.runner import DiscoverRunner import time class TimeLoggingTestRunner(DiscoverRunner): def __init__(self, slow_test_threshold=0.0, *args, **kwargs): self.slow_test_threshold = slow_test_threshold return super().__init__( resultclass=TimeLoggingTestResult, *args, **kwargs, ) def run(self, test): result = super().run(test) self.stream.writeln( "\nSlow Tests (>{:.03}s):".format( self.slow_test_threshold)) for name, elapsed in result.getTestTimings(): if elapsed > self.slow_test_threshold: self.stream.writeln( "({:.03}s) {}".format( elapsed, name)) return result def get_resultclass(self): return TimeLoggingTestResult class TimeLoggingTestResult(TextTestResult): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_timings = [] def startTest(self, test): self._test_started_at = time.time() super().startTest(test) def addSuccess(self, test): elapsed = time.time() - self._test_started_at name = self.getDescription(test) self.test_timings.append((name, elapsed)) super().addSuccess(test) def getTestTimings(self): return self.test_timings settings.py: TEST_RUNNER = 'core.utils.test_runner.runner.TimeLoggingTestRunner' However, nothing prints at the end. I know the code runs, because debug statements fire in both classes - but the actual end result (run) doesn't appear to get called. What I have managed to do is get the timings to print (by adding print statements inside TimeLoggingTestResult), but I can't seem to get them to all print out at the end. Does anyone have any experience with doing something like this? The run method doesn't … -
Restrict User from view based on existing model
I have a few really simple views in my views.py. class IndexView(generic.ListView): template_name = 'voting/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Poll.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Poll template_name = 'voting/detail.html' context_object_name = 'question' def get_queryset(self): """ Excludes any questions that aren't published yet. """ return Poll.objects.filter(pub_date__lte=timezone.now()) class ResultsView(generic.DetailView): model = Poll template_name = 'voting/results.html' context_object_name = 'question' I also have created a model where I store which users are invited to which polls along with some other data. class EligibleVoters(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) poll = models.ForeignKey(Poll, on_delete=models.CASCADE, null=True) encrypted_keypart = models.BinaryField(max_length=200, blank=True) decrypted_keypart = models.BinaryField(max_length=200, blank=True) class Meta: unique_together = ["user", "poll"] I want to restrict users that aren't invited to a poll from seeing any of these polls. I think that what I want to do is something like this for each view, but I'm not sure if that's the correct way to go. class DetailView(generic.DetailView): model = Poll template_name = 'voting/detail.html' context_object_name = 'question' def get_queryset(self): """ Excludes any questions that aren't published yet. """ if EligibleVoters.objects.filter(poll=Poll.objects.id, user=self.request.user.id).exists(): return Poll.objects.filter(pub_date__lte=timezone.now()) else: return render('voting/somethingsomething.html') }) Should I … -
Login Django 2.0, autentfcação
Bom dia, Estou tentando realizar uma pagina de login, porem estou encontrando algumas dificuldades. Por algum motivo que não consigo entender, toda vez que eu digito o usuário e a senha, estando certo ou não, ele da a resposta que o usuário não existe. views.py Forms.py models.py Tela de login