Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django_tables2: Split colums
I'm newby in Django. I try to split cell with comma separated integers into n colums, but can't find how to do that in Django_tables2. Please help Source: id | Name | Marks | 1 | Peter | 3,2,4 | 2 | Joe | 4,4,4 | Result: id | Name | Marks | 1 | Peter | 3 | 2 | 4 | 2 | Joe | 4 | 4 | 4 | -
Django Sitemap -- 'str' object has no attribute 'get_absolute_url' Error
I'm getting the 'str' object has no attribute 'get_absolute_url' error on my django project on my sitemap page. Any help is appreciated. Here is my traceback: Traceback: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\views.py" in inner 16. response = func(request, *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\views.py" in sitemap 71. protocol=req_protocol)) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\__init__.py" in get_urls 111. urls = self._urls(page, protocol, domain) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\__init__.py" in _urls 120. loc = "%s://%s%s" % (protocol, domain, self.__get('location', item)) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\__init__.py" in __get 68. return attr(obj) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\__init__.py" in location 75. return obj.get_absolute_url() Exception Type: AttributeError at /sitemap.xml Exception Value: 'str' object has no attribute 'get_absolute_url' my sitemaps.py file from django.contrib import sitemaps from django.contrib.sitemaps import Sitemap from django.urls import reverse from deals.models import Deal from blog.models import Post class StaticViewSitemap(sitemaps.Sitemap): priority = 1.0 changefreq = 'daily' def items(self): return ['about', 'contact', 'disclosure', 'terms', 'privacy', 'deals:deals', 'blog:blog'] class BlogSitemap(Sitemap): changfreq = "daily" priority = 1.0 location ='/blog' def items(self): return Post.objects.filter(status='Published') def lastmod(self, obj): return obj.created class DealSitemap(Sitemap): changfreq = "daily" priority = 1.0 def items(self): return Deal.objects.all() def lastmod(self, obj): return obj.date_added and my two … -
What are the advantages of more modern web app frameworks (Django, Ruby on Rails, Node) over Java-based web apps like J2EE?
Being that Django, Ruby on Rails, and Node apps are as popular as they are, I was curious as to why some people still choose to develop Java-based web frameworks like Spring and J2EE. Are there any good reasons? I somewhat suspect that those are just used by people who are most comfortable with Java because that's the language they learned in their computer science classes. I've never heard of a self-taught developer opting to use that, so I would be curious to see if anybody out there has chosen J2EE or Spring or Struts over the laternatives. -
django how to use get_or_create with a FileField and an upload_to
I have a website that where users upload data files. To prevent users from uploading duplicate data files, I'm using Django's get_or_create, which was working fine, until I added an 'upload_to' to the model. This is my model: class TestFile(models.Model): file = models.FileField(upload_to='data/%Y/%m/') date = models.DateField(default=date.today) welded-part = models.ForeignKey(WeldedPart, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return str(self.file) Uploading the file calls the following function: def process_data_file(myfile, my_id): a, created = TestFile.objects.get_or_create(file=myfile) if created: do some number crunching here a.welded-part = my_id a.save() return created If I try to upload testfile.xyz it checks for an object where TestFile.object = 'testfile.xyz'. I will never find a duplicate file because the object stores the file as 'data/2018/04/testfile.xyz', not as 'testfile.xyz'. What's the proper way to use get_or_create in this instance? I'm using django 1.11.3 -
Validation for model forms
I am trying to do validation for model forms to check if both 'email' and 'confirm_email' have same value. I tried searching online but getting some errors. I am making custom validators in models.py file. Can you please help me with that. What would be the best way of validating model forms. Here is my code. MODELS.PY from django.db import models from django.core import validators from django.core.exceptions import ValidationError # Create your models here. def validate_equal(self, email, confirm_email): if email != confirm_email: raise ValidationError( ('email does not match'), params={'email': email, 'confirm_email': confirm_email} ) class NewSubscriber(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) email = models.EmailField(max_length=254,unique=True) confirm_email = models.EmailField(max_length=254, validators=[validate_equal('self', 'email', 'confirm_email')]) -
cannot use in operator to search for status
I have the following script that is returning cannot use in operator to search for status in the console: var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $(document).ready(function () { $('#selectuserlist').select2({ minimumInputLength: 3, allowClear: true, placeholder: { id: -1, text: 'Enter the Student ID.', }, ajax: { type: 'POST', url: '', headers: { "X-CSRFToken": csrftoken }, contentType: 'application/json; charset=utf-8', async: false, dataType: 'json', data: function (params) { return "{'searchFilter':'" + (params.term || '') + "','searchPage':'" + (params.page || 1) + "'}"; }, processResults: function (res, params) { var jsonData = JSON.parse(res.d); params.page = params.page || 1; var data = { more: (jsonData[0] != undefined ? jsonData[0].MoreStatus : false), results: [] }, i; for (i = 0; i < jsonData.length; i++) { data.results.push({ id: jsonData[i].ID, text: jsonData[i].Value }); } return { results: data.results, pagination: { more: data.more, }, }; }, }, }); }); The entire error i'm getting is: select2.min.js:1 Uncaught TypeError: Cannot use 'in' operator to search for 'status' in undefined at Object.<anonymous> (select2.min.js:1) at fire (jquery.js:3317) at Object.add [as fail] (jquery.js:3376) at Object.transport (select2.min.js:1) at d (select2.min.js:1) at d.query (select2.min.js:1) at d.a.query (select2.min.js:1) at d.j [as query] (select2.min.js:1) at e.<anonymous> (select2.min.js:1) at e.d.invoke (select2.min.js:1) My error occurs when the minimumInputLength of 3 for … -
Https shows an empty page with Django project deployed on Elastic Beanstalk
I deployed my Django project through AWS Elastic Beanstalk which is Amazon Linux AMI, and then I installed SSL to make https to work. My website is currently working on http well. But when I get into it through https, it just shows an empty page with a few words, "Index of /". I feel like I should do something on port 443 which is a port for https. Other than that, everything seems good since the website is working well on port 80. Can anyone help me about this? -
Error: 'index.html' could not be found
I am following this tutorial. I get this error when I run the server- Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Raised by: django.contrib.staticfiles.views.serve 'index.html' could not be found How can I fix it? -
Django: Merge two ManyRelatedField in serializer
The code is as the following. What I want to do is combine 'promises_as_inviter' and 'promises_as_invitee' into 'whole_promises' which is what I will use as a serialization field. As can be seen below, 'promises_as_inviter' and 'promises_as_invitee' come from the reverse-relationship of 'User' class to 'Promise' class by using ;PrimaryKeyRelatedField'. I tried simple things like using '+' operation to combine two fields, but it did not work. I checked the type of 'promises_as_inviter' and 'promises_as_invitee' by using type method and it says they are 'ManyRelatedField'. So the question is this. How can I merge two 'ManyRelatedField' into one? Thank you. class UserAllSerializer(serializers.ModelSerializer): promises_as_inviter =serializers.PrimaryKeyRelatedField(many=True, queryset=Promise.objects.all()) promises_as_invitee = serializers.PrimaryKeyRelatedField(many=True, queryset=Promise.objects.all()) whole_promises= **???** class Meta: model = User fields = ('id','username','whole_promises') -
How to properly include + register viewset routers with Django 2.0 DRF 3.8
I'm developing a basic Django DRF API. I have been using class-based views with explicit URLs. Now I'm trying to use very vanilla DRF ViewSets + router (for auto URL generation). Can anybody help point me in the right direction? I'm on DRF 3.8 and Django 2.0 Project urls.py: from django.conf.urls import url, include urlpatterns = [ url(r'^userprofile/', include('UserProfile.urls', namespace='UserProfile')), ] App: UserProfile/urls.py: from django.conf.urls import include from django.urls import path from rest_framework.routers import DefaultRouter from UserProfile import views app_name = 'UserProfile' router = DefaultRouter() router.register('humans', views.HumanViewSet,) urlpatterns = [path('', include(router.urls))] App: UserProfile/views.py from rest_framework import viewsets from UserProfile.models import Human from UserProfile.serializers import HumanSerializer class HumanViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = HumanSerializer queryset = Human.objects.all() I get an error: __init__() missing 2 required positional arguments: 'app_name' and 'app_module' -
Deploying and development env for Django and React
I build a nice web application with django and react and i want to deploy it, during development i used to have to separate app which run on different ports on my sys, django app and react js app. I'm using axios to connect between my frontend and my backend. Now i think i finish my first version of my web app and i want to deploying it and i understand its not that simply as i thought and i'm so frustrated i couldn't find the right way. My question is what is the best way to build this kind of project using those two platforms? there is a way which i can develop this app and make this work as production on dev? how can i work with relative http request on dev, because its different servers? I don't need to perfect way to do it because its first version and i'm doing it for my first time, i want the right way to begin and to deploying my first app to the internet.. -
Conda environment
I create a conda environment, which called MyDjangoEnv. When I try to activate it, I wrote on the terminal "source activate MyDjangoEnv" and I get the error "No such file or directory." I tried Install a different version of Python with "conda create --name MyDjangoEnv python=3", but I get the error "conda: the order was not found" -
Django migration dependency order
I have a relatively complex set of Django models. I'm trying to start with a fresh set of migrations (rm -rf apps/*/migrations; bin/dev/manage.py makemigrations A B C...). makemigrations works fine, and there are no circular dependencies, but I'm consistently getting an InconsistentMigrationHistory exception when I migrate. Here's a graph of the dependencies between the migrations, simplified to remove the migrations with no related dependencies, and with the app names redacted for readability: The links in red cause the error (different ones each time I run migrate), even with a run_before added to each migration that should be run before its dependency: A/migrations/0002_whatever.py: ... run_before = [('P', '0001_initial'),] Here's the error text. django.db.migrations.exceptions.InconsistentMigrationHistory: Migration `P.migrations.0001_initial` is applied before its dependency `A.migrations.0002_whatever` on database 'default'. Any ideas? -
Key Value Error in saving changes to model values in Django Admin
I have a model which uses a sign up form to create a user. The form is working fine and the user is created and with the correct values. However when I use Django Admin interface to change values and save them or save and create another I get an error message as below (To note: I just added 2 new values to the model - preapproved and active. I've made the migrations): ValueError at /admin/app_users/profileteacher/4/change/ invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/admin/app_users/profileteacher/4/change/ Django Version: 1.10.5 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: /home/fungai/pythonicness/mildev/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 1832 Python Executable: /home/fungai/pythonicness/mildev/bin/python Python Version: 2.7.12 Python Path: ['/home/fungai/pythonicness/milingual_api', '/home/fungai/pythonicness/mildev/lib/python2.7', '/home/fungai/pythonicness/mildev/lib/python2.7/plat-x86_64-linux-gnu', '/home/fungai/pythonicness/mildev/lib/python2.7/lib-tk', '/home/fungai/pythonicness/mildev/lib/python2.7/lib-old', '/home/fungai/pythonicness/mildev/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/fungai/pythonicness/mildev/local/lib/python2.7/site-packages', '/home/fungai/pythonicness/mildev/lib/python2.7/site-packages', '/home/fungai/pythonicness/milingual_api'] Server time: Fri, 6 Apr 2018 14:55:54 +0000 the error is traced to this line: super(ProfileTeacher, self).save(*args, **kwargs) and the model is (with a save function in there): class ProfileTeacher(models.Model): created = models.DateTimeField(auto_now=False, auto_now_add=True, blank = False, null = False, verbose_name = 'Creation Date') user = models.OneToOneField(app_settings.USER_MODEL,blank=True, null=False) first_name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'First Name') last_name = models.CharField(max_length = 400, null=True, … -
Generate dynamic url patterns with django version 2
I want to generate dynamically urlpatterns for my application. All the functions that i use are class based. The defaults CreateView, UpdateView, DeleteView, ListView, DetailView. The code works but the problem is that urlpatterns are not unique. For example category/create pattern appears multiple times inside urlpatterns dict. url.py file from importlib import import_module from django.apps import apps from django.urls import path from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView app_module = import_module('{}.{}'.format('projects', 'views')) app_models = apps.get_app_config('projects').get_models() model_names = [model.__name__ for model in app_models] urlpatterns = [] for key, value in app_module.__dict__.items(): if isinstance(value, type): for model_name in model_names: if issubclass(value, ListView): pattern = path('{}/'.format( model_name.lower()), value.as_view(), name='{}-list'.format(model_name.lower())) if value.__name__.find(str(model_name)): if pattern.pattern not in urlpatterns: urlpatterns += [pattern] if issubclass(value, DetailView): pattern = path('{}/<int:pk>/detail/'.format( model_name.lower()), value.as_view(), name='{}-detail'.format(model_name.lower())) if value.__name__.find(str(model_name)): if pattern.pattern not in urlpatterns: urlpatterns += [pattern] if issubclass(value, CreateView): pattern = path('{}/create/'.format( model_name.lower()), value.as_view(), name='{}-create'.format(model_name.lower())) if value.__name__.find(str(model_name)): if pattern.pattern not in urlpatterns: urlpatterns += [pattern] if issubclass(value, UpdateView): pattern = path('{}/<int:pk>/update/'.format( model_name.lower()), value.as_view(), name='{}-update'.format(model_name.lower())) if value.__name__.find(str(model_name)): if pattern.pattern not in urlpatterns: urlpatterns += [pattern] if issubclass(value, DeleteView): pattern = path('{}/<int:pk>/delete/'.format( model_name.lower()), value.as_view(), name='{}-delete'.format(model_name.lower())) if value.__name__.find(str(model_name)): if pattern.pattern not in urlpatterns: urlpatterns += [pattern] print(urlpatterns) -
Addition of multiple image of one product variation django eCommerce app
I am trying to make django eCommerce app in which product has diffrenet variation.For example, product T-shirt has different color(red, green ..) variations. For each variation I would like to upload different images at least three images.But I can upload now only one image per variation. Can anyone help me how to add multiple image and show them in the template?Thank you in advance for your help! Please find below app details: class Product(models.Model): title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2, max_digits=20) default_image = models.ImageField(upload_to=image_upload_to_prod, blank=True, null=True) slug = models.SlugField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('Products:SingleProduct', kwargs={'pk': self.pk}) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2, max_digits=20) DEFAULT = 'DEFAULT' RED = 'RED' BLUE = 'BLUE' TYP = ( (DEFAULT, 'DEFAULT'), (RED, 'RED'), (BLUE, 'BLUE'), ) color = models.CharField(max_length=100, choices=TYP, default=DEFAULT) image = models.ImageField(upload_to=upload_location, blank=True, null=True) def get_price(self): if self.sale_price is not None: return self.sale_price else: return self.price def get_image(self): if self.image is not None: return self.product.default_image else: return self.image def get_absolute_url(self): return self.product.get_absolute_url() def upload_location(object, filename): title = object.product.title slug = slugify(title) return "products/%s" % (slug) -
python|django how to post file, change it, and send it back?
I am writing a small test project with python\django. I'm sending an image to server (with request post), resizing it and want it back to the client. So far it seems that everything working properly beside that i dont know how to send the file back to the client. CLIENT: testFile = "<location>" api_url = 'http://localhost:9999/upload' files = {'file': open(testFile, 'rb')} r = requests.post(api_url,files=files,data={"m":10,"n":15}) files["file"].close() print r -> status 200 SERVER: @csrf_exempt def post(request): if request.method == 'POST': logger.info("New post request") #logger.info(request.FILES) file = request.FILES['file'] resized_frame = job_manager.add_job(file,request.POST.get("m"),request.POST.get("n")) logger.info("returning new resized frame ") response = HttpResponse(content_type='image/png') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(resized_frame) return response #return HttpResponse(resized_frame) else: return HttpResponse('500') can I even send response with files while getting a post request? -
interface / inheritance model django
I am trying to modeling the following in Django but I am having troubles City: name : Str belongs_to_providence : Providence Providence: name : Str belongs_to_country : Country Country: name : Str language : Str Proponsal: title : Str affects_to : City | Providence | Country I tried to do this using an abstract model , like the following : # account/models.py class CommonLocationInfo(models.Model): name = models.CharField(max_length=180, blank=False) def __str__(self): return self.name class Meta: abstract = True class Country(CommonLocationInfo): language = models.CharField(max_length=120) class Providence(CommonLocationInfo): country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="belongs_to_country", null=True) class City(CommonLocationInfo): providence = models.ForeignKey(Providence, on_delete=models.CASCADE, related_name="belongs_to_providence", null=True) class Proponsal(models.Model): affects_to = models.ManyToManyField(CommonLocationInfo) but is not working , it tells me the following Field defines a relation with model 'CommonLocationInfo', which is either not installed, or is abstract. -
Serve scraped HTML data as an API using Django Rest Framework
I'm trying to build a public facing API that collects data through scraping HTML (the content of the page is what is important, not the pages themselves). I've elected to use Django-Rest-Framework as my backend. My question is: How exactly would I organize the structure of this project so that the Django ORM stores the scraped content and then it can be accessed using Django-Rest-Framework's API? I've looked into Scrapy, but that seems less focused on content scraping and more focused on webcrawling. Additionally, it deploys in its own project, which makes conflicts with Django's bootstrapping. Is my best bet just running cronjobs? That seems inelegant. -
django serializer thumbnail of ImageField using sorl
I have an existing serializer which includes an ImageField which can be very large image. I want to have a smaller thumbnail version of that image. I am trying to use sorl to create the thumbnails, since its able to upload it to AWS S3. How can I create this thumbnails in the serializer? in my current serializers.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ("id", "username", "first_name", "last_name", "face_image",) my model looks like this, it uploads to AWS S3: class Employee(models.Model): username = models.CharField(max_length=30, blank=False) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) face_image = models.ImageField(upload_to=upload_to('employee/face_image/'), blank=True, null=True, storage=MediaStorage()) This is an attempt to have a new field in the serializer called "face_image_small", but it doesnt work from sorl.thumbnail import get_thumbnail class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ("id", "username", "first_name", "last_name", "face_image", "face_image_small",) face_image_small = get_thumbnail(self.face_image, '200x200', crop='center', quality=99) -
Python 3, complex database creation
i want to create a database for a hospital, the main entity will be 'Patient' each 'Patient' would have many informative fields, some of which are constructed of only text (str) and some would be pdf's excell charts, and so on. my question is, should i start designing the DB (working on django) as such class PatientInnerField1(model.Models): '' '' class PatientInnerField2(model.Models): '' '' class PatientInnerFieldN(model.Models): '' '' N fields of data for a 'Patient' And then define class Patient(PatientInnerField1,PatientInnerField2,----> , PatientInnerFieldN) Any tips on how to plan this kind of data base, and how to start building it ? Thanks -
How to use Graphviz/Networkx using django template and view
I am currently working on Django graph. I successfully displayed my models data using template and view, the result looks like this: As you can see, the Formula detail table include the reactants that participates in the reaction, now I want to add a function to this page, like add a button at the right side. And when I click on the button, a graph could be generated automatically. The graph should looks like '10fthf5glu_m(in a circle) -> 10fthf5glu_c(in a circle)' I know this function should be done by using Graphviz and Networkx, but how? -
Mix Django and DRF urls
So far, I have built a REST API with Django Rest Framework (DRF) which can be consumed by any front-end. Let call this API backend. I am trying to add another Django app (a regular one this time i.e. no DRF) which shares the same models. Let call this app webapp However, it seems that the URLs linked to webapp are not available. Here is my urls.py: from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from rest_framework.authtoken import views as token_views from backend import views from webapp import views as webapp_views router = routers.SimpleRouter() router.register(r'users', views.UserViewSet, 'User') router.register(r'games', views.GameViewSet, 'Game') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^connect/', views.CustomObtainAuthToken.as_view()), url(r'membership_create/', views.MembershipCreate.as_view()), url(r'auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()), url(r'auth/connect_with_credentials/', views.TokenViewWithData.as_view()), url(r'debug/', views.UserLoginAndIdView.as_view()), url(r'^auth/', include('rest_framework_social_oauth2.urls'), url(r'^test/', webapp_views.home, name='test'), # the new view ) ] urlpatterns += router.urls And the single view (from webapp.views): from django.http import HttpResponse from django.shortcuts import render def home(request): return HttpResponse(""" <h1>WEBAPP !</h1> <p>test webapp</p> """) I am thus wondering if DRF and regular Django views can be mixed so easily or if it is not the right way of doing it. -
django sequence:item 4 expected string or unicode int found
I'm running python manage.py migrate with my models,the database was already made i'm just making the models for it now, but getting this error when running the command TypeError: Error when calling the metaclass bases sequence item 4: expected string or Unicode, int found my models class Publisher(models.Model): publisherCode = models.CharField(3,primary_key=True) publisherName = models.CharField(25) city = models.CharField(20) class Book(models.Model): bookCode = models.CharField(4,primary_key=True) title = models.CharField(40) publisherCode = models.ForeignKey(Publisher) type = models.CharField(3) paperback = models.CharField(1) class Branch(models.Model): branchNum = models.DecimalField(2,0,primary_key=True) branchName = models.CharField(50) branchLocation = models.CharField(50) class Copy(models.Model): bookCode = models.ForeignKey(Book) branchNum = models.ForeignKey(Branch) copyNum = models.DecimalField(2,0,primary_key=True) quality = models.CharField(20) price = models.DecimalField(8,2) -
How do i link a .sav file with DJango. My .sav file contains a ML model
I am trying to link a python file with Django. For linking the python file,we need to link the saved model. The saved model is of the format .sav