Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django OAuth Toolkit and Django Rest Swagger Integration
I'm using OAuthToolkit and DjangoRestSwagger. I've created an application using Django Admin, and now I've client_id and client_secret. I want to generate the token using client_id and client_secret. Currently, I use curl to generate the token. curl -X POST -d "grant_type=client_credentials" -u"client_id:client_secret" http://localhost:8000/o/token/ How can I do it using the Swagger docs.? Basically, how can integrate third party(OAuthToolkit) API URLs with Swagger? Currently, I've an Authorize button which takes api_key value, ie the token. Here's my Swagger settings. SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'token': { 'type': 'apiKey', 'name': 'AUTHORIZATION', 'in': 'header', } }, } -
How to add all of the migrations/ to git .gitignore file in django?
In my Django project, I have many migrations directory, I want to add to my .gitignore file: Because they are under each app directory, I do not want to add every one. How can I add all the migrations directories in it? Now in it only like this: .idea/ -
how to display large list of data using reactJS as frontend and django rest framework as backend
I am having large list of data of ingredients required for cooking. More than 3000+ I am using Django rest framework as the backend and ReactJs as frontend. Each item in the list has a name, id, measurementunit, density in kg/ltr and cost/measurementunit In Django i have created an api endpoint to supply the data in JSON format. I want to display the data in a table format and with search filter on the top. Also at a time i want to show maximum 300 results. Can someone guide me how to achieve this. Should i fetch all the list at a time or use pagination from django. Should i use seperate api for search or do it using reactjs on the frontend. Presently i dont need any authorization in django. The data is for local use only. -
Django saving to Foreign field
I'm trying to save an Item based on the Foreign Key Primary Key for topCategory and middleCategory. models.py class MiddleCategory(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() def __str__(self): return self.title class TopCategory(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() middleCategory = models.ManyToManyField(MiddleCategory) def __str__(self): return self.title # Item class Product(models.Model): title = models.CharField(max_length=500, db_index=True) price = models.DecimalField(max_digits=10, decimal_places=2) brand = models.CharField(max_length=100) # brand_id = models.IntegerField() retailer = models.CharField(max_length=255) image = models.CharField(max_length=1000) url = models.URLField(max_length=800, unique=True, default='') model_numbers = models.BigIntegerField(default=0) description = models.CharField(max_length=500) featured = models.CharField(max_length=255, db_index=True, default='NO') timestamp = models.DateTimeField(auto_now=True) topCategory = models.ForeignKey(TopCategory) middleCategory = models.ForeignKey(MiddleCategory) def __str__(self): return self.title In my script I'm saving like this: Product(title=title, price=price, brand=brand, retailer=retailer, image=image, url=url, description=description, midCategory=midCategory, topCategory=topCategory ).save() This is the error I am getting: ValueError: Cannot assign "'1'": "Product.topCategory" must be a "TopCategory" instance. -
This field cannot be blank
I want to add image in Django admin, but when I chose img, fill all fields and click on Save, I saw next message 'This field cannot be blank.' near img field. In django console all is good, I havent any bugs(on local server all works). What did I do wrong? -
How to edit the multi-count many to many data? like use the shuttle table?
How to edit the multi-count many to many data? like use the shuttle table? I have two models, they are many to many relationship: class HostType(models.Model): name = models.CharField(max_length=8) availablearea = models.ManyToManyField(to=AvailableArea, related_name='hosttypes',default=1) def __str__(self): class AvailableArea(models.Model): name = models.CharField(max_length=8) # there I omitted a foreign field, because its useless here. def __str__(self): return self.name def __unicode__(self): return self.name In the serializers: class HostTypeSerializer(ModelSerializer): class Meta: model = HostType fields = "__all__" depth = 1 The views.py: class HostTypeDetailAPIView(RetrieveAPIView): serializer_class = HostTypeSerializer permission_classes = [] queryset = HostType.objects.all() When I access the retrieve url(..../hosttypes/1/), I get bellow data: { "id": 2, "name": "标准型二", "availablearea": [ { "id": 6, "name": "东北地区", } ] } You see, there is only one row data in this hosttype's availablearea list. I want to use the shuttle table to edit the hosttype's availablearea: -
MissingSchema: Invalid URL 'None': No schema supplied. Perhaps you meant http://None?
views.py from django.shortcuts import render from django.http import HttpResponse import random import hashlib import os import requests def index(request): """Displays the page that asks for the phone number""" return render(request, "verify/sms.html") def verify(request): """Displays the page that asks for the verification code""" # if the form wasn't submitted properly, then go to index page try: phoneNumber = request.POST['phonenumber'] except: return render(request, "verify/sms.html") verificationCode = str(random.randint(1000000, 9999999)) # the check sequence is sent to the next page to verify if the code entered is correct checkSequence = hashlib.sha1((verificationCode+str(os.environ.get("SEED"))).encode("utf-8")).hexdigest() sendVerificationCode(phoneNumber, verificationCode) return render(request, "verify/verification.html", {"code": checkSequence}) def checkCode(request): """Checks if the verification code entered is correct""" try: verificationCode = request.GET['verification'] correctCheckSequence = request.GET['code'] except: return render(request, "verify/sms.html") # check the correct check sequence against the check sequence based on the verification code provided checkSequence = hashlib.sha1((verificationCode+str(os.environ.get("SEED"))).encode("utf-8")).hexdigest() if checkSequence == correctCheckSequence: return HttpResponse("1") else: return HttpResponse("0") def sendVerificationCode(phoneNumber, verificationCode): """Sends the verification code to the provided phone number using TILL API""" if len(phoneNumber) < 10: return # doesn't give the user an error message - just doesn't send the message TILL_URL = os.environ.get("TILL_URL") requests.post(TILL_URL, json={"phone":[phoneNumber], "text": "Verication code: " + str(verificationCode)}) urls.py from django.conf.urls import url, include from . import views urlpatterns = … -
Save foreign key data in the Parent model of a formset - Django
So I'm using Django formsets for the first time and am stuck at saving my foreign Key data at the Parent model of the formset. I have 3 models - CustomUser, SchoolMarks, SchoolDetails in which SchoolMarks is the Parent model/form for the SchoolDetails formset. As you can see below, SchoolMarks has CustomUser as a foreignkey and I'm trying to save the SchoolDetails data to the respective user, but am unable to do this in my views with the formset. Would appreciate any guidance since this is one aspect where the documentation is lacking as well. models.py class CustomUser(AbstractBaseUser,PermissionsMixin): email = models.EmailField(unique=True, null=True) class SchoolMarks(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) tenth_grade_total_marks_received = models.PositiveIntegerField() class SchoolDetails(models.Model): schoolmarks = models.ForeignKey(SchoolMarks) school_name = models.CharField(max_length=255) school_cocurricular_activities = models.CharField(max_length=255) school_critical_projects_undertaken = models.CharField(max_length=255) forms.py class SchoolDetailsForm(forms.ModelForm): class Meta: model = SchoolDetails fields = '__all__' exclude = ('user',) SchoolDetailsFormSet = inlineformset_factory(SchoolMarks, SchoolDetails, form=SchoolDetailsForm,extra=1) views.py class SchoolDetailsCreate(generic.CreateView): model = SchoolMarks fields = ('tenth_standard_total_marks_received','tenth_standard_maximum_marks_possible',) success_url = reverse_lazy('all_accounts_app:school-marks-list') def get_context_data(self, **kwargs): data = super(SchoolDetailsCreate, self).get_context_data(**kwargs) if self.request.POST: data['schooldetails'] = SchoolDetailsFormSet(self.request.POST) else: data['schooldetails'] = SchoolDetailsFormSet() return data def form_valid(self, form): context = self.get_context_data() schooldetails = context['schooldetails'] with transaction.atomic(): self.object = form.save() if schooldetails.is_valid(): schooldetails.instance = self.object schooldetails.save() return super(SchoolDetailsCreate, self).form_valid(form) -
OSError at /dfa/lkd/link_auth/ [Errno 5] Input/output error WHEN I TRY TO RUN MY DJANGO APP ON SERVER
im getting an OS error -[Errno 5] Input/output error when i run my django app on server by giving the IP address an URL . the app also contains authentication which shows the following error -> OS error as we close the gunicorn or putty terminal in which gunicorn was running. The following error doesn't occur if we keep the putty terminal alive in which the gunicorn is running. -
Python string to dict, what's the fastest way?
AdWords for some reason doesn't have a normal REST api, it uses instead a SOAP api which either returns a .csv file or recently a string. I'm using django and I need to save results in my database. Currently I use Pandas to transfor the string to a dataframe, and then I iterate through it and save it in my database. However this process is slow and inefficient. I don't want to use pandas just for this. Would AST work in my situation? What's the fastest way to do this? My code with pandas looks like this: abc = report_downloader.DownloadReportAsString(report, skip_report_header=True, skip_column_header=False,skip_report_summary=True) print(abc) print(type(abc)) df = pd.read_csv(StringIO(abc), sep=",",) #print (df.to_string()) for index, row in df.iterrows(): ctr = float(float(row['CTR'].strip('%')) / 100) conv_rate = float(float(row['Conv. rate'].strip('%')) / 100) cost = row['Cost']/1000000 cpm = row['Avg. CPM']/1000000 avg_cpc = row['Avg. CPC']/1000000 def_data = { 'impressions':row['Impressions'], 'ctr':ctr, 'avg_cpc':avg_cpc, 'conversion_rate':conv_rate, 'clicks':row['Clicks'], 'cost':cost, 'cpm':cpm, 'conversions':row['Conversions'], } obj, created = AdWordsData.objects.get_or_create( user=user, date=row['Day'], campaign=row['Campaign'], ad_group=row['Ad group'], final_url=row['Final URL'], tracking_template=row['Tracking template'], defaults=def_data, ) if not created: obj.__dict__.update(**def_data) obj.save() else: print ('No campaigns were found.') ABC (the data return by adwords is a string and looks like this: Day,Campaign,Ad group,Final URL,Tracking template,Impressions,CTR,Avg. CPC,Conv. rate,Clicks,Cost,Avg. CPM,Conversions 2017-09-08,mysite.me Many Keywords,Many Keywords,https://mysite.me, --,364,0.82%,73333,0.00%,3,220000,604396,0.00 … -
How to access named url arguments in permissions with Django REST Framework?
I have an url config like url(r'^user/(?P<id>[0-9]+)/$', UserView.as_view()) And a view class like class UserView(GenericAPIView): serializer_class = UserSerializer permission_classes = [MyCustomPermission] def get(self, request, id): # code... The permission is like class MyCustomPermission(BasePermission): def has_permission(self, request, view, *args, **kwargs): # code How do I access id in MyCustomPermission? I can't find it from the request or from *args or *kwargs. Documentation doesn't say anything about this. I've tried to look the source code but can't find how to access those named url arguments. Is it even possible? -
django unable to render form
I'm new to django. look at the following code in my form.py: class ProfileForm(forms.Form): name = forms.CharField(label=_("first name")) lname = forms.CharField(label=_("last name")) phone= forms.CharField(label=_("phone")) address = forms.CharField(label=_("address")) def categorize_fields(self): categorized_fields = [ [ self.fields["name"], self.fields["lname"] ] , [ self.fields["phone"], self.fields["address"] ] ] return categorized_fields in my form render I have the following code which does not work properly: {% for field_set in form.categorize_fields %} {% for field in field_set %} {{ field.label }} {{ field }} {% endfor %} {% endfor %} field.label is working correctly but {{ field }} is not showing the HTML rendered and instead is showing this: <django.forms.fields.CharField object at 0x000002161591CA90> but if I iterate through the main form passed to form_render.html, everything works fine: {% for field in form.visible_fields %} {{ field.label_tag }} {{ field }} {% endfor %} how can I solve that? thanks -
How do you allow time entry in 2 formats in Django?
I want users to be able to entry time as decimals: 8.25 and as time: 8:15 What Django FormField should I use? My thoughts are to make is a forms.CharField() as that would remove HTML restrictions and forms.TimeField() creates the same input. What Validators should be applied to that formfield? I'm not sure if I need to create a custom validator. -
django rest framework test warning but succeed
I have a problem or rather a warning, when i'm running my django tests I verified the rest api manually and its working perfectly WARNING:django.request:Not Found: /api/summoners/1 TESTS class SummonerRetrieveTest(APITestCase): def test_get_summoner(self): summoner = Summoner.objects.create( username='karim', level=30, icon='test' ) response = self.client.get('/api/summoners/{}'.format(summoner.id)) self.assertEqual(response.status_code, 200) summoner_resp = response.data self.assertEqual(summoner.id, summoner_resp['id']) self.assertEqual(summoner.username, summoner_resp['username']) self.assertEqual(summoner.level, summoner_resp['level']) self.assertEqual(summoner.icon, summoner_resp['icon']) def test_get_summoner_dont_exist(self): # if i remove this request, there is no warning # if i duplcate it then there is 2 warning with the same message response = self.client.get('/api/summoners/1') print(response.data) self.assertEqual(response.status_code, 404) URLS urlpatterns = [ url(r'^summoners$', SummonerListView.as_view()), url(r'^summoners/(?P<pk>[0-9]*)$', SummonerRetrieveView.as_view()), url(r'^summoners/exist/(?P<username>[\w0-9_\-]+)$', SummonerExistView.as_view()), url(r'^summoners/autoc_username/(?P<username>[\w0-9_\-]+)$', SummonerAutoCompleteView.as_view()), ] -
Django queryset - column IN() GROUP BY HAVING COUNT DISTINCT
With the following models: class Post(models.Model): class Meta: db_table = "posts" class Tag(models.Model): tag = models.CharField(max_length=50) class Meta: db_table = "tags" class PostTag(models.Model): postid = models.PositiveIntegerField() tagid = models.PositiveIntegerField() class Meta: unique_together = ("postid", "tagid") db_table = "posttags" To get postids of posts which contain all the tags given in TAGLIST where TAGLEN is the number of tags in TAGLIST: SELECT postid FROM posttags WHERE tagid IN (TAGLIST) GROUP BY postid HAVING COUNT(DISTINCT tagid) = TAGLEN But how do I do this with Django ORM? -
django-filter: only show filter options contained in queryset
I'm using the excellent django-filter app to filter a queryset of model objects. However, when I .exclude() objects from the queryset in the view, the filter selectors in the template still show all available options - even those of objects I excluded from the queryset. Let's say my model and view look as follows: #model [...] class Animal(models.Model): REGION_CHOICES = ( (0, 'Africa'), (1, 'Europe'), ) name = models.CharField(max_length=100) region = models.CharField(choices=REGION_CHOICES, max_length=100) [...] #view [...] qs = Animal.objects.all() filter = AnimalFilter(request.GET, qs) [...] Assuming there are two animals in the database: zebra = Animal(name='Zebra', region='Africa') frog = Animal(name='Frog', region'Europe') When I render the filter in the template, I correctly get a selector for region which contains the two options Europe and Africa. But if I use some logic in the view to .exclude() objects from the queryset like this: #view [...] qs = Animal.objects.all().exclude(name='Frog') filter = AnimalFilter(request.GET, qs) [...] Now if I render the filter in the template I still get the two options Europe and Africa for region although the queryset only contains one animal which has the region Africa. Any ideas how I could get the correct options for the region field rendered in the template? Any … -
Heroku Upload - Could not find a version that satisfies the requirement anaconda-client==1.4.0
I'm trying to push a Django app onto Heroku but am getting the following error upon running git push heroku master Counting objects: 80, done. Delta compression using up to 8 threads. Compressing objects: 100% (74/74), done. Writing objects: 100% (80/80), 990.21 KiB | 0 bytes/s, done. Total 80 (delta 20), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 2 is python-2.7.14 (you are using python-2.7.12, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-2.7.14). remote: Learn More: https://devcenter.heroku.com/articles/python- runtimes remote: -----> Installing python-2.7.12 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: Collecting alabaster==0.7.7 (from -r /tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 1)) remote: Downloading alabaster-0.7.7-py2.py3-none-any.whl remote: Collecting anaconda-client==1.4.0 (from -r /tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 2)) remote: Could not find a version that satisfies the requirement anaconda-client==1.4.0 (from -r /tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 2)) (from versions: 1.1.1, 1.2.2) remote: No matching distribution found for anaconda-client==1.4.0 (from -r /tmp/build_a1f6d188f9e0e61e01076a73d4e10542/requirements.txt (line 2)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to demo-freshstart. Seems like it has something to do with Anaconda, … -
Cant delete object because i have manyToMany relationship in django
Sorry for my english. I try delete object from admin and i have error: Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed I have model like this: class Event(models.Model): user_create = models.ForeignKey(User, related_name="user_created", on_delete=models.CASCADE) users = models.ManyToManyField(User, related_name='users', blank=True, null=True) name_event = models.CharField(max_length=64, blank=False, null=False) description = models.TextField(blank=True, null=True, default=None) life_of_time = models.DateTimeField(blank=True, null=True, default=None) created_at = models.DateTimeField(auto_now_add=True, auto_now=False) updated_at = models.DateTimeField(auto_now_add=False, auto_now=True) class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return "%s" % (self.name_event) if i remove this line: users = models.ManyToManyField(User, related_name='dealers', blank=True, null=True) then do migrations and try delete event from admin, everething delete fine. -
Django rest response to display full dependencies structures and data
I have made Django REST function based API. I want to generate response to display full dependencies structure and data. Employee is onetoone relation with User and Foreignkey to Company. The response should show Employee data with User and Company related data. Below is my code excerpts https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py @api_view(['GET']) def get_employee(request): return Response(Employee.objects.all().values(), status=status.HTTP_200_OK) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) identity_number = models.CharField(max_length=20, blank=True) current result [ { "id": 1, "user_id": 8, "company_id": 3, "identity_number": "", "tel": "", "address_1": "", "address_2": "", "address_zip": "", "address_city": "", "address_state": "", "address_country": "", "face_image": "", "created_at": "2017-11-12T15:35:19.427973Z", "updated_at": "2017-11-12T15:35:19.455553Z" }, { .... what i am trying to achieve is this. how to do this result ? kind of like presenter on ruby on rails. [ { "id": 1, "user": {"id": 1, "username": "michaeljackson", "first_name": "michael", "last_name": "jackson", "email": "xxx@gmail.com"}, "company": {"id": 2, "name": "company X", "tel": "123456", ....}, "identity_number": "", "tel": "", "address_1": "", "address_2": "", "address_zip": "", "address_city": "", "address_state": "", "address_country": "", "face_image": "", "created_at": "2017-11-12T15:35:19.427973Z", "updated_at": "2017-11-12T15:35:19.455553Z" }, { .... -
Where is the datewidget in my wagtail formbuilder?
I am implementing an AbstractEmailForm using wagtail form builder. The date-widget is not showing in the date-field. Is this a current bug? Or am I missing something? -
can't import name 'Post'
i can't import a class Post in my django models,when i try to runserver, its returns importError:cannot import name "Post",i have been on this for some days now,please help me..thanks this is my class models for Post from .models import Post, Comment class Post(models.Model): objects = models.Manager() published = PublishedManager() def get_absolute_url(self): return reverse('blog:post_detail',args=[self.publish.year,self.publish.strftime('%m'), self.publish.strftime('%d'),self.slug]) STATUS_CHOICES = (('draft', 'Draft'),('published', 'Published'),) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES,default='draft') class Meta: ordering = ('-publish',) def __unicode__(self): return self.title And this also my class model for Comment from .models import Post, Comment class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __unicode__(self): return 'Comment by {} on {}'.format(self.name, self.post) -
Multiple file upload DoS attack prevention with Django
I am building a Django application in which users will have to upload several files (too much to do one at a time), hence a form is available for them with a FileField that allowst the upload of several files at once. With validators it is not hard to constrain the individual file sizes so what worries me is the total number of files they might upload at once. How can I solve this issue? My attempt: In views.py I am following the numer of files they have and not saving them anymore if this numer is over 100. Despite this the browser keeps pinging the upload handler view with POST requests (one attempt for each intended upload). This makes me feel uneasy about the solution. Would this not still consume my bandwidth possibly leading a Denial of Servie attack? -
this page is now working - Docker
I have a local docker image running with a django project that i am running. The docker image is up but when i go to the local host with port 8000 which is set, gives a message that the page is not working and that 127.0.0.1 didn’t send any data. Here is the docker code: omars-mbp:Split omarjandali$ docker build -t split . Sending build context to Docker daemon 222.2kB Step 1/7 : FROM python:3 ---> 79e1dc9af1c1 Step 2/7 : WORKDIR user ---> 15e014da5b80 Removing intermediate container f4081817276f Step 3/7 : COPY requirements.txt ./ ---> 1f444390862b Step 4/7 : EXPOSE 8000 ---> Running in f75a6674ade2 ---> 7641865ffc85 Removing intermediate container f75a6674ade2 Step 5/7 : RUN pip install -r requirements.txt ---> Running in 40738a20f481 Collecting Django==1.11.5 (from -r requirements.txt (line 1)) Downloading Django-1.11.5-py2.py3-none-any.whl (6.9MB) Collecting gunicorn==19.6.0 (from -r requirements.txt (line 2)) Downloading gunicorn-19.6.0-py2.py3-none-any.whl (114kB) Collecting pytz (from Django==1.11.5->-r requirements.txt (line 1)) Downloading pytz-2017.3-py2.py3-none-any.whl (511kB) Installing collected packages: pytz, Django, gunicorn Successfully installed Django-1.11.5 gunicorn-19.6.0 pytz-2017.3 ---> 371a95617f78 Removing intermediate container 40738a20f481 Step 6/7 : COPY . . ---> fa31f9520063 Step 7/7 : CMD python manage.py runserver 0.0.0.0:8000 ---> Running in 28b6a097dac4 ---> c0d19bca8c2d Removing intermediate container 28b6a097dac4 Successfully built c0d19bca8c2d Successfully tagged … -
Django How can I add the code so that I can filter my customers as per some choosen model field and export it to excel
some way so that i can choose from a drop-down menu which field I want to select and transfer the data corresponding to all the customers in an excel sheet class Customer(models.Model): soss = models.CharField(max_length=60) soss_line = models.CharField(max_length=70) build_date = models.CharField(max_length=80) ctb_Status = models.CharField(max_length=60) ctb_comment = models.CharField(max_length=50) comments = models.CharField(max_length=200) sjz_status = models.CharField(max_length=60) production_result_Code = models.CharField(max_length=70) bu = models.CharField(max_length=50) pf = models.CharField(max_length=50) current_fcd = models.DateField(null=True, blank=True) tan = models.CharField(max_length=50) eta = models.CharField(max_length=60, null=True, blank=True) tied = models.CharField(max_length=30) otm_status = models.CharField(max_length=30) bucket_aged = models.CharField(max_length=60) ead = models.DateField(null=True, blank=True) -
Django in difference OS (windows10 &Ubuntu16.04) access same DB (SQL Server 2012) but show difference result to template
Django version: 1.11.2 Pytohn version : 3.6 I have a problem when I use django to show data from DB. I had 20 article in DB (table :ResultArticle) In Windows 10, I can show all article(20) to template(web) But in Ubuntu 16.04, I just can show 18 to template. I loss 2 article, this 2 article had long content(full_text 12728 bytes & full_text_stem 11471 bytes ) models.py class ResultArticle(models.Model): article_guid = models.CharField(primary_key=True, max_length=36) project_guid = models.CharField(max_length=36) title = models.CharField(max_length=255) full_text = models.TextField() # This field type is a guess. full_text_stem = models.TextField(blank=True, null=True) # This field type is a guess. resource = models.CharField(max_length=255) get_time = models.DateTimeField() url = models.TextField() # This field type is a guess. class Meta: managed = False db_table = 'result_article' views.py def archives(request,project_id,filter): articles = ResultArticle.objects.filter(project_guid = project_id) return render(request, 'archives/archives.html', {'articles': articles}) Any help will be appreciated.