Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : Digital Ocean Spaces/AWS S3, how to create image using django_storages
I am trying to user django_storages package for storing images on AWS S3 or Digital Ocean spaces. When I use normal image upload using a form, the image is successfully getting uploaded to the server. But When I try to create an image manually and then write it to S3 or Digital Ocean Space buckets, the image is not getting created properly. Following is the code which I have run on Shell and tried alot: from PIL import Image, ImageDraw, ImageFont img = Image.new('RGB', (500,500), (255,255,255)) d = ImageDraw.Draw(img) d.text((10,10), "Hello", font=ImageFont.truetype("tahomabd"), fill='BLACK') d.text((10,60), "World", font=ImageFont.truetype("tahomabd"), fill='BLACK') from django.core.files.storage import default_storage as storage JPEG_PATH = "pathtofile.jpeg" storage.exists(JPEG_PATH) storage.delete(JPEG_PATH) JPEG_STORAGE = storage.open(JPEG_PATH, "w") JPEG_STORAGE.write(img) JPEG_STORAGE.close() The above code creates a .JPEG file on the storage location but it is some default file which does not make any sense. Please suggest what is issue with the code. -
my app that i included in installed_apps is not included when i deploy my django to heroku
this is the error in my deployed site every time i open it Environment: Request Method: GET Request URL: http://skinproject.herokuapp.com/ Django Version: 1.9 Python Version: 2.7.13 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/app/.heroku/miniconda/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 134. resolver_match = resolver.resolve(request.path_info) File "/app/.heroku/miniconda/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve 374. for pattern in self.url_patterns: File "/app/.heroku/miniconda/lib/python2.7/site-packages/django/utils/functional.py" in __get__ 33. res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/miniconda/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns 417. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/app/.heroku/miniconda/lib/python2.7/site-packages/django/utils/functional.py" in __get__ 33. res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/miniconda/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module 410. return import_module(self.urlconf_name) File "/app/.heroku/miniconda/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/app/skindisease/urls.py" in <module> 4. from .views import ( File "/app/skindisease/views.py" in <module> 16. from .forms import PostForm File "/app/skindisease/forms.py" in <module> 4. from .models import skindisease File "/app/skindisease/models.py" in <module> 14. class skindisease(models.Model): File "/app/.heroku/miniconda/lib/python2.7/site-packages/django/db/models/base.py" in __new__ 103. "application was loaded. " % (module, name)) Exception Type: RuntimeError at / Exception Value: Model class skindisease.models.skindisease doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. in the Installed Applications: part i can't see the app that i created in django which is … -
using Django crispy forms, how do you shrink the text box for a TextField?
The text boxes that crispy forms lay out for TextField columns are too tall for my app, they are taking up too much screen space. The user can make them taller if desired by dragging the bottom frame line, but the minimum size is too tall. I would like the default height to be 4 rows or so. I tried some ideas I got off related posts, but nothing worked -- the text boxes were still the same height and too tall. Guidance would be appreciated. -
Resolve a list in Django queryset value_list
I'm doing a CSV export of a queryset. For this I dynamically receive the fields by a form and I pass them to the queryset through the filter values_list directly as a list but it launches AttributeError -> 'list' object has no attribute 'split' -
My data base list is not getting displayed if I use forums. Can any one spot the error (must be a silly mistake since I am a rookie)?
I am learning Django, and I have certain entries on the data base that just won't show up. This is my detail (template name) file: {%load staticfiles%} <img src = '{%static album.album_logo%}' alt = 'IMAGE'/> <h1>{{album.album_title}}</h1> <h2>{{album.artist}}</h2> {% if error_message %} <p><strong>{{error_message}}</strong>></p> {% endif %} <form action="{%url 'music:favorite' album.id%}" method = 'post'> {%csrf_token%} {% for songs in album.song_set.all %} <input type = 'radio' id = 'song{{ forloop.counter}}' name = 'song' value = '{{song.id}}'> <label for="song{{ forloop.counter}}"> {{Song.song_title}} {% if song.is_favorite %} <img src = 'C:/Users/my dell/Desktop/project/main/trending/static/logos/dis.png' height="1"> {% endif %} </label><br /> {% endfor %} <input type="submit" value = 'favorite'> </form> It does not display the content b/w the form tags. I am positive the error must be in this file but if you don't see any, I'll edit and provide the views and urls file as well. Help would be appreciated. -
python Django - Convert SQL Query to ORM Query(Subquery)
SELECT *, (SELECT sum(amount) FROM history WHERE history_id IN (SELECT history_id FROM web_cargroup WHERE group_id = a.group_id) AND type = 1) as sum FROM web_car a; It is very difficult to convert the above query to orm 1. orm annotate is automatically created by group by. 2. It is difficult to put a subquery in the 'in' condition please help. -
get all objects of json field from other app
I have a model class with json field: class Collection(models.Model, AdminImageable): units = JSONField(verbose_name='element collection') I'm trying get all objects of this field in other app with such code in my views.py qwe = Collection.objects.filter(pagecollection__page_id=sluglist[0]).order_by('units') l = [] for col in qwe: l.append( apps.get_model(col.units['namespace'], col.units['model'], require_ready=True) ) But, I have a error -- list indices must be integers or slices, not str -
Send to template queryset from A model but get fields in template from B model
I send to template queryset from my A model but i need some additional fields from B model. Shorty i will not paste all of my code. Just short example models.py class A(models.Model): user = models.ForeignKey(User) location = models.CharField(max_length=255) class B(models.Model): message = models.TextField() date = models.DateTimeField() views.py class AllInformationListView(generic.ListView): template_name = 'test.html' context_object_name = 'test' queryset = A.objects.all template {{ test.user }} {{ test.location }} Thank you in advance :) -
GIS/Gdal/OSGeos Import error in django on Windows
I am trying this from hours now and I couldn't get get it solved. I am using this link to setup GeoDjango on Windows. I am getting following error message and I have no clue what to do. All the environment variables are set in Windows and I am able to import with from osgeo import gdal successfully in python terminal as import gdal is deprecated. In Postgresql database I have all extensions available as required like address_standardizer, fuzzystrmatch, ogr_fdw, pgrouting, plpgsql, pointcloud, pointcloud_postgis, postgis, postgis_sfcgal, postgis_tiger_geocoder and postgis_topology. Django Project Settings: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'postgis_24_sample', 'USER': 'postgres', 'PASSWORD': 'Hello123', 'HOST': 'localhost', 'PORT': '', } } GDAL_LIBRARY_PATH = os.getenv('GDAL_LIBRARY_PATH') GEOS_LIBRARY_PATH = os.getenv('GEOS_LIBRARY_PATH') INSTALLED_APPS = [ ... 'django.contrib.postgis', ... ] ERROR: (easy_geodj) C:\Users\dell\Desktop\easy_geodj\easy_geodj\djlocate>python manage.py runserver Unhandled exception in thread started by <function wrapper at 0x066D6330> Traceback (most recent call last): File "C:\Users\dell\Desktop\easy_geodj\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\dell\Desktop\easy_geodj\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\dell\Desktop\easy_geodj\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Users\dell\Desktop\easy_geodj\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\dell\Desktop\easy_geodj\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\dell\Desktop\easy_geodj\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\dell\Desktop\easy_geodj\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "c:\python27\Lib\importlib\__init__.py", line … -
Django model.delete() method returning successful delete but not actually deleting
I am using Django 2.0. I make an AJAX call to a function in Django that should allow a user to vote on a post or remove their vote from a post. When I call the .delete() method on a model, the model returns a result as if it was being deleted, but the record is not removed from the database. Here is the Django function: if request.method != 'POST': raise Http404 post_id = request.POST.get('postId') vote_type = request.POST.get('voteType') # If vote_type isn't valid, 404 if (not any(vote_type in allowed_vote_type for allowed_vote_type in Vote.ALLOWED_VOTE_TYPES) or not 'null'): raise Http404 post_queryset = Post.objects.filter(pk=post_id) post = get_object_or_404(post_queryset) try: vote = Vote.objects.get( post=post, user=request.user ) print('Vote object found') # User has already voted on this post. # Update user's vote. if vote_type == 'upvote': print('vote_type is upvote') if vote.vote_type == 'upvote': print('Deleting vote.') # User just upvoted twice. Expected behavior: Remove their vote ################## ## THIS IS MY PROBLEM ################## vote_delete_result = vote.delete() print(vote_delete_result) if vote_delete_result[0]: # If upvote was successfully deleted, reduce post score post.score -= 1 ################## ## END PROBLEM ################## elif vote.vote_type == 'downvote': print('Changing from downvote') # User is changing from downvote to upvote vote.vote_type = vote_type # Add 2 … -
if I use ModelForms then dont know how to modify fields
The table has 2 fields. trackword and created_by If I include the field "created_by" in the forms.py yes, I get a select list, I can select the creator and it is saved alright, but, obviously it is superfluous that one has to manually make use of a select list to say who is adding the trackword because on the one side, it is the person logged in, and secondly, it creates me the problem that other users will see the other existing users in the select list, and that should not be viewable by others. So, if my Form code looks like this: @login_required def add_trackword(request): form = masterform(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, "The post has been saved!") return HttpResponseRedirect("/trackwords/list/") return render(request, 'masterform.html', {'form': form}) FORM <div class="row" > <div class="panel panel-default col-md-4"> <div class="panel-body"> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-block btn-success" value="Submit"> </form> </div> </div> </div> as you see, the form is automatically created by the django model form engine and while I dont HAVE TO write any field, neither CAN I If I need to. or I dont know how how to. I would like … -
Django, users in group sorted
I want to show the users of each group of my Django app. {% for group in groups %} <h2>{{ group }}</h2> {% for user in group.user_set.all %} <div> {{ user }} </div> {% endfor %} {% endfor %} This works great, but for this specific template, I'd like the users to be sorted by their date_joined attribute. How could I achieve that? I suspect that it could be done using a custom filter but I am not really sure if it is the right way or if there is a better one. -
How to display many to many field as searchable choice
In my django app I have a many to many connection with a lot of choices. In the admin panel I could solve this problem very elegantly through django-salmonella But now I would like to have the possibility to have a searchable choice in a user accessible form. How can I do that? Is there a good package that I can use? -
Translating 'Django-Oscar'
I want to learn how to build an opensource e-commerce site. For this purpose I'm using 'Django' framework with 'Oscar' extension. I read the whole tutorial here: https://django-oscar.readthedocs.io/en/releases-1.5/index.html, where there is a Translation tutorial. I followed it (must say that it has missing steps). This part says that, in order to translate a page you must create two folders and a symbolic link: mkdir locale i18n ln -s $PATH_TO_OSCAR i18n/oscar Then, for each language you want to translate: ./manage.py makemessages --symlinks --locale=<language code> That's correct but, besides that, you must compile .po files in order to get the final traduction in locale folder (.mo files). After that you must include the traductions into settings.py of project (or app). This is done with the following code: In terminal (from root directory of project): $ django-admin.py compilemessages In settings.py add: LANGUAGES = [ ('de', _('German')), ('en', _('English')), ('es', _('Spanish')), ] (Note: This is my case, where I want to translate the store into German, Spanish and English) After doing that, I run my server and only these three languages appear in the select language box, but when I push the button in order to translate the page, It returns the default language … -
django restframework _ OneToOne field save()
I have 2 models in my project .model A and B .model B has a OneToOne relation with model A. I wrote a serializer class for model B. in .create() function I have a problem for saving model B .cause I need to override the save() function in B model for inserting Slug value.the error is : save() got an unexpected keyword argument 'force_insert' class A(models.Model): address = models.Charfield(max_length=160) class b(models.Model): a = models.OneToOneField(AdIfo, related_name='ad_info', primary_key=True, on_delete=models.CASCADE) slug = models.SlugField(unique=True, db_index=True, blank=True) def save(self): self.slug ="%d%s" %(self.pk, slugify(self.title)) super(B, self).save() serializers.py class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = "__all__ class BSerilizer(serializers.ModelSerializer): a = ASerializer(many=False, required=False, allow_null=True) slug = serializers.SlugField(read_only=True) class Meta: model = B fields = '__all__' def create(self, validated_data): info_data = validated_data.pop('ad_info') A.objects.create(**info_data) ad = B.objects.update_or_create(**validated_data) A.objects.update_or_create(ad_info=adgame, **info_data) ad.save() return ad -
AJAX Post request not sending values to Django View
I am trying to pass some data from the frontend to the backend of my site using AJAX. This is the post request view in my django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} return JsonResponse(args) This is the function I have in javascript. I know the correct value is being passed because the console.log(teacher_id) prints the right value. function send(teacher_id){ console.log(teacher_id) var url = window.location.pathname; $.ajax({ method: "POST", url: url, data: { 'teacherID': teacher_id, }, dataType: 'json', success: function (data) { //location.href = data.url;//<--Redirect on success } }); } When the code is run, and the print statement in my view is run, regardless of what the teacher_id is, None is printed. what is wrong with the code? -
Email verification after signup code working good but not email send
How to solve this problem that code run work and terminal show that Content-Transfer-Encoding: 7bit Subject: Activate your service account. From: webmaster@localhost To: yeasincse2012@gmail.com Date: Sat, 30 Dec 2017 04:24:49 -0000 Message-ID: <20171230042449.1841.3324@1.0.0.127.in-addr.arpa> Hi uu, Please click on the link below to confirm your registration: http://127.0.0.1:8000/activate/MTc/4sf-5894ea0e96ff8411ac73/ [30/Dec/2017 04:24:49] "POST /signup/ HTTP/1.1" 200 63 when check mail but not mail found? This code given link pastebin.com here that -
Where are the historical models?
The doc says: When you run migrations, Django is working from historical versions of your models stored in the migration files. But I can't see them there. I have data migrations with RunPython operations, but no historical models there as well. Could it be that Django generates them on the fly? How does it do it? And while we're at it, let me confirm if I understand it correctly. Historical models are models as they were when a migration was written? Except for some limitations, like no custom methods. -
Django Custom User admin page
I am currently trying to implement my admin page for the custom user model I have made. I have added a field called 'email_confirmed', and I am trying to get this to display on the Admin page. This is the model: class User(AbstractUser): """User model.""" abstract = True username = None email = EmailField(_('email address'), unique=True) email_confirmed = BooleanField(default = False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'second_name'] objects = UserManager() def get_full_name(self): fname = self.first_name lname = self.last_name return '{} {}'.format(fname, lname) def email_confirmed(self): return self.email_confirmed As you can see I have tried writing a method called email confirmed to get this to work, however it didn't work. This is the UserAdmin I have in my admin.py: @admin.register(get_user_model()) class UserAdmin(UserAdmin): class Meta: model = get_user_model() fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email_confirmed')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'email_confirmed()'), }), ) list_display = ('email', 'first_name', 'last_name', 'is_staff', 'email_confirmed') search_fields = ('email', 'first_name', 'last_name', 'email_confirmed') ordering = ('email',) Thanks for the help -
How to create django project in Windows?
I tried of creating project in Windows When I type django-admin.py startproject projectname it takes but it won't created in folder . Everything is installed and previous project also running fine .Please help me out ! -
Migrate existing live Django site from one server to another along with user records intact
I have deployed a Django site on GoDaddy Django "droplet" for a while and users have been using the site to keep their records. Now that GoDaddy is discontinuing the service, I would like to migrate the entire site with all records intact to DigitalOcean. How does one go about doing this? -
Pycharm type hinting for querysets
I use python 2.7 and use docstring for type hinting in pycharm. Having set :rtype of methods to list of ClassName it provides great code completion. I wanted to know whether I can do sth similar for querysets. (eg sth like :rtype: Queryset of ModelName) -
How to append a database table created by a django model
I am following the tutorials https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html on making a simple user registration website. The key model defined in model.py is from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() which creates the table profile in the database. My question is how do we append this table to include information like user's first/last name and email. I know those information is stored in auth_user, but it would nice to have everything on one table. I am new to django platform. Any explanation or reference is greatly appreciated. -
Django Dynamic Form with Json Input
I know this question is bit vague but i could not find exact solution anywhere. I am at loss having very poor knowledge on UI. Any help will be greatly appreciated. I have a simple Json like below passing to site.html template. { "datacenter1" : ["IP1", "IP2",...,"IPn"], "datacenter2": ["IP1", "IP2",...,"IPn"], "datacenter3": ["IP1", "IP2",...,"IPn"], ..... ..... "datacentern": ["IP1", "IP2",...,"IPn"], } I want to create form for User with datacenter as main section with radio button and IPs are subsections with check boxes below datacenter. User should be able to select one datacenter and multiple/all IPs of that specific DC o datacenter1 (Radio) IP1 IP2 IP3 ..IPn (Check) o datacenter2 (Radio) IP1 IP2 IP3 .. IPn (Check) o datacenter3 (Radio) IP1 IP2 IP3 .. IPn (Check) ..... o datacentern (Radio) IP1 IP2 IP3 .. IPn (Check) SUBMIT number of datacenter and its IPs are variable, so Json size keeps varying all the time.I a looking for Django template than take the Json, iterate and create a for that looks like below. I have multiple solutions using bootstrap but no luck. Since I have almost zero knowledge on Javascript, Bootstrap i am so far direction less. -
How to include links in blog post
I have built a blog with Django. In my BlogPost model I have a text field named "content". When I compose a blog post via the admin panel, any custom HTML (links, code blocks, external images) that I enter is rendered in the template as static, literal text - not it's true semantic HTML. I want to create a blog that allows blog posts to use markdown. No one else is making posts except me, and there is not client-facing form throughout the entire site (except the admin login page). How do I turn off escaping so that I can use custom HTML like italics, bold, links, external images, h1's, h3's, paragraphs, etc in my blog posts? I have been trying to find a resource to learn from but am coming up short. Should I use a preconfigured markdown app, or roll my own?