Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
passing a parameter to a form in FormView Django
it's a simple question. I have a form called MyForm , I overrid the __init__() method. Now I need to pass the request user when creating this form in MyFormView. I want to do this: class MyFormView(FormView): form_class = MyForm(request.user) Do I have to override the __init__ method of my view? if so, how? Thank you -
Django filter on calculated field when calculated field returns the value based on combination of two model fields
How to filter on calculated field whose values can be decided based on combination of two model fields in the same Model? Models.py class Job(models.Model): start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True) expiry_time = models.DateTimeField(null=True) is_complete = models.BooleanField(default=True) def _get_job_status(self): if self.is_complete is False and self.expiry_time >= now: return "active" elif self.is_complete is False and self.expiry_time < now: return "expired" else: return "complete" job_status = property(_get_job_status) I want to filter on job_status field, which can have 3 values active, expired or complete. I can not add job_status field directly in the filter fields, so how to filter on it? -
Django: DetailView and multiple slugs
I have an issue with my DetailView. I want to make sure both values are in the url string and then want to display the page. However I am always recieiving this error here: KeyError at /orders/ticket/ug2dc78agz-1/d04fkjmo37/ 'order_reference' views.py class TicketView(DetailView): model = Attendee template_name = 'orders/ticket_view.html' def get_queryset(self): return Attendee.objects.filter( order__order_reference=self.kwargs['order_reference'], ).filter( access_key=self.kwargs['access_key'], ) urls.py urlpatterns = [ path( 'ticket/<slug:ticket_reference>/<slug:access_key>/', TicketView.as_view(), name='ticket' ), ] -
Django Models for Time Series Data
My friends and I building an app that buy and sell stocks and we want to keep the historical prices of each stocks that we have in our possession by the end of day. The 3 most important fields are the ticker symbol and the price and the date. For example: 01/01/2018 - Bought Stock A, record price of Stock A at end of day(EOD) 01/02/2018 - Did nothing, record price of Stock A at EOD 01/03/2018 - Bought Stock B, record price of Stock A and Stock B at EOD 01/04/2018 - Sell Stock A, record price of Stock B at EOD We are using Django to build the models. Everyday we will record the price of each stock we have in our possession. This set of data is only for external use and will not be exposed to the public. My initial research tells me it is not ideal to have a single table for historical prices and store each price for per stock as a single row. I'm not sure what the best approach is while using Django. What is the best Django model to store all of this data and should we be using MYSQL? -
How to iterate over all child in Django?
If many models in Django are related to same common model using foreign key then how will it be possible to iterate over all the child models one by one. I know about parent.child_set.all() ,but I want to know if there is something that can be helpful to access child using a variable. -
Access other table in the same database in Django
We're using two backends languages, JAVA and Python, to handle different modules in the same project. -
Does packages installed on root are available in virtualenv?
Whether i can access packages installed on root user in my virtual env while working on django project? -
Django: how to pass template list to javascript onclick method?
I would like to pass the template list to javascript on the onclick function. I know that I can pass specific parameter. onclick="selectRows({{ rows.0 }})" function selectRows(row) { console.log(row); } // log: 1 but if I send list I get an error onclick="selectRows({{ rows }})" function selectRows(row) { console.log(row); } // Uncaught SyntaxError: Unexpected token < Is there a way to send to JavaScript the whole list? -
Django rest framework: catch ValidationError from external package
I'm using the django-rest-passwordreset package to implement password reset endpoints. When a given email doesn't exist, it throws a ValidationError exception, causing a 500 error. How can I catch this error, and return a 400 instead? I simply added the urls as shown below, so I don't think I can surround it with an Except or something similar. urlpatterns=[ ... url(r'^password/recover/', include('django_rest_passwordreset.urls')), ... ] -
How to fill foreign key field in form automatically?
I have following models: class Shops(models.Model): shopkeeper = models.ForeignKey(Shopkeeper, on_delete=models.CASCADE) and class Product(models.Model): shop = models.ForeignKey(Shops, on_delete=models.CASCADE) title = models.CharField(max_length=250) price = models.IntegerField() image = models.FileField(null=True, blank=True) and ModelForm Class as follow: class AddProductForm(forms.ModelForm): class Meta: model = Product exclude = ['dateCreated','dateUpdated'] and view as: def add_product(request): if request.method == 'POST': if request.user.is_shopkeeper: form = AddProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/') return HttpResponse('There is something wrong') if request.method == 'GET': form = AddProductForm(request.GET) return render(request, 'OnlineShops/addProduct.html', {'form':form}) and my rendered page is as: How can I fill up shop field with all shops only current logged in user has? -
django ajax_select fields not saving with modal (not rendering list)
I am using ajax_select widgets, its working fine but the values are not saving in my models sizes = models.ManyToManyField(Size,blank=True,related_name='product_sizes') colours = models.ManyToManyField(Colour,blank=True,null=True,related_name='product_colour') In my form.py class ProductCreateForm(forms.ModelForm): sizes = make_ajax_field(ProductCreateModel,'sizes','sizes') colours = make_ajax_field(ProductCreateModel,'colours','colours') class Meta: model = ProductCreateModel fields = ('title', 'description', 'orignal_price', 'discount', 'brand_name','model_name','stock', 'model_number','warranty','shiping_price','category', 'availability_regions','image1','image2','image3','image4', 'messages','sizes','colours' ) When I try print the values of sizes and colours with views def form_valid(self, form): product = form.save(commit=False) print(self.request.POST.getlist('colours')) print(self.request.POST.getlist('sizes')) form.save() return super(ProductCreateView, self).form_valid(form) In my console it printed ['|1|2|7|'] ['|2|3|1|4|'] these are the pk value of sizes and colours but as I know instead of "|" ,comma should be delimiter and values should be like ['1','2','7'] I don't know why I am getting these type of values, does anyone ever faced this issue ? or anyone who can help me out. -
Making a function in a app that changes fields in another app
Hi Djangonauts, I am new to Django so please forgive any errors in logic or code I have a accounts app that has a Profile model with a field is_verified Now I have another app called verification. That has a model Verification and a field called verify I want to create a logic such that when you verify the user on the verification app. The is_verified on profile app is also marked as True models.py for Profile class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=100) country = models.CharField(max_length=100) is_verified = models.BooleanField(default=False) models.py for Verification class Verification(models.Model): user = models.ForeignKey(User, related_name='verified') applied_on = models.DateTimeField(auto_now_add=True) verify = models.BooleanField(default=False) deny = models.BooleanField(default=False) verified_on = models.DateTimeField() denied_on = models.DateTimeField() def verify_a_user(self, user): self.verify = True user.profile.is_verified = True return user.profile.is_verified.save() Is this correct? Is there a better way to execute this code -
I am getting django database connection error
DATABASE_OPTIONS = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'student', 'USER': 'root', 'PASSWORD': 'pooja', 'HOST': 'localhost', 'PORT': 3306, 'init_command': 'SET storage_engine=INNODB, SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED' }, } Exception IS: raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I am using mysql database I am getting above exception in django while migrating model to the database please let me know what is the error what i ma doing wrong here. thanks you for your reply -
Object of type 'Decimal' is not JSON serializable Error when use request inherited object
I have a strange problem with creation of shopping cart I in Django 2.0. Sopping cart is and object inherited from request and stored in session: class Cart(object): def __init__(self, request, shop_u_id): self.session_key = str(settings.CART_SESSION_ID) self.session = request.session cart = self.session.get(self.session_key) if not cart: cart = self.session[self.session_key] = {} self.cart = cart I have no problem with set and get methods, but strange problem appeared in total sum function: def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) I got an error: Object of type 'Decimal' is not JSON serializable But get_total_price nothing stores in session, it just for representation. (item['price'] stored as string) -
Django TypeError: __str__ returned non-string (model name)
I have the following tables in my models.py class ScanTarget(models.Model): scan_target = models.CharField(primary_key=True, max_length=60) scan_count = models.IntegerField(default=1) last_scan = models.DateTimeField(default=timezone.now, blank=True, null=True) created = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.scan_target) class RawScanResults(models.Model): scan_target = models.ForeignKey(ScanTarget, on_delete=models.CASCADE, related_name='raw_results') result_uid = models.UUIDField() start = models.DateTimeField(default=timezone.now, db_index=True) finish = models.DateTimeField(null= True, blank=True, db_index=True) score = models.TextField(max_length=5, blank=True, null=True) def __str__(self): return str('test') The problem is raised when I want to instantiate a new RawScanResults with a foreign key to the ScanTarget in my views.py as following: if not ScanTarget.objects.filter(scan_target=domain).exists(): obj=ScanTarget(scan_target=domain) obj.save() uid = str(uuid4()) RawScanResults.objects.create(scan_target=obj, result_uid = uid, start = timezone.now(), ) I keep getting this error: TypeError: __str__ returned non-string (type ScanTarget) I have tried modifing def __str__ for both classes or commenting them out but it keep giving me the same error. What am I getting wrong here? -
AttributeError , 'super' object has no attribute 'save', in class based view
I am new the Django and I am unable to save the Registration form using the Class Based View. I have made the Abstract user in the Models as shown below. models.py class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) # can login staff = models.BooleanField(default=False) # staff user non superuser admin = models.BooleanField(default=False) # superuser timestamp = models.DateTimeField(auto_now_add=True) user_type = models.CharField(max_length= 120, choices=u_type) # confirm = models.BooleanField(default=False) # confirmed_date = models.DateTimeField(default=False) USERNAME_FIELD = 'email' #username # USERNAME_FIELD and password are required by default REQUIRED_FIELDS = [] #['full_name'] #python manage.py createsuperuser objects = UserManager() def __str__(self): return self.email def get_full_name(self): if self.full_name: return self.full_name return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active I have used ModelForm for creating the Registration form as shown below forms.py class RegisterForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ( 'email','full_name','user_type') #'full_name',) def clean_password2(self): # Check that the two password entries … -
Django InMemoryUploadedFile and asynchronous tasks
I have a django application on which I upload several files of huge size. Once in my view, I want to do an asynchronous task on those files: def my_view(request): Thread(target=_my_task, args=[request.FILES]).start()) return redirect(my_url) The problem is, by the time I uses the files in my thread, the main request has finished and the request object is deleted, alongside the InMemoryUploadedFile objects contained in it, and I get an IO exception: ValueError: I/O operation on closed file. How can I force the persistence of those files without writing them in my filesystem ? -
Django - DRF Validations
I'm designing an API which will be consumed by different partners. Following is the API dummy payload:- { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, partner: partner_code } Now, I've got a model in which above fields need to be saved. class Table(models.Model): key1 = models.IntegerField() key2 = models.IntegerField(blank=True, null=True) key3 = models.IntegerField() key4 = models.IntegerField(blank=True, null=True) key5 = models.CharField(max_length=255) partner = models.ForeignKey(Partner) Also, I've a serializer:- class TableSerializer(models.Model): class Meta: model = Table fields = '__all__' Now, whenever the data is POSTed, I serialize(and validate) the data, and then save it. Here's how I do it. serializer = TableSerializer(data=payload) if serializer.is_valid(): serializer.save() This is the normal DRF flow. Now, the problem that is arising is that I need to apply custom validations wrt to each partners. For eg:- `key2` and `key4` are mandatory for PartnerA. Similarly, for PartnerB, max value of `key1` is 100 and many more. As per the current DRF flow, I need to add if-else conditions in serializers. class TableSerializer(models.Model): def validate(self, data): if partner == `partnerA`: # checkfor key1 max value. # check the mandatory fields. elif partner == `partnerB`: # some custom validations # and so on class Meta: model = … -
Django forms, POST
I need to get user's choices and show the information to the user based on the data entered by the user. For this I am using a form to fetch the data from url1 and I am posting the data to another url, url2 whose view function will process the data and show the information. All working fine. I don't want to save the form's data into the database, that's why I am not redirecting after validating the form in url1 views' post method. POST data can't go with redirects. If I validate as well as process the form in url1 then I need to display the information in url1 itself, I need the urlname changed to url2 when displaying the information. Is there any standard way to do this thing? -
django-import-export import data from views.py
I'm working on django-import-export library for importing & exporting xls format, Everything working probably at AdminModel,Now I'm trying to make importing working with views.py & templates but for some reasons didn't work with me views.py def simple_upload(request): if request.method == 'POST': person_resource = resources.SimsResource() dataset = Dataset() new_persons = request.FILES['myfile'] imported_data = dataset.load(new_persons.read()) result = person_resource.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): person_resource.import_data(dataset, dry_run=False) # Actually import now return render(request, 'import_sims.html', {'errors': result.has_errors(), 'result': result}) return render(request, 'import_sims.html') resources.py class SimsResource(resources.ModelResource): class Meta: model = models.Sim fields = ['s_serial_number', 's_number', 's_provider', 'status'] forms.py class UploadFileForm(forms.Form): file = forms.FileField() url.py url(r'^importing_sims/$', views.simple_upload, name='Import'), template {% if errors %} errors: {{ errors }} <br><br><br> resluts : {{ result }} {% endif %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> and shown error : errors: True resluts : <import_export.results.Result object at 0x1072b75f8> -
StaticLiveServerTestCase not logging in
I'm new to python. I'm trying to use StaticLiveServerTestCase with Python to login to the Django admin portal. I'm using the below code. Running the below code launches the admin portal but I'm unable to login with my credentials. Please let me know if I'm missing something. Thanks! from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.webdriver.firefox.webdriver import WebDriver class MySeleniumTests(StaticLiveServerTestCase): port = 0 host = <<my host>> @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def test_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/login/')) username_input = self.selenium.find_element_by_name("username") username_input.send_keys('myuser') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('secret') self.selenium.find_element_by_xpath('//input[@value="Log in"]').click() -
Django - KeyError
I don't know why this gives me KeyError at this line > idtoken=request.session['uid'] in postCreateEquity function def postsignup(request): firstName=request.POST.get('signupfirstusername') lastName=request.POST.get('signuplastusername') email=request.POST.get('signupemail') password=request.POST.get('signuppassword') vpassw=request.POST.get('signupverifiedpassword') birthday=request.POST.get('signupdob') country=request.POST.get('signupcountry') checkbox=request.POST.get('signupcheckbox') user=authe.create_user_with_email_and_password(email,password) uid=user['localId'] #this id is unique for everyone data={"firstName":firstName,"lastName":lastName ,"birthday":birthday ,"country":country,"checkbox":checkbox} database.child("Users").child(uid).set(data) return render(request,'welcomepage/login.html') def startCampaign(request): return render(request,'welcomepage/start-campain-registered-user.html') def createEquity(request): return render(request,'welcomepage/efund-createEquity-registered-user.html') def createReward(request): return render(request,'welcomepage/efund-createReward-registered-user.html') def postCreateEquity(request): category=request.POST.get('category') duration=request.POST.get('duration') highlight=request.POST.get('heighlight') imgName=request.POST.get('img') investDiscussion=request.POST.get('investDiscussion') investTerms=request.POST.get('investterms') linkForVideo=request.POST.get('video') market=request.POST.get('market') name=request.POST.get('name') neededMoney=request.POST.get('amountofmoney') endDate=request.POST.get('enddate') offers=request.POST.get('offers') startDate=request.POST.get('startdate') summary=request.POST.get('summary') team=request.POST.get('team') timeline=request.POST.get('timeline') idtoken=request.session['uid'] a= authe.get_account_info(idtoken) a=a['users'] a=a[0] a=a['localId'] print(str(a)) -
No module named 'django' (Without Virtualenv)
I was making django application work with apache mod_wsgi.Below is my error log. [Mon Jul 02 15:20:42.859177 2018] [so:warn] [pid 4046] AH01574: module wsgi_module is already loaded, skipping [Mon Jul 02 15:20:42.868149 2018] [wsgi:warn] [pid 4047] mod_wsgi: Compiled for Python/3.5.1+. [Mon Jul 02 15:20:42.868187 2018] [wsgi:warn] [pid 4047] mod_wsgi: Runtime using Python/3.5.2. [Mon Jul 02 15:20:42.869974 2018] [mpm_prefork:notice] [pid 4047] AH00163: Apache/2.4.33 (Ubuntu) mod_wsgi/4.5.2 Python/3.5.2 configured -- resuming normal operations [Mon Jul 02 15:20:42.870004 2018] [core:notice] [pid 4047] AH00094: Command line: '/usr/sbin/apache2' [Mon Jul 02 15:20:46.777714 2018] [wsgi:error] [pid 4051] [client ::1:57828] mod_wsgi (pid=4051): Target WSGI script '/home/pocra/dashboard/dashboard/dashboard/wsgi.py' cannot be loaded as Python module. [Mon Jul 02 15:20:46.777807 2018] [wsgi:error] [pid 4051] [client ::1:57828] mod_wsgi (pid=4051): Exception occurred processing WSGI script '/home/pocra/dashboard/dashboard/dashboard/wsgi.py'. [Mon Jul 02 15:20:46.778033 2018] [wsgi:error] [pid 4051] [client ::1:57828] Traceback (most recent call last): [Mon Jul 02 15:20:46.778164 2018] [wsgi:error] [pid 4051] [client ::1:57828] File "/home/pocra/dashboard/dashboard/dashboard/wsgi.py", line 12, in [Mon Jul 02 15:20:46.778207 2018] [wsgi:error] [pid 4051] [client ::1:57828] from django.core.wsgi import get_wsgi_application [Mon Jul 02 15:20:46.778245 2018] [wsgi:error] [pid 4051] [client ::1:57828] ImportError: No module named 'django' [Mon Jul 02 15:20:46.839298 2018] [wsgi:error] [pid 4048] [client ::1:57830] mod_wsgi (pid=4048): Target WSGI script '/home/pocra/dashboard/dashboard/dashboard/wsgi.py' cannot be loaded … -
Django: Do not allow users to see pages when login details do not match with custom models details
I have custom model where login details have been stored: class UserRegistration(models.Model): # Auto updated when data is inserted created_at = models.DateTimeField(auto_now_add=True, auto_now=False) # Auto updated when data is altered updated_at = models.DateTimeField(auto_now_add=False, auto_now=True) username = models.CharField(max_length=255, null=True) password = models.CharField(max_length=255, null=True) first_name = models.CharField(max_length=255, null=True) last_name = models.CharField(max_length=255, null=True) def __str__(self): return self.first_name urls.py is url(r'^login/$', view.login_page, name='login_page'), views.py is def login_page(request): if request.method == 'GET': return render(request, "login_page.html") if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') print username, password credentials_matches = False # considering credentials are wrong all_users = UserRegistration.objects.all() for user in all_users: if user.username == username and user.password == password: credentials_matches = True break if credentials_matches: return HttpResponse('success') # return redirect("http://127.0.0.1:8000/lmtech") else: return HttpResponse('fail') I have other views that I do not wish to show to user if they have not logged in. I though about @login_required() but in this case, user details are in custom model. How do I solve this problem? -
Django QuerySet: additional field for counting value's occurence
I have QuerySet object with 100 items, for each of them I need to know how many times particular contract_number occurs in the contract_number field. Example of expected output: [{'contract_number':123, 'contract_count':2},{'contract_number':456, 'contract_count':1}...] which means that value 123 occurs 2 times for the whole contract_number field. Important thing - I cannot reduce amount if items, so grouping won't work here. SQL equivalent for this would be additional field contract_count as below: SELECT *, (SELECT count(contract_number) FROM table where t.contract_number = contract_number) as contract_count FROM table as t The question is how do it with python object. After some research, I have found out that for more complex queries Queryset extra method should be used. Below is one my tries, but the result is not what I have expected queryset = Tracker.objects.extra( select={ 'contract_count': ''' SELECT COUNT(*) FROM table WHERE contract_number = %s ''' },select_params=(F('contract_number'),),) models.py: class Tracker(models.Model): contract_number = models.IntegerField()