Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URLField with custom scheme
Django's django.db.models.URLField uses a django.core.validators.URLValidator: class URLField(CharField): default_validators = [validators.URLValidator()] Since it does not specify the schemes to accept, URLValidator defaults to this set: schemes = ['http', 'https', 'ftp', 'ftps'] I want my URLField to accept ssh:// URLs, so I tried this: class SSHURLField(models.URLField): '''URL field that accepts URLs that start with ssh:// only.''' default_validators = [URLValidator(schemes=['ssh'])] However when I try to save a new object with a valid ssh:// URL, I get rejected. This also happens if I skip inheriting from URLField and inherit from CharField directly: class SSHURLField(models.CharField): '''URL field that accepts URLs that start with ssh:// only.''' default_validators = [URLValidator(schemes=['ssh'])] def __init__(self, *args, **kwargs): kwargs['max_length'] = 64 super(SSHURLField, self).__init__(*args, **kwargs) But if I use the URLValidator directly in a test, it works: def test_url(url): try: URLValidator(schemes=['ssh'])(url) return True except: return False >>> test_url('ssh://example.com/') True >>> test_url('http://example.com/') False -
Post json to django rest framework API with jquery-ajax not working
i have the models: class Publicacion(models.Model): usuario = models.ForeignKey(User) fecha = models.DateField(auto_now_add=True) class Estado(models.Model): publicacion = models.OneToOneField(Publicacion, on_delete=models.CASCADE) texto = models.TextField() imagen = models.ImageField(upload_to='estados', blank=True, null=True) so my json should be like { "estado": { "texto": "", "imagen": image } } my jquery ajax is $$.ajax({ beforeSend: function(request) { request.setRequestHeader("Authorization", "Token " + token); }, url: "url", dataType: 'JSON', type: 'POST', data: JSON.stringify({"estado":{"texto": "text", "imagen": dataImg}}), success: function (data) { myApp.alert("Correcto"); }, error: function (xhr, ajaxOptions, thrownError) { console.log(xhr); } }); but when i send it with i have a 400 bad request response, server says that "estado" is required, any idea what's the problem? -
How to reset page number in Django ListView
How to reset page number in Django ListView. There is a view with filter form, results are paginated. For example: First request returns 50 pages, we come to 40 page. Then we change filter, and result is just 10 pages. In the url we have page number 40. And we get 404 page, because result just 10 pages. Seems I must redirect to the first page while 'POST'. How to make it in ListView -
creating users with Django REST Framework - not authenticate
I am working with Django users, and I've hashed the passwords when I create an user with Django REST Framework and I override the create and update methods on my serializer to hash my passwords users class UserSerializer(serializers.ModelSerializer): #username = models.CharField() def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def update(self, instance, validated_data): for attr, value in validated_data.items(): if attr == 'password': instance.set_password(value) else: setattr(instance, attr, value) instance.save() return instance class Meta: model = User fields = ('url', 'username', 'password', 'first_name','last_name', 'age', 'sex', 'photo', 'email', 'is_player', 'team', 'position', 'is_staff', 'is_active', 'is_superuser', 'is_player', 'weight', 'height', 'nickname', 'number_matches', 'accomplished_matches', 'time_available', 'leg_profile', 'number_shirt_preferred', 'team_support', 'player_preferred', 'last_login', ) My views.py is this: class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer filter_fields = ('username', 'is_player', 'first_name', 'last_name', 'team' , 'email', ) My REST_FRAMEWORK settings are: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'PAGE_SIZE': 10 } The inconvenient that I have is that when I create and user via rest framework, the password is hashed, but I cannot sign in or login via rest authentication and Django admin too. How to … -
what's the difference between cleaned_data and normal data? - django
as mentioned in title...what's the difference? I have seen people keep on saying use cleaned_data and in videos people still say so but only says it cleans the data but when I use print print form.cleaned_data.get('title') print request.POST.get('title') I don't see any difference though. At first I thought it's those character escape and so but tested and doesn't seem so. which is actually a preferred way since there doesn't seem to have differences? -
django drf left join
I have this model: class Env(models.Model): env_name = models.CharField(max_length=100, unique=True) is_enabled = models.CharField(max_length=1, choices=ENABLED, default='Y') def __unicode__(self): return unicode(self.env_name) I also have this model ... class Hosts(models.Model): host_name = models.CharField(max_length=200, unique=True) host_variables = jsonfield.JSONField() host_env = models.ForeignKey(Env, models.DO_NOTHING, related_name='host_env') I wish to have a serialized representation equivalent to a join. I'm trying to get rows that contain host_name and env_name I can't seem to find the right way to serialize it I'm have so far ... class HostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Hosts fields = ('host_name', 'ip_address', 'is_enabled','is_managed','managed_users') I can't seem to find the right way to get the name of the env in each row of my Hosts results. What am I missing? -
Nginx Bad Gateway after altering project structure
I have a django app hosted on AWS and have been cleaning up some aspects of the project structure. One of these cleanups involved removing a parent folder in the root directory and putting my appspec.yml file (used for CodeDeploy) in the folder with docs. So I am going from this: myproject/ appspec.yml myproject/ requirements/ docs/ myproject/ manage.py myproject/ __init__.py urls.py wsgi.py settings/ To this: myproject/ appspec.yml requirements/ docs/ myproject/ manage.py myproject/ __init__.py urls.py wsgi.py settings/ I made the following prior to rebooting the instance: Changed gunicorn.conf location from root /var/www/myproject/myproject/myproject/myproject to root /var/www/myproject/myproject/myproject Changed nginx.conf location from root /var/www/myproject/myproject/myproject/myproject to root /var/www/myproject/myproject/myproject I am now seeing 502 BAD GATEWAY when I try to access my website URL and seeing failed (104: Connection reset by peer) while reading response header from upstreamwhen looking at nginx error.log. This clearly happened because I messed with the project directories. Did I miss something else that needs to change or was it just a bad idea to change the directories in the first place? Current nginx.conf server { listen 80; server_name www.wehealth.co; return 301 http://wehealth.co$request_uri; } server { listen 80; server_name myproject.co; ##Deny illegal Host headers if ($host !~* ^(myproject.co)$ ) { return 444; … -
Django - EasyRTC: socket.io 404 error
I have deployed the EasyRTC server on an remote machine. The demos are working properly. I want to make my Django app to load a HTML page which starts a videocall trough my EasyRTC server. However when I load the page the browser console says that http://localhost/socket.io/?EIO=3&transport=polling&t=Lcvt96k is not found. I'm loading the Socket.io client lib from my EasyRTC server. -
Disallowed Host at Django
I'm just starting out with Django for the first time. So I create a django project and run the command python3 manage.py runserver 0.0.0.0:8000 Instead of getting the expected django homepage, I get the following error message, DisallowedHost at / Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS. Request Method: GET Request URL: http://0.0.0.0:8000/ Django Version: 1.10.5 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS. Exception Location: /usr/local/lib/python3.5/site-packages/django/http/request.py in get_host, line 113 Python Executable: /usr/local/opt/python3/bin/python3.5 Python Version: 3.5.2 I haven't yet scratched the surface of django, so would appreciate some help as to how to fix this? -
from .forms import RegisterForm error
I got from .forms import RegisterForm ImportError: cannot import name RegisterForm error. I cannot understand . of from "." forms. What means of .? I think I can resolve this error when i can understand . mean. Now, I write urls.py of accounts app, from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.decorators.http import require_POST from .forms import RegisterForm def index(request): context = { 'user': request.user, } return render(request, 'accounts/index.html', context) @login_required def profile(request): context = { 'user': request.user, } return render(request, 'accounts/profile.html', context) def regist(request): form = RegisterForm(request.POST or None) context = { 'form': form, } return render(request, 'accounts/regist.html', context) @require_POST def regist_save(request): form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('main:index') context = { 'form': form, } return render(request, 'accounts/regist.html', context) What should i do to fix? -
Django upload images and place in a directory for each user
I am looking to create a new directory for each user. The code for the model is below, and should look something like this. How do I access the current username that is created during registration? I put a placeholder function getcurrentusername() that should return a string so the directory created for the image is username/profile_images/ class UserProfile(models.Model): user = models.OneToOneField(User) website = models.URLField(blank=True) picture = models.ImageField(upload_to=getcurrentusername()+'\profile_images', blank=True) def __unicode__(self): return self.user.username -
Django Variable Based on the Range of an Object
Below are partials of my view and template that identifies plaque location on veteran memorial wall. Template ... wall = models.CharField(max_length=10, blank=True, help_text='lowercase letters') direction = models.CharField(max_length=10, blank=True, help_text='north, south, east or west (lowercase)') row = models.SmallIntegerField(null=True, blank=True, help_text='use a number') plaque_num = models.SmallIntegerField(verbose_name='Plaque Number', null=True, blank=True, help_text='use a number') ... view def plaque_list(request): today = timezone.now().date() queryset_list = Plaque.objects.active().order_by("first_name") ... I would like to create a new variable that is the concatenated value of the wall letter and a string value of the plaque_num range. For example - if the plaque_num is in the range of 1-10, assign the value 10, if 11-20, the value of 20, if 21-30, the value of 30 etc... These values concatenated would look like a10, a20, a30 etc... I hope this makes some sense. I need these values so that I can place location markers on a map. Here is a link to the dev site so you can get an idea - http://www.new.soledadmemorial.com/plaques/ Thank you for your help. -
Django : TypeError: static() got an unexpected keyword argument 'document_root'
I am trying to view my uploaded image through web-browser/DRF-browsable API. So I added MEDIA_URL and MEDIA_ROOT to my setting.py file. When I trying to run the code , it showing TypeError: static() got an unexpected keyword argument 'document_root' . Here is my relevant portions of code, settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR,'Images') MEDIA_URL = '/Images/' urls.py from django.conf.urls import include, url from django.contrib import admin from django.templatetags.static import static urlpatterns = [ # Examples: # url(r'^$', 'project.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', index), url(r'^health$', health), url(r'^admin/', include(admin.site.urls)), url(r'^sample/',sampelview), url(r'myapp/',include(myRouter.urls)), url(r'^test/$', testRequest), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
django-tinymce HTMLField covering model field description in admin/add
The Issue The name of the model field is not visible in Django's admin "add" page when using django-tinymce's tinymce_models.HTMLField(). The Name: field is in the picture, but the Description field is not. How can I display the Description text over the TinyMCE editor? The Model class Project(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=255) description = tinymce_models.HTMLField() started = models.DateField(blank=True) Versions Django 1.10.4 django-tinymce 2.4.0 Tiny MCE 4.5.2 A Bunch of Code https://codepen.io/anon/pen/xgqRqM HTML is directly from Chrome Developer Tools on the Django admin page for adding this model. CSS is both Django's and Tiny MCE's. JS is from the Tiny MCE theme. It doesn't seem to render correctly on Codepen so I'm not sure how useful it will be... Let me know if there's any more clarifying information I can provide. More Pictures I know the text Description: is in the HTML: This guy is covering it up? -
How do I render ForeignKey fields in my template?
I'm making a comment system for my django app and i've been told it's best to make a seperate model for comment-voting. So i've done that and here's my models.py: class Comment(models.Model): user = models.ForeignKey(User, default=1) destination = models.CharField(default='1', max_length=12, blank=True) author = models.CharField(max_length=120, blank=True) comment_id = models.IntegerField(default=1) parent_id = models.IntegerField(default=0) comment_text = models.TextField(max_length=350, blank=True) timestamp = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return self.comment_text class CommentScore(models.Model): user = models.ForeignKey(User, default=1) comment = models.ForeignKey(Comment, related_name='score') upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) def __str__(self): return str(self.comment) Here's my views.py where the comments are created: comment_list = Comment.objects.filter(destination=id) score = CommentScore.objects.all() if request.is_ajax(): if comment.is_valid(): comment = Comment.objects.create(comment_text=ajax_comment, author=str(request.user), destination=id) comment.save() com_score = CommentScore.objects.create(comment=comment) com_score.save() So the comment works fine, but as you can see a couple lines later i'm trying to then create a CommentScore instance to match with the comment. In my template, I've rendered each comment and it's fields (comment_text, author etc), but I want to render the upvotes field associated with that comment. How would I do this? template {% for i in comment_list %} <div class='comment_div'> <h3>{{ i.author }}</h3> <p>{{ i.comment_text }}</p><br> </div> {% endfor %} -
How can I keep GET instance on template inputs
I have a simple search bar, I would like to keep the data the user submited and show it on the search bar after the form submission. How can I do that ? I'm using GET for the search method, but I do not save any searched items on any model and I prefer not to, I was wondering if there was another way to show it without using the database storage. Here is what my code looks like : views.py def index(request): allGigs = Gig.objects.filter(status=True) context = {'gigs': allGigs} return render(request, 'index.html', context) def search_gigs(request): title = request.GET['title'] request.session['title'] = title #a try with session, but the data is kept once the user returns to front page... gigs = Gig.objects.filter(title__contains=title) return render(request, 'index.html', {"gigs": gigs}) models.py Gig Model has title CharField. index.html <form role="search" method="GET" action="{% url 'search' %}"> <input type="text" name="title"> <input type="submit" value="submit"> </form> urls.py url(r'^search/$', views.search_gigs, name='search'), url(r'^$', views.index, name='index'), I thought about using Django Sessions but the problem is that the user can only see what he search after returning to the index page, any suggestion ? -
The SECRET_KEY setting must not be empty - django+pycharm
For sure I searched a few posts but none of them helped though. Even the closest one didn't help too. I am currently using pyCharm installed django using virtual environment. As I have tried lots of ways but no luck using pycharm to run the project BUT if I do it in the terminal by using python manage.py runserver the server runs properly though. Somehow in pyCharm after all the setup, it just wouldn't let me run. Where am I setting it wrong in pycharm? Anyways, I am getting this error raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. my manage.py as some posts were talking about this but I see it's setting up properly though #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CodingEntrepreneurs.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget … -
How to determine previous URL in django
How do I find the previous URL that referred to the current one in Django? For example, I want different output from my home page if it was referred from the login page or from the sign up page or from elsewhere? I can see what I want in the Referer section of Request Headers in Chrome Developer Tools, but I can't seem to access the value using request.referer. I don't want to append the referer using index.html?return_url={{ request.path }} because I'm not certain where it's coming from. -
Django - url with variable (slug)
This is my template file: {% for tag, count in tags.items %} <a href="{% url 'tags' slug=tag.slug %}">{{ tag }}</a> ({{count}}), {% endfor %} urls.py url(r'^tag/(?P<slug>[\w-]+)/$', views.tags, name='tags'), I am trying to take {{ tag }} as slug parameter. Is it possible? Next I would try to create page where I will list all pages that cointain tag in keywords field in Sites model. -
How to handle versioning with django?
Our current solution is to create two apps at the beginning, APP_V1 and API_V1. APP_V1 will handle the logic of the app and the models. While API_V1 will handle the API logic by making calls to to APP_V1. When we need to create a new API version we will create a new app ( eg: API_V2 ) to handle requests from a new API version. When we need to change the logic or change our models we will create a new app ( EG: APP_V2 ) to handle the changes. Our goal is to avoid doing migrations on live apps and to have the ability to create new versions of our API. During our research we have found a lot of answers into how to use django-rest-framework with django. We don't want to use django-rest-framework or other frameworks on top of django to handle our versioning. Can you think of a better solution? Overview of the file system -
How can I save only specific fields in Django?
When I update my Usuario form I have a problem the password field is save in blank but I want to save only specific fields and don't affect password field. I try this if usuario.contrasenia == '': form.save(update_fields=['nombre', 'correo_electronico', 'direccion', 'usuario', 'id_perfil', 'fecha_modificacion']) but I get this save() got an unexpected keyword argument 'update_fields' The main problem is that I don't know how override the save method to save only specific fields. -
Is it unrecommended to run Django on IIS?
I'm going to run Django-based webpage on my not-using Windows labtop. Some material that I found from web says that I have to use PyISAPIe to run Django on ISS but its last update day is 2009-06-17... You can see that here : https://sourceforge.net/projects/pyisapie/files/pyisapie/ Is it safe to use that such old module? Or can you let me know what I should do without PyISAPIe to run Django on Windows server? -
How can I replace blank spaces with hyphens on django-taggit?
Django-taggit separates each word when there is a blank space as if there were commas. for instance, when I enter tag[My Word] it gives me 2 separate tags (tag[my] tag[word]). To resolve this issue I would like to replace all blank spaces after the first word of the tag with hyphens (-) in order to not count the first blank space after a coma as a hyphen. What I expect django-taggit to do : tags[a-tag,another-tag]. What I don't expect django-taggit to do : tags[a, tag, another, tag] or tags[a-tag,-another_tag]. Where and how should I modify django taggit in order to do it ? -
Dictionary in a model of django rest framework
I have to have this in my model: content: (Dictonary) recipient: (Dictionary) type: (Facebook, Address or Email) name: (name or email) id: (id) textfields: (Array) title: (title) text: (text) size: (size) I saw this post and this one, but I can't do it. For me is actually the first time that someone tells me that he needs exactly that structure in the model. I have never seem something like that before. But I'm also new :) so, maybe it's just that I don't know how to do it. Maybe someone here with more experience than me can help me. I don't have any idea. EDIT I mean, I don't have to have it so in the model, but I need to accept POST, DELETE, PUT requests with that structure as well return GET request with that structure. -
ForeignKey inconsistently working across Sites
I have a parent BlogPost on one Site and a number of children ('clones') BlogPosts on other Sites. class BlogPost(object): clone_source = models.ForeignKey( "self", related_name='clones', ) If I'm looking at a Child active_post and I run parent = active_post.clone_source siblings = parent.clones.all() I correctly get all the children as expected. However, if I'm on the Parent as active_post, active_post.clones.all() returns an empty list. It's the same code, no? Also, children = BlogPost.all_sites.filter(clone_source=active_post) returns all the children correctly. What's the difference?