Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build web app like instructables?
i have already learned html, css, js. I want to create web app like instructables. ( Users can input recipe and app can show this recipe to other users ). How to start? Which technology i should use/learn? Node + express? Django? I already knew node + express at beginner level. -
Django save a model instance when testing but can't find it in real database
I'am new to Django, when I was doing testing, I created a new test model record in setup() function for the following test, it succeeded, and I can access the record in the following code, but when I go to check the real database, the new record is not exist. the setup code like this: class UserTest(TestCase): def setUp(self): test_user = User.object.create(name='test') when I set the breakpoint in the setUp() function, and after the 'test_user' is created, I can use 'User.object.get()' to obtain the created user, but when I go to real database and check the User table, I can't find this record. By the way, I use postgreSQL. The test runner is using this: class NoDBTestRunner(DiscoverRunner): def setup_databases(self, **kwargs): pass def teardown_databases(self, old_config, **kwargs): pass I want to know where the created data record is stored? Any suggestion will be very helpful -
Django: DurationField with resolution in microseconds
The django DurationField displays only HH:MM:SS in the django admin interface. Unfortunately this is not enough in my current context. I need to be able to show/edit microseconds in the admin interface. How could this be done? -
Select Columns from multiple tables - Django
I am trying to select all the columns from one table and only a single column from the second table using the Django ORM.The two tables are related by a foreign key but the column in the second table which i want, is not related, so using select_related doesn't work. I used FirstTable.objects.filter().values("All first table columns separated by a comma","second tablename__column name") and this worked fine. Since, the columns are very large in number, i do not want to list all of them in "values". So, i am looking for an easy way to do this. Thanks for your help -
Extend filter_horizontal in django admin
I have django app (django 1.11) and I need to extend filter_horizontal. I mean, I need to near title also a date of event. Here is my first model, where is M2M to event: class Product(models.Model): title = models.CharField(max_length=500) events = models.ManyToManyField('events.Event', related_name="products", blank=True) admin.py, and here I would like to have event title and date of event (event_title - event_date). Is it possible? class ProductAdmin(TranslationAdmin): list_display = ('title',) filter_horizontal = ('events',) here is model of event: class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() -
Django urlspatterns for two related models
I have two models (School and Student) with one to many relationship. my models.py are set as follows: class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name def get_absolute_url(self): return reverse("basic_app:school_detail",kwargs={'pk':self.pk}) class Student(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE,default=None) and the urls.py file will have the following: urlpatterns = [ url(r'^$',views.SchoolListView.as_view(),name='school_list'), url(r'^(?P<pk>\d+)/$',views.SchoolDetailView.as_view(),name='school_detail'), url(r'^create/$',views.SchoolCreateView.as_view(),name='school_create'), url(r'^update/(?P<pk>\d+)/$',views.SchoolUpdateView.as_view(),name='school_update'), url(r'^delete/(?P<pk>\d+)/$',views.SchoolDeleteView.as_view(),name='school_delete'), my question is I want to add to the urlpatterns list more urls for students:something like #url(r'^$',views.StudentListView.as_view(),name='student_list'), # url(r'^(?P<pk>\d+)/$',views.StudentDetailView.as_view(),name='student_detail'), # url(r'^create/$',views.StudentCreateView.as_view(),name='student_create'), # url(r'^update/(?P<pk>\d+)/$',views.StudentUpdateView.as_view(),name='student_update'), # url(r'^delete/(?P<pk>\d+)/$',views.StudentDeleteView.as_view(),name='student_delete') I know my addition is not correct because each group of students should be related to a specific school. I am confused how to use id/pk in the url because for example student_detail.html url should contain both school id and student id. sorry if this looks naive question.. but I am still learning and any help will be highly appreciated.. thanks -
django query all with filtering on the related set?
class Customer(models.Model): name = models.CharField(max_length=200) # .. class CustomerTicket(models.Model): customer = models.OneToOneField(Customer) date = models.DateTimeField(auto_now_add=True) # .. I want to query all customers, adding for each customer its ticket if it has one. -
Django Web Application Access Active Directory
I am trying to get user's Active Directory information on the local intranet network, from an Django Web Application. What I want: ** When Users/Client log on to the website, they can see their various details from the Active Directory ** If the users have already entered their username and password when turning on their PCs. So they shouldn't need to do it again. How can I make it so that users are able to enter their website without entering their username and password? -
Error HTTP Error 403: SSL is required when pip installing MySQL-python
I'm having a problem pip installing MySQL Python on my server. Full stack trace is as follows: (ENV)[fendyhj@web530 lepaperville]$ pip install MySQL-python Downloading/unpacking MySQL-python Running setup.py egg_info for package MySQL-python Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz Traceback (most recent call last): File "<string>", line 16, in <module> File "/home/fendyhj/webapps/lepaperville/ENV/build/MySQL-python/setup.py", line 7, in <module> use_setuptools() File "distribute_setup.py", line 145, in use_setuptools return _do_download(version, download_base, to_dir, download_delay) File "distribute_setup.py", line 124, in _do_download to_dir, download_delay) File "distribute_setup.py", line 194, in download_setuptools src = urlopen(url) File "/usr/local/lib/python2.7/urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "/usr/local/lib/python2.7/urllib2.py", line 437, in open response = meth(req, response) File "/usr/local/lib/python2.7/urllib2.py", line 550, in http_response 'http', request, response, code, msg, hdrs) File "/usr/local/lib/python2.7/urllib2.py", line 475, in error return self._call_chain(*args) File "/usr/local/lib/python2.7/urllib2.py", line 409, in _call_chain result = func(*args) File "/usr/local/lib/python2.7/urllib2.py", line 558, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 403: SSL is required Complete output from command python setup.py egg_info: Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz urllib2.HTTPError: HTTP Error 403: SSL is required Anyone know how to install MySQL Python through HTTPS ? Any help would be appreciated, Thanks ! -
Check type of a database field - python
I've a Django model which contains settings, so each element of the model is a setting and the possible fields are setting_name, setting_value, setting_type and so on. For example, if I have a setting named version where the possible values are integers (like 1,2,3), the fields in the database are the following: setting_name = "version" setting_value = "2" setting_type = "int" What I need to do is check if the value and the type of the settings are consistency between them. With integers fields is not a problem because I'm able to cast the value to Int in order to check that. But what about float and str? In the first case (Float) I don't want the automatically conversion in case the field contains an int (i.e "5" -> 5.0) For the string, instead, the "cast approach" is not possible, because the field is always a string from database. Any suggestions? I'm using Python 3.5 and Django 1.11 Thank you in advance -
from uno.core.models import StateModel ImportError: No module named models
from django.db import models from redactor.fields import RedactorField from uno.core.models import StateModel class PromoBanner(StateModel): title = RedactorField(blank=True, null=True) sub_title = RedactorField(blank=True, null=True) button_1_text = models.CharField(max_length=255, blank=True, ..... ..... ..... ..... ..... from uno.core.models import StateModel ImportError: No module named models -
jQuery & Django: how can I use jquery properly in this case
I'm having hard time with js and jquery executing events, I guess there is something I'm missing in my understanding of jquery. Because I'm really new to this language, I'm confused and need some orientation if you can help me please. what I need: I have a form as a row, and a button that adds a new form everytime I click on it. also the new generated forms have different Ids and names. Now every form contains two selects and need a change function to be excuted on it. Where should I write this change function, so that every row have his own change function without getting confused with other rows. Any help would be great. Thank You in advance -
How fix test for change password view (Django REST Framework)?
In view, the test does not take the request.data as an element of DRF. I have this view: class ChangePasswordView(UpdateAPIView): serializer_class = ChangePasswordSerializer model = UserInfo permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): return Response(status=200) def put(self, request, *args, **kwargs): self.object = self.request.user serializer = self.get_serializer(data=request.data) if serializer.is_valid(): if not self.object.check_password(serializer.data.get("old_password")): return Response( {"old_password": ["Wrong password"]}, status=400 ) self.object.set_password(serializer.data.get("new_password")) self.object.save() return Response("Success", status=200) return Response(serializer.errors, status=400) and I have this test method: def test_change_password(self): client = APIClient() self.client.post('/api/user/login/', self.data, follow=True) self.client.login(username="testuser", password="secret") request = client.put('/api/user/change_password/', self.new_data) self.assertEqual( request, '<Response status_code=200, "application/json">' ) where data: def setUp(self): self.data = { 'username': 'testuser', 'password': 'secret' } self.new_data = { 'old_password': 'secret', 'new_password': 'other_secret' } User.objects.create_user(**self.data) Why does the test stop at reqest.data in serializer = self.get_serializer(data=request.data)? -
Ordering objects by foreignkey field and not foreignkey count
I am making a request and a voting feature for the request: class Request(models.Model): title = models.CharField(max_length=255) approved = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) class Vote(models.Model): request = models.ForeignKey(Request, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) vote_type = models.BooleanField() I would like to order requests by the total vote counts in descending order by substracting different vote_type's (True/False) for each request. Meaning order requests with highest number of votes to lowest number of votes. I can order by the vote this way: Request.objects.order_by('-vote') But this just gives me which request has highest number of foreign key count, and not the actual vote count. I can get the actual vote counts for a request like this: def get_vote_count(obj): return obj.vote_set.filter(vote_type=True).count() - obj.vote_set.filter(vote_type=False).count() But I can't figure out how to achieve this when getting all the requests and ordering them in the view. -
Difference between PositiveInteger and PositiveSmallInteger Field in Django
There is no difference between PositiveInteger and PositiveSmallInteger field in the Django source code. But, Django documentation says, PositiveInteger starts from 0 to 2147483647 and PositiveSmallInteger starts from 0 to 32767. Please clarify me what is the difference between two type. Thanks in advance. -
Django REST: serialize url to list of objects of a category
Hard facts: I am using Django 2.0 with python 3.6, if it makes any difference. What I am trying to achieve is a link to a list of objects that belong to a summary. I have a ManyToOne relationship in my models.py. class Summary(models.model): type=models.CharField class Object(models.Model): summary= models.ForeignKey(Summary, on_delete=models.CASCADE) in urls.py object_list= views.ObjectListViewSet.as_view({ 'get': 'list' }) urlpatterns = format_suffix_patterns([ url(r'^summary/(?P<pk>[^/.]+)/objects/$', object_list, name='summary-objects') ]) and now the idea was to give a user the possibility to click the an url in the browsable API and getting all objects. So, I tried to write a MethodField in serializers.py. I am not able to get any reasonable URL here, the only solution would be to hardcode it. class SummarySerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name="app:summary-detail") objects= serializers.SerializerMethodField('get_obj_url') def get_obj_url(self, obj): pass class Meta: model = Summary Is this possible? Is it necessary to write a MethodField? If yes, how do I get the url I need? -
Google Flexible Environment django gunicorn static files
Running a Django project Google Flexible Environment with gunicorn as entrypoint so that I can use geventworkers. Cant seem to figure out how to server the static files properly. I have done I have STATIC_URL = '/static/' and STATIC_DIR = 'static' in django settings. I've also ran manage.py collectstatic and the files do get copied correctly, yet my django rest framework swagger cant find its files. For the convenience I had already added TEMPLATES to my settings aswell. This used to work before I started using geventworkers. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'rest_framework.templates', 'rest_framework_swagger.templates', os.path.join(BASE_DIR, 'website'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', ], }, } ] -
Accessing multiple dictionaries in list using for loop in Django Templates
I have been working on a project and it requires me to access dictionaries that are in a list. I am using Django 2.0. This is my code here. {% if dictdata %} {% for x in range %} {{ "in loop" }} {{ dictdata.x.name }} {% endfor %} {{ dictdata.0.name }} {{ dictdata.1.name }} {% endif %} The two statement after the for loop are working fine. But the one in the loop is not returning anything but printing the message 'in loop'. dictdatais a list containing dictionaries. -
Django ManyToManyField as separate checkboxes in form with individual error messages
For each possible many to many relation I want a form to have separate checkboxes. I know this is possible using the CheckboxSelectMultiple, but it seems I can't have individual error messages per checkbox. # models.py class OptIn(models.Model): required = models.BooleanField(default=False) description = models.TextField() def __str__(self): return self.description class Lead(models.Model): optins = models.ManyToManyField(OptIn, blank=True) # forms.py class LeadForm(forms.ModelForm): class Meta: model = Lead fields = ['optins'] widgets = { 'optins': forms.CheckboxSelectMultiple } def clean_optins(self): # Errors raised here are for entire field I want people signing up on the website (Lead) being able to agree to a number of opt-ins (OptIn). Opt-ins can be optional or required for the user. For the required opt-ins I want to show an error message or add a class when the user doesn't agree to them. Raising errors in clean_optins shows the error for the entire optins field. Can a custom template for the CheckboxSelectMultiple widget handle this in a nice way or is there a better way to implement this functionality? -
Creating a Single Solution with multiple Django Projects
I am new to Django and I was thinking whether it would be possible to go in to any other alternative solution except the monolith architecture like solution based projects in C# MVC. Is it possible to do something like that with Python such that we can use multiple frameworks on different projects and make a combination of them once the final solution is made. -
Django query set COUNT on multiple DISTINCT VALUES
I want to count all distinct programs with certains fields for every faculty. test_count = Faculty.objects.annotate( count=Subquery( Program.objects.filter(faculty=OuterRef('pk')) .values('faculty', 'title, 'form', 'level', 'years') .distinct() .annotate(count=Count('pk')) .values('count'))) I'm getting error: (1242, 'Subquery returns more than 1 row') This due to passing multiple values in the first values list. If i pass on on value it will count, but the count won't be distinct. Are there are workarounds or others ways counting like this? Or should i resort to raw SQL. -
In Django restframework, foreign key value is not getting in HyperlinkedModelserializer
Models.py from django.db import models class BusinessType(models.Model): method = models.CharField(max_length=25) class Vendor(models.Model): first_name = models.CharField(max_length=25) middle_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) nick_name = models.CharField(max_length=10) email = models.CharField(max_length=30) company = models.CharField(max_length=25) phone = models.CharField(max_length=15) mobile = models.CharField(max_length=10) fax = models.CharField(max_length=10) billing_address_street = models.CharField(max_length=120) billing_address_city = models.CharField(max_length=20) billing_address_state = models.CharField(max_length=20) billing_address_zip = models.CharField(max_length=6) billing_address_country = models.CharField(max_length=20) shipping_address_street = models.CharField(max_length=120) shipping_address_city = models.CharField(max_length=20) shipping_address_state = models.CharField(max_length=20) shipping_address_zip = models.CharField(max_length=6) shipping_address_country = models.CharField(max_length=20) notes = models.CharField(max_length=120) gstin = models.CharField(max_length=25, null=True) tin = models.CharField(max_length=25, null=True) business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE) Serializers.py from rest_framework import serializers from .models import Vendor,BusinessType class BusinessTypeSerializer(serializers.HyperlinkedModelSerializer): [enter image description here][1] class Meta: model = BusinessType fields = ('id','method') class VendorSerializer(serializers.HyperlinkedModelSerializer): business_type = serializers.CharField(source='business_type.method') class Meta: model = Vendor fields = ('id','first_name','middle_name','last_name','nick_name','email','company','phone','mobile','fax','billing_address_street','billing_address_city','billing_address_state','billing_address_zip','billing_address_country','shipping_address_street','shipping_address_city','shipping_address_state','shipping_address_zip','shipping_address_country','notes','gstin','tin','business_type') In Django restframework, foreign key value is not getting in HyperlinkedModelserializer in 'business_type' field. When I tried to post method after declaring foreign key field, it says: "AssertionError: The .create() method does not support nested writable fields by default. Write an explicit .create() method for serializer UserSerializer, or set read_only=True" -
How to send multiple objects in one single POST method from one app to another using django rest framework
I have a POST method for a Payslip implemented using class based view in payroll.models which after the POST the data will be sent to another app accounting.models that has a model called transactions. Currently the code below works fine I can send data to the accounting app but the data for Allowances and Deduction is not included in the JSON object. How do I include both allowances and deductions in the payslip. views class PayslipPostAPIView(APIView): """ { "employee":2, "currency": "KES", "payment_mode":1, "month_ending":"2018-04-02", "allowance_list":[{ "name":1, "amount":200 }], "deduction_list":[{ "name":1, "amount":200 }] } """ serializer_class = PayslipSerializer queryset = Payslip.objects.all() def post(self, request, format=None): try: # print(type(request.data['allowance_list'])) allowance_list = request.data.pop('allowance_list') # print(allowance_list) deduction_list = request.data.pop('deduction_list') employee = Employee.objects.get(id=request.data['employee']) # print(employee) basic_salary = Salary.objects.get( employee=request.data.pop('employee')) payment_mode = PaymentMode.objects.get( id=request.data.pop('payment_mode')) payslip = Payslip.objects.create(**request.data) payslip.payslip_no = "PAYSLIP" + str(payslip.id) + "DT" + \ str(datetime.datetime.now()) payslip.basic_salary = basic_salary payslip.employee = employee payslip.payment_mode = payment_mode for item in allowance_list: allowance = Allowance.objects.create(name=AllowanceType.objects.get(id=item['name']), amount=item['amount'], payslip=payslip ) # print("looop1") for item in deduction_list: ded = DeductionType.objects.get(id=item['name']) deduction = Deduction.objects.create(name=ded, amount=item['amount'], payslip=payslip ) payslip.save() # payslip = Payslip.objects.get( # payslip__id=request.data['payslip_id']) serializer = PayslipSerializer(payslip) encoded_data = json.dumps(serializer.data) payslip_data = json.dumps( {"object": encoded_data, "app": "payslip"}) print(payslip_data) r = requests.post( "http://0.0.0.0:8000/acc/incoming/transations/", headers={'Content-Type': … -
Django: Save duplicate of an instance along with relationships
I want to save duplicate of an instance along with all direct and reverse relationships I have used the following code instance.id=None instance.pk=None instance.save() By doing so, I am able to save all the attributes of the instance along with all the direct relationships and even reverse Foreign key relationship but I am not able to save the reverse one to one field relationship. -
module 'object has no attribute' BaseSettings
import django.conf class AppSettings(django.conf.BaseSettings): """ A holder for app-specific default settings that allows overriding via the project's settings. """ def __getattribute__(self, attr): if attr == attr.upper(): try: return getattr(django.conf.settings, attr) except AttributeError: pass return super(AppSettings, self).__getattribute__(attr) AttributeError: 'module' object has no attribute 'BaseSettings here am facing issue while running django project Thanks in advance