Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Receive Data From a Django Form Using a POST Request and render on Html template
How to Receive Data From a Django Form Using a POST Request and render on html template. My view code is: def my_drive_fun(request): if request.method =='POST': form=my_drive_module(request.POST) if form.is_valid(): Production_Drive = form.cleaned_data['Production_Drive'] work_drive = form.cleaned_data['work_drive'] show_name = form.cleaned_data['show_name'] show_sup = form.cleaned_data['show_sup'] show_coor = form.cleaned_data['show_coor'] glow_project="Projects"+show_name pro_drive_path=Production_Drive+":"+"\\" wor_drive_path = work_drive + ":" + "\\" #text=form.cleaned_data['post'] print("Production_Drive:",Production_Drive,"Work Drive:",work_drive,show_name,show_sup,show_coor,pro_drive_path,wor_drive_path) form=my_drive_module() drive_data={'form':form} return render(request,'my_drive.html',drive_data) -
Table doesn't exist in django
I'm trying to send data from a form to a database using this model, but i keep getting this error: ("Table 'trades.main_trade' doesn't exist") Here is my model: class SomeModel(models.Model): data = models.CharField(max_length=100) def save(self): super(SomeModel, self).save(using='dataset') And here is my form: class DataForm(forms.ModelForm): class Meta: model = Trade fields = ("data",) def save(self, commit=True): send = super(SomeModel, self).save(commit=False) if commit: send.save() return send I already tried this but it's not working: when i got to step 3, in fact, i got the error table "main_SomeModel" already exists What am i doing wrong? Should i migrate again? -
Model.objects returns django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor
When querying objects from one of my models I cannot access the usual methods like "filter" or "get" or "all". It returns the error: AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'all' This is the model with the problem: class Job(models.Model): DEFECT = 'FIX' ENHANCEMENT = 'ENH' DEVELOPMENT = 'DEV' TYPE_CHOICES = ( (DEFECT, 'Defect Resolution'), (ENHANCEMENT, 'Enhancement'), (DEVELOPMENT, 'Major Development'), ) job_number = models.IntegerField() job_type = models.CharField(max_length=3, choices=TYPE_CHOICES) summary = models.TextField() reason = models.TextField() functional_description = models.TextField(null=True) regression_testing = models.TextField(null=True) This is another model in the same application that doesn't have the problem: class Release(models.Model): name = models.CharField(max_length=10) live = models.DateField(null=True) -
How best to work with Django database from another Docker container?
So I'm building a tool using Docker Compose and Django. I have an app container running Django and a database container running a MySQL database. I want to add a third container, which will run a data collection script, with the intention of inserting that data into the database. It's straightforward enough to insert the data directly using queries, but I'd rather be using the Django ORM for ease-of-use, consistency, and so that Django signals etc. are being fired correctly. What's the most sensible way for this data collection script to run while making use of the Django ORM to save the data? Should I just be running the data collection process in the Django container? -
How to set the value of a field when creating a user, based on the value of the current user
I'm creating a form where users can register additional users, and I need to automatically pass the foreign key (organization) of the current user to the new user being created. I'm relatively new to Django, but I believe the issue is with the following line in the forms: "user.organization = self.instance.organization" Model class Organization(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) city = models.CharField(max_length=255) state = models.CharField(max_length=255) zip = models.CharField(max_length=255) class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) organization = models.ForeignKey(Organization, on_delete=models.CASCADE, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.CASCADE, blank=True, null=True) user_type = models.CharField(max_length=255, choices=(('org_admin', 'Admin'),('org_user','User'),('client_admin','Client Admin'),('client_user','Client User'))) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() View def register(request): if request.method == 'POST': form = UserOrgCreationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') messages.success(request, f'User has been created') # return redirect('login') else: form = UserOrgCreationForm() return render(request, 'users/register.html', {'form': form}) Form class UserOrgCreationForm(UserCreationForm): password1 = None password2 = None class Meta: model = User fields = ('email', 'first_name', 'last_name', 'user_type') def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_unusable_password() user.organization = self.instance.organization if commit: user.save() return user I need the new user to inherit the organization of the current user. -
Weird parsing json response via django-template
I am trying to parse json response from get request to rest api. Let me show you what i mean "weird". My views.py def about_abc(request, host_id): response = requests.get( 'abc.net:1768/abc/api/v1/about', verify='cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxxx'}, ).json() context = {'response': response} return render(request, 'itpassed/about.html', context) now, when i put i template about.html {{ response }} in web-browser i get normal, not parsed response (at least it looks like this) {'version': '3.3.2', 'level': 'SP2', 'system': 'unix', 'server_time': '1556275198000', 'server_utc': '2', 'multinode_enabled': 'NO', 'cg_enabled': 'NO', 'instance_id': 'hostname'} but when i put in about.html {% if response %} {% for id in response %} <p>{{ id }}</p> {% endfor %} {% else %} <p>No IDs are available.</p> {% endif %} i get ids without values: version level system server_time server_utc multinode_enabled cg_enabled instance_id According to what i see in browser with only {{ response }} in template, whole response is passed (ids and their values). How to parse this to look more or less like this: version: 3.3.2 level: SP2 system: unix server_time: 1556275198000 server_utc: 2 multinode_enabled: NO cg_enabled: NO instance_id: hostname -
How to override an objects dot access for a specific column in Django?
Say I have a Django object that I have filtered like so: details_obj = DetailsTable.objects.get(user_name='nap') details_obj.user_name 'nap' details_obj.city 'Paris' details_obj.age 22 Now what I want to do is override the access for one specific column to achieve something like: # if a new city exists in a different table if updated_city_exists: # return the updated city instead return 'London' else: # the usual flow that currently exists in Django return obj.city # is user accesses city like details_obj.city 'London' # London returned here as updated city exists for this user I can't really modify the model of the existing DetailsTable due to it being pre-existing code that has been used a lot of times. Also there are lots of places in the code where dot access for city is already taking place. So I would like to override the existing method to access the column value. I also don't want to update the city column in the existing DetialsTable column. Is there anyway I can achieve this? The only thing I could think of was to write a function would return updated city if it exists and use this function everywhere but I will have to replace a lot of … -
Scheduling task from admin Panel in Django
I want to schedule a task in Django which would run at a paticular time every day.Is there anyway I could pass the time at which I want to execute the task from django admin panel?Any help would be appreciated(examples especially). -
Clean an InlineFormset based on data located in others forms in the same view
I am working on a project where I have those 3 models: class Loan(models.Model): ... drawdown = models.OneToOneField('Drawdown'...) amount = models.DecimalField(max_digits=19, decimal_places=2) ... class Drawdown(models.Model): ...(some fields like the drawdown_type) class Tranche(models.Model): drawdown = models.ForeignKey(Drawdown, related_name='tranches') amount = models.DecimalField(max_digits=19, decimal_places=2) ... In a LoanCreateView I am abble to create a new Loan using a ModelForm, I also pass to the context a Drawdown ModelForm and another InlineFormset to handle the Tranche corresponding to the drawdown. For the context: A loan have a amount eg :150k, but the borrower want it like: 50K then 100K. We have now a loan amount of 150k with 2 tranche (50k and 100k) It's working great so far. I need to be abble to check that the total of amount in Tranche Formset are equal to the loan amount. I end up with this solution wich works, but I feel like it's looking messy: class TrancheBaseInlineFormset(forms.BaseInlineFormSet): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request", None) super(TrancheBaseInlineFormset, self).__init__(*args, **kwargs) def clean(self): #get the post request and get the loan amount loan_amount = (self.request.POST.get('amount')) #sanitize a little bit this try: loan_amount = int(strip_tags(loan_amount)) except ValueError: loan_amount = loan_amount.replace('€','').replace('£','').replace(',','').replace('.','') loan_amount = int(strip_tags(loan_amount)) total_amount = 0 for form in self.forms: … -
Pass ID of object from django model
Here is my test def someTest(self): # create an object sampleModel.objects.create(unique_id='999999') # add code here to pass the sampleModel object created above to view:page1 # Make sure the sampleModel object created appears in page 1 response = self.client.get(reverse('view:page1')) # check that above created mlab appears self.assertEqual(response.status_code, 200) How can I modify my test to check that the sampleModel object created appears in view:page1 ? The goal of the test to check if created objects appear in page1. Here is my urls.py path('<int:pk>/', views.sampleView.as_view(), name='page1'), -
How to use Hashicorp Vault
How can I use Hashicorp Vault to store credentials and to display them on a web page generated by Django only when the user is allowed to view them. The main idea is to enter username and password into Vault to access servers and to make them available in an existing web interface built with Django. I know lots of systems integrate their own password vault to be able to decrypt credentials only with a specific user key. How can Vault compare to this? I'd like to use Vault as it might also be integrated later with Ansible for example to automate tasks. The main point is not to replace secrets in Django configuration files, but to store privileged access credential sets of different severs. Someone can point me to a documentation on how to use Vault that way or will it make more sense to implement my own vault in Django and have user keys decrypting the creds? Probably there are other solutions which might fit better into what I'd like to achieve? All hints are warmly welcome and thank you in advance for commenting the topic. -
'decimal.DivisionUndefined' error thrown when creating model before children models
When I try to create a model that uses children models before making these children models, I keep getting error: class 'decimal.DivisionUndefined'. I do not understand why this error is being thrown or how to resolve it. class Parent(models.Model): title = models.CharField(max_length=200, unique=True) description = models.TextField() sub_value1: DecimalField = models.DecimalField(max_digits=11, decimal_places=2, null=True) class Meta: @property def children(self): children = [] for child in Child.objects.all(): if child.parent_id == self.id: children.append(child) return children @property def main_value(self): try: main_value = self.sub_value1 / self.sub_value2 return round(main_value, 2) except ZeroDivisionError: return 0 except TypeError: return None @property def sub_value2(self): local_sub_value2 = 0 for child in self.children: local_sub_value2 += child.sub_value_2_of_child return round(local_sub_value_2, 2) When I create this model without any children created yet, I expect the children property to return an empty array. Therefore sub_value2 should be 0, therefore main_value should throw a ZeroDivisionError which I am handling. However, I keep getting the following error from django: [<class 'decimal.DivisionUndefined'>] Why does this happen and how can I fix this? -
convert a numeric value to its name
I'm developing a web-application of prediction(machine learning), using django. I used the linear regression model because I have to predict a quantitative variable "sales", and I have in the entries of data a dummy variables , so I code them with handle_non_numerical_data (). the problem is at the level of entering entries in the application by user I must use the name and not their covertion to numeric. any solution? -
How to generate link for file download?
I created a model without using FileField() and saved the url into path field. Now while displaying I can see the attributes but I cannot download the file. href treats it as a page and i get an error saying GET request failed. I need to do the same for static files also. models.py looks like this: import os from django.conf import settings from django.db import models # Create your models here. class Document(models.Model): code = models.CharField(max_length = 50) path = models.CharField(max_length = 500) date_of_submission = models.CharField(max_length = 50) type = models.CharField(max_length = 50) title = models.CharField(max_length = 200) department = models.CharField(max_length = 50) subject = models.CharField(max_length = 100) updation_allowed = models.CharField(max_length = 1, default = '0') @property def relative_path(self): return os.path.relpath(self.path, settings.MEDIA_ROOT) template has some code like this: <a href = '{{ MEDIA_URL }}{{ value.thesis.relative_path }}'> Thesis </a> *static files* <a href='/uploads/report.pdf'> Front Page</a> I tried using the property and provinding the path myself. -
AttributeError: 'SQLiteCursorWrapper' object has no attribute 'callproc'
In my Django Application, I started using SQLite in an app heavily developed under MySQL. I actually swapped to SQLite because I was having issues with MySQL. However, the most important thing is to make this work so I can submit my task, but the error I am getting is AttributeError: 'SQLiteCursorWrapper' object has no attribute 'callproc'. Bellow is my settings in settings.py. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Any help will be appreciated. Thanks -
Call a function that is in seprate py file on Button click
I have a file named Database.py containing a class for Postgres. I am also using 4 textboxes to take input as credentials to connect to Postgres. I want to call a function from Postgres when I enter the credentials and submit them using a button click. -
render scrape data in browser without storing in database
Is there any way to render the scrape data in the browser without storing in database. I am using BeautifulSoup for scraping the data in my Django project. image 1 showing code for scraping the data about mobile phone image 3 code to render data in browser image 3 data showing in browser -
how can I solve csrf verification failed
I'm trying to create form that uploads a zip file to the server. But everytime I click the submit I keep getting CSRF verification failed error. This is my html code: <form method="POST" name="form-import-file" enctype="multipart/form-data"> <div> <input type="file" id="file" name="file" accept=".zip"/> <input type="submit" value="Upload file"> </div> </form> <div class="url-csrf" data-csrf="{{ csrf_token }}"></div> <div class="url-import-file" data-url-import-file="{% url 'intent:import_file' %}"></div> In my .js code: $("form[name='form-import-file']").submit(function(e) { var formData = new FormData($(this)[0]); alert(formData); var json_data = {'csrfmiddlewaretoken' : $('.url-csrf').attr('data-csrf'), 'file': formData }; $.ajax({ url: $('.url-import-file').attr('data-url-import-file'), type: "POST", data: json_data, success: function (msg) { alert(msg) }, cache: false, contentType: false, processData: false }); e.preventDefault(); }); -
Create authenticated user for django tests
The reason I am asking is I have the fields username,password and otp_token. The otp_token is challenging to create, therefore I was wondering if there is a way create an authenticated user at the beginning of the test file to carry out the rest of the django tests as an authenticated user? related question -
Fake a locale field for model testing
I simply have a collection of languages in a model like this: from django.conf.global_settings import LANGUAGES class AvailableLanguage(models.Model): code = models.CharField(choices=LANGUAGES, unique=True) In factories.py, I'd like to fake code field. I've tried to pick up a locale code ramdomly from LANGUAGES but it fails. Instead of creating one instance of AvailableLanguage, it loops over languages and quickly raises an issue because code is set to unique. So I thought of creating a Provider as a singleton, and it fails for the same reason. It generates all the locale codes instead of providing only one ! class Provider(BaseProvider): lang_code = NotImplemented def __init__(self, generator): self.langs = LANGUAGES self.generator = generator def __getattribute__(self, attrib): if attrib == 'lang_code': self.lang_code = self.langs.pop()[0] return self.lang_code else: return super().__getattribute__(attrib) fake.add_provider(Provider) class AvailableLanguageFactory(DjangoModelFactory): code = Faker('lang_code') class Meta: model = AvailableLanguage -
how to display media files after DEBUG=False in django
How can i display media files after debug is turned false.I have some 404 page and to get the 404 pages i set debug=false and after that my media files disappeared but static files are working fine.How can i manage this -
DeleteView not deleting
I have a problem in implementing DeleteView for a model that has a related model. When I try to delete a Task object nothing happens and it is not redirecting to the success_url. Noting happens. It just keeps on displaying the template. here are the models: class Project(models.Model): name = models.CharField(max_length=100) description = models.TextField() date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Task(models.Model): name = models.CharField(max_length=50, default='New Model') project = models.ForeignKey(Project, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) Here is my DeleteView Class: class TaskDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Task template_name = 'tasks/confirm_delete.html' # template for deletion success_url ='/projects/' # Test user permission def test_func(self): task = self.get_object() if self.request.user == task .project.author: return True else: return False def get_success_url(self): project = self.object.project return reverse_lazy('tasks-listview', kwargs={'pk': project.id }) and my URL patterns: urlpatterns = [ path('tasks/<int:pk>/list/', TasksListview.as_view(), name='tasks-listview'), path('tasks/<int:pk>/delete/', TaskDeleteView.as_view(), name='task-delete'), ] and here is my delete temple: <form method=" POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class='form-group'> <h4>Current Project: {{ object.project }}</h4> <h4>Are you sure you want to delete task named {{ object.name }}? </h4> </fieldset> <div class="form-group"> <button class="btn btn-danger float-sm-right mr-1" type="submit">Yes, Delete</button> <a class="btn btn-secondary float-sm-right mr-1" href="{% url 'task-detail' object.id %}">Cancel</a> </div> </form> -
Django Models: Many to Many or One to Many
I am trying to figure how to appropriately create the relationship between Order and Ticket models. The user can purchase many tickets, and with it will receive a Ticket ID--but when the User pays the amount of tickets (or ticket ID)--I want it to show the Order ID# with the Ticket ID#. However, I am unsure how to create the relationship between Ticket and Order models. Would I even need Order to be joined with Ticket models? What would you suggest? I tried using Order as many-to-many relationship with ticket, but it didn't seem to work. Suggestions would be helpful. models.py class User(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) email=models.CharField(max_length=100) password=models.CharField(max_length=100) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class Ticket(models.Model): venue=models.CharField(max_length=100) quantity=models.PositiveIntegerField() price=models.DecimalField(default=25.00, max_digits=5, decimal_places=2, null=True, blank=True) loop=models.CharField(max_length=100) purchaser = models.ForeignKey(User, related_name="purchases", on_delete=models.PROTECT) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class Order(models.Model): full_name=models.CharField(max_length=100) cc_number=models.PositiveIntegerField() exp_date=models.PositiveIntegerField() cvc=models.PositiveIntegerField() buyers=models.ManyToManyField(Ticket, related_name="bought_tickets")-----THIS HAS BEEN DELETED created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) ``` -
Why select query returs data as tuple, i need associative array in python
I am new in python, I am working on models.py, I can see it shows me data as tuple, I need associate array, can anyone please help me for that, Here is my code for that import datetime from django.utils import timezone from django.db import connection from django.db import models class Question(): @classmethod def get_poll_question(cls): with connection.cursor() as cursor: db_table = "polls_question" cursor.execute('SELECT * FROM '+db_table) allquestion = cursor.fetchall() return allquestion -
How to read large file sentence by sentence and send response after each line?
I want to read a large user uploaded file on my django server. I want to read each line and return it line by line on each user request. Suppose I have a file with content: This is a demo file. This is second line. Another line I want to return each sentence one by one on user request. Currently I am reading the file over and over and going to a particular line and returning that line. What is the best way to do this?