Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
how to have options in urls in django 2.0
In Django 1 I used to have url choices like this: url('meeting/(?P<action>edit|delete)/', views.meeting_view, name='meeting'), How I do this in Django 2.0 with the <> syntax: Maybe something like this? path('meeting/(<action:edit|delete>)/', views.meeting_view, name='meeting'), -
Django New lines in view variable
I am sending email with Django using Sendgrid. I have a variable message for the message that will send, however the message holds the value of a few other variables. I would like them to be on different lines to make the email easier to read. Here is what I have, although it is not working. if form.is_valid(): name = form.cleaned_data.get('name') phone = form.cleaned_data.get('phone') email = form.cleaned_data.get('email') party_size = form.cleaned_data.get('party_size') form_message = form.cleaned_data.get('message') listing_address = listing.address message = name + "\n" + phone + "<br>" + email + "<br>" + party_size + "<br>" + listing_address send_mail('New Lead', message, 'leads@studentcribz.com', ['email@gmail.com'], fail_silently=False) The email is being sent as this: garrett 1234234<br>g@d.com<br>2<br>address would be here Although I would like this: garrett 1234234 g@d.com 2 address would be here -
birthday_year&birthday_month&birthday_day cannot be gotten
birthday_year&birthday_month&birthday_day cannot be gotten. I wrote in views.py @require_POST def regist_save(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) context = { 'regist_form': regist_form, 'profile_form': profile_form, } if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid(): try: username = regist_form.cleaned_data.get('username', None) email = regist_form.cleaned_data.get('email', None) exist_user = User.objects.get(Q(username=username)) exist_email = User.objects.get(Q(email=email)) if exist_user != "": messages.warning(request, 'That user name is already used.') if exist_email != "": messages.warning(request, 'That email is already used.') return render(request, 'registration/regist.html', context, messages) except User.DoesNotExist: regist = regist_form.save(commit=False) regist.is_staff = True regist.save() profile = profile_form.save(commit=False) profile.user = regist sex = request.POST.get("sex", "") year = request.POST.get("year", "") month = request.POST.get("month", "") day = request.POST.get("day", "") profile.sex = sex profile.birthday_year = year profile.birthday_month = month profile.birthday_day = day profile.save() return render(request, 'registration/detail.html') else: return render(request, 'registration/regist.html', context) in forms.py class ProfileForm(forms.ModelForm): class Meta: model = NewUser fields = ( "birthday_year", "birthday_month", "birthday_day", "sex" ) in models.py class NewUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday_year = models.CharField(max_length=100, null=True, default=None) birthday_month = models.CharField(max_length=100, null=True, default=None) birthday_day = models.CharField(max_length=100, null=True, default=None) sex = models.CharField(max_length=100, null=True, default=None) in regist.html <form class="form-horizontal" action="/accounts/regist_save/" method="POST"> <div class="form-group-lg"> <label for="id_username">username</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label … -
Django sendfile with nginx failed to send the file as attachment
I'm using django-sendfile for sending a large file as attachment to the UI. This works with sendfile.backends.simple backend but when I use sendfile.backends.nginx, it returns 404 error on nginx logs. I think there was something wrong with my nginx configuration. views.py class FileDownloadView(View): def get(self, request, id_file): obj = FileCombined.objects.get(id_file=id_file) return sendfile(request, obj.path, attachment=True) settings.py SENDFILE_BACKEND = "sendfile.backends.nginx" SENDFILE_ROOT = os.path.join(BASE_DIR, 'media') SENDFILE_URL = '/media' /etc/nignx/sites-enabled/myapp server { # simple reverse-proxy listen 80; server_name localhost; sendfile on; # serve static files location /static { proxy_pass http://127.0.0.1:8000/static; } location /media/ { internal; root /home/foo/project/django-combine/media; } location / { proxy_pass http://127.0.0.1:8000; } } nginx/access.log 127.0.0.1 - - [30/Dec/2017:08:20:01 +0530] "GET /file/id/5114a7721b6943fb31fc143a20adbec630bb5eb2516d7574b881454209338eed/download/ HTTP/1.1" 404 208 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" 127.0.0.1 - - [30/Dec/2017:08:25:01 +0530] "GET /file/id/5114a7721b6943fb31fc143a20adbec630bb5eb2516d7574b881454209338eed/download/ HTTP/1.1" 404 208 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" -
How to customize username validation
I am trying to customize username validation for the django.contrib.auth User model. It says Usernames may contain alphanumeric, _, @, +, . and - characters. but I'd like to make it so that it would be invalid if the user made a username with @, ., -, +. How would I go about overriding this validation so when the user creates a username it is using my custom validation instead of the original UnicodeUsernameValidator? I am using my own custom User model, but i'm inheriting from AbstractBaseUser Is there a simple way to add my username validation? -
django - use environment variables in debian not working
It might be simple thing but I just can't seem to get it running. in my Django project's settings, I have these db settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PWD'), 'HOST': 'xxxx.yyyyy.eu-central-1.rds.amazonaws.com', 'PORT': '', } } and in /etc/environment I have set the variables and also in .profile. but this is just not working and I am getting: (1045, "Access denied for user 'www-data'@'132.31.48.116' (using password: NO)") If I remove and hardcode the credentials, it works. so obviously my env variables are located in wrong place. can someone please give some look at it? I am using Debian 4.9.51-1 (2017-09-28) x86_64 in ec2 server