Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mezzanine keyword_tags give me an empty page
I have a Mezzanine site configured with a blog that has 3 categories. On every blog post, there are the associated with it, tags or keywords. When I click on a keyword I get an empty page while I should be getting a list with all the blog posts associated with that keyword. The url goes like mysite/blog/tag/conference yet nothing appears there. Should I make a new template so as have that functionality? If so, what tags should I use in my template and what urls? I am new to Django generally so I am really stuck with this one. Thanks in advance. -
Setting up Django on a droplet that has Apache installed
I have a DigitalOcean droplet that is running Ubuntu and is using Apache and PHP for the web server. I need to move to using Django instead. I already wrote the server using Django. If possible, I'd rather not delete any of the PHP files from the server or delete Apache. How would I go about doing that? I was also using a MySQL server on Apache. Would you recommend using the default SQLite with Django? Either way, how would I move the data from the old Apache DB to the Django one? -
has_object_permission is not called for custom defined API
I have a viewset SampleViewSet for API POST /api/samples/sample_id/check. I have defined object level permission for it. class SamplePermission(BasePermission): def has_object_permission(self, request, view, obj): print "checking object level permission" return True class SampleViewSet(viewsets.ModelViewSet): permission_classes = (SamplePermission) @detail_route(methods=['post']) def check(self, request, pk=None): if pk: print "check" The function has_object_permission is not getting called when I call the API "POST /api/samples/check". What could be the reason? -
Add button to table in Django Admin
I need to add a column in the table which will be a button to delete the record models.py class Worker (models.Model): name = models.CharField ('Name', max_length=30) surname = models.CharField ('Surname', max_length=30) admin.py class WorkerAdmin (admin.ModelAdmin): list_display = ('surname', 'name') search_fields = ('surname', 'name') list_filter = ('surname', 'name') admin.site.register(Worker, WorkerAdmin) -
django+gunicorn+nginx ,https redirect issue
my server is django + guincorn + nginx ,after i add ssl certification, nginx is set entire https. when receive http & https request , nginx give it to gunicorn as http. my problem is , in my program i sometimes use httpredirect , so broswer get redirect response from gunicorn and re-request as http, so nginx get http and redirect to https.......(yes, so complicated). i don't think it's a good way to work, and may cause some other problems. so how can i setup nginx or server to make the 'http redirect' from gunicorn respone to browser from nginx may it changed to 'https redirect' ?? -
TypeError: node is null . Some Javascript library/function is not working in mozilla after installing django-htmlmin
Some Javascript library/function is not working in mozilla after installing django-htmlmin but others browser its working fine.Please help,thanks in advance! In browser console I am getting - TypeError: node is null . -
Query in django based on a list
I have a list for example: home_type = ["villa", "apartment", "flat"] And I want to query my objects in my database: agencies = Agency.objects.filter(home_type_available__contains= home_type) I think there is a problem with my query. I want to have all the Agency that contain at least one of the "home_type" in their "home_type_available" -
django channels session resetting
I am trying to work with active users and sessions with channels. However often my channel gives a AnonymousUser while i am logged in. @login required on the normal view) Also on every call my session seems to save. @channel_session_user_from_http def ws_connect(message): print(message['headers']) drop_map(message) # message.user.active_map works like it is supposed to message.user.active_map.websocket_group.add(message.reply_channel) def ws_message(message): payload = json.loads(message['text']) payload['reply_channel'] = message.content['reply_channel'] Channel("maps.receive").send(payload) @channel_session_user @catch_client_error def map_background(message): # Now message.user is anonymous user and code crashes map_obj = message.user.active_map character = message.user.active_character grid = map_obj.template.static_grid.slice_grid(character.location.x, character.location.y, message.user.settings) message.reply_channel.send({ "text": json.dumps({ "action": "load_background", "name": map_obj.name, "grid": grid, }), }) At the ws_connect it all works as it should and i get my logged in user. However when I make a call on map_background, suddenly my user is an anonymous user. I use redis as my channel backend. headers: [[b'cache-control', b'no-cache'], [b'accept-encoding', b'gzip, deflate'], [b'cookie', b'csrftoken=mlI5ODljY3eJ3Le1dPnv1VrmZznAVCbo7XU9JAIK8bb8urjbcEimsZRUqczCzzdI; sessionid=druv90lxnz36yahnr7zcybojh5xlzdl2'], [b'connection', b'keep-alive, Upgrade'], [b'sec-websocket-version', b'13'], [b'origin', b'http://localhost:8000'], [b'sec-websocket-extensions', b'permessage-deflate'], [b'host', b'localhost:8000'], [b'pragma', b'no-cache'], [b'upgrade', b'websocket'], [b'accept-language', b'en-US,en;q=0.5'], [b'user-agent', b'Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0'], [b'sec-websocket-key', b'mx5wy9w8HxH2dQ6ls5/rUg=='], [b'accept', b'text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8']] -
django rest api curl giving notification gateway timeout
When running the curl on rest api : curl -X POST -H "Authorization: Token <token_id>" "http://localhost:4000/api/.....url" I am getting The system cannot communicate with the external server The Internet server may be busy, may be permanently down, or may be unreachable because of network problems.Please check the spelling of the Internet address entered.If it is correct, try this request later.If you have questions, please contact your organization's network administrator and provide the codes shown below. Username:my username Source IP: my ip URL: POST http://localhost/api/.....url Category: Reason: UNKNOWN Notification: GATEWAY_TIMEOUT as the response. It was working properly earlier. Can you tell me what is wrong. I made the server run in localhost:4000 and gave it on curl but the response in giving gateway timeout. -
Fill two other fields of a formset depending on autocomplete selection
I would like to fill two other fields automatically depending upon the selection someone makes in an autocomplete field, using django-autocomplete-light. However, my java script is not that good, so I don't realy know where to start. Any help is very much appreciated. User submit there publiciced papers. There is a "person" autocomplete field in a formset (its a many to many realation for authors and other people that worked towards the publication). If a user chooses a person, I want that persons name and family name automatically filled in two other fields in that formset, so that users can make changes (also, it is a prerequisite from the data modell). Same if they change or delete the selected person. I thought best would be to have a view for name and a view for family nam in order to retrive those two with the id I could get from the autocomplete field. However, how do I do the asyncrounos retrival of the names and fill them into the two fields? Thank you! Best Teconomix -
Django Serving Static Files not loading
Setting up a new django application with the following settings: import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) DEBUG = True INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'kb/media') STATIC_ROOT = os.path.join(BASE_DIR, 'kb/static/') Setup a template {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>HomePage</title> </head> <body> <img src="{% static 'img/girl.png' %}"> <img src="/media/boy-512.png"> </body> </html> I assume there's an issue with the settings of how it's supposed to get the static files. In this case the directory for the static image girl.png is kb\kb\static\img\girl.png -
query two objects with different slug on Django ORM?
I have a model class Person(models.Model): name=models.CharField() slug=models.SlugField() Now if I want to get persons with slugs john and thomas what should I query to get both objects in a tuple or a list, with slug=thomas and slug=john? -
django-filer - AttributeError: 'Manager' object has no attribute '_inherited'
I'm trying to install django-filer. But when I run manage.py migrate I get AttributeError: 'Manager' object has no attribute '_inherited'. I don't know what that means. (I started this project with Heroku starter template https://github.com/heroku/heroku-django-template) I initially thought that perhaps I forgot to install JPEG and ZLIB, but to my understanding they are default since Pillow 3.0. $ pip freeze dj-database-url==0.4.1 Django==1.10.4 django-filer==1.2.5 django-mptt==0.8.7 django-polymorphic==1.0.2 easy-thumbnails==2.3 gunicorn==19.6.0 psycopg2==2.6.2 whitenoise==3.2 Pillow==4.0.0 settings.py INSTALLED_APPS = [ ... 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'easy_thumbnails', 'filer', 'mptt', ... ] -
PermissionError when running Django functional tests using FireFox ESR in a virtualenv on Ubuntu
I've been slowly working my way through the excellent "Obey the Testing Goat" book on Test Driven Development, and as I hit the end of chapter 7, I noticed the author has put out an updated version. In the updated version, the author recommends using a virtualenv from the very beginning, so I decided to update my current code to work in a virtualenv, and to switch from a Windows to Linux environment at the same time. My issue is when running my (previously working) functional tests, I end up with "PermissionError: [Errno 13] Permission Denied" on line 3 below def setUp(self): binary = FirefoxBinary(r'/home/spa/firefox') self.browser = webdriver.Firefox(firefox_binary=binary) I have full access to the files in question, so I'm thinking it may be an issue as I'm calling the function from a virtualenv, and I have no clue how that effects permissions. Any help would be appreciated. -
how create a login and registration page for a website using django framework?
I am new to Django. i am unable to store the user input values into the postgres DB. I have created a tables using Models.py file and create a user interface using template file .How can i pass the vaues to the database using view.py file . someone help me plsz -
How do I Optimize Nginx + Gunicorn + Django nonrel stack?
How do I optimize my Nginx + Gunicorn + Django nonrel to accept more connections and perform better? I have configured Nginx to accept 1500 connections per worker and fine tuned fds, cache, gzip, workerlimit etc. Made the following changes to Nginx conf: NOT sure about multi_accept? Nginx worker processes is auto which is okay, I guess. Nginx keepalive timeout is 65 which is high. open_file_cache max=200000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; tcp_nopush=on Send all the response in a simple packet. keepalive_timeout 65; types_hash_max_size 2048; send_timeout 10; sendfile on; sendfile_max_chunk 512k; worker_rlimit_nofile 10000; Gzip settings as follows: gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; Could it be that my Nginx is accepting connections and Gunicorn not being optimized is not being able to process those requests. Also, should I make system level changed like: sysctl net.core.somaxconn=1024 ? For now it is 128. I want to know how and what parameters I can change in Gunicorn so that I am well utilizing my resources. My servers are 4 core 8 GB RAM -
How to set fields attribute of CreateAPIView Meta class for model having foreign key?
I have a Model like this and I want to add User attributes in my serializer file fields variable models.py class CustomUser(models.Model): user_object = models.OneToOneField(User) reg_id = models.CharField(max_length=250, blank=False) serializer.py class UserCreateModelSerializer(ModelSerializer): class Meta: model = CustomUser fields = ('reg_id') views.py class UserCreateAPI(CreateAPIView): queryset = CustomUser.objects.all() serializer_class = UserCreateModelSerializer In serializer file how can I set foreign key attributes in fields like want to set username, email, password ? -
Including only selected urls in django
I have a third party app with the following url configuration: urlpatterns = [ url(r'^webhook/(?P<token>[-_:a-zA-Z0-9]+)', TelegramView.as_view(), name='webhook'), url(r'^bots', BotViewSet, name='api'), ] Now I want to include only the second url (with namespace 'api') because I have overridden the first one in my own app (It will be handled by my own views). How do I use include so that it only includes the second url? -
Pythonanywhere - Error code: Unhandled Exception
Using Python 2.7 and Django 1.10.4, I was trying to deploy my app to pythonanywhere, but I keep getting this error enter image description here Error Log enter image description here wsgi.py import os import sys path = '/home/hellcracker/First-Blog' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler application = StaticFilesHandler(get_wsgi_application()) I can't tell where the error is coming from. Any help would be appreciated! -
Updating the a user profile upon user save
I'm following the 'User profile' approach to extend my User model, like so: # models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE, primary_key=True) my_field = models.CharField(max_length=100) # signals.py @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) With this approach, I have to explicitly call user.profile.save(), which to me feels clunky, as I want the profile to give the illusion it is part of the User object: # views.py def some_func(request): user = User.objects.create_user('dummy', 'dummy@dummy.com', '12345678') user.profile.my_field = 'hello' user.save() # This does not persist the profile object... user.profile.save() # ...this does To remedy this, I've changed create_user_profile() to the following, which works: # signals.py @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): profile = UserProfile.objects.get_or_create(user=instance) profile.save() Numerous examples I've encountered do not use this approach. Are there any caveats to using this approach? -
when I use the django function object.filter ,the python's handle increased,how can i resolve this?
I use the WIN7 32 System,django 1.8.13,python 2.7 .When I use the function like xxx.object.all() or xxx.object.filter('xx'),the python's handle number will increase.It seems that it used Class QuerySet,then the handle number will increase.Even if,I just use the admin-site to manage the DB.The handle leak also will happen. How can I release it or resolve it? -
uwsgi running on port 8000 on emperor mode
For reasons I'm going through setup testing on port 8000 for django 1.7.1 and uwsgi which is good but passing --http :8000 doesn't seem to work on the example emperor code in their documentation. If I run: uwsgi --http :8000 --ini kb/kb_uwsgi.ini I'm able to see the django successful setup page (on port 8000) but with uwsgi --http :8000 --emperor /etc/uwsgi/vassals --uid www-data --gid www-data it fails to load. Also if you wanted the proccess in the background what command is best, I use ctrl + C to cancel it. -
django admin does not add objects into manytomany fields
I have a model to save user post: class Tag(models.Model): name = models.CharField(max_length=255, unique=True) class Post(models.Model): user = models.ForeignKey(User) body = models.TextField() tags = models.ManyToManyField(Tag, blank=True) pub_date = models.DateTimeField(default=timezone.now) activity = GenericRelation(Activity, related_query_name="posts") Now whenever I save a new Post object, I would like to save the Post object's body into the Post object's tags field. I am doing this using the signals: @receiver(post_save, sender=Post) def create(sender, instance, **kwargs): if kwargs.get('created', True): tag_list = [Tag.objects.create(name=word) for word in instance.body.split()] print "from signals!: instance body: %s" % instance.body instance.tags.add(*tag_list) if not kwargs.get('created', False): tag_list = [Tag.objects.create(name=word) for word in instance.body.split()] print "already signals!: instance body: %s" % instance.body instance.tags.add(*tag_list) So if I save a new Post object in the admin, it does create a new Post object, also create tag objects inside tag_list. But... it does not add the tags from tags_list into the object's many to many field (i.e. post_object.tags). However, if I create a new Post object from shell, it does create a new Post object, create tag objects inside tag_list, and also adds the tags into the post.objects tag field. What am I doing wrong here? -
Django : Saving a url request parameter Into Form
I'm Using a Form to save data into it models.py: class presciptiontemplates(models.Model): templateid = models.AutoField(primary_key=True) template = tinymce_models.HTMLField() draft = models.BooleanField(default=False) savedate = models.DateTimeField(default=datetime.now()) patientid = models.ForeignKey('Patient') I'm Passing the parameter Patient Id From the url url(r'^addprescription/(?P<patid>\d+)/$', views.viewtemplate How do I save this parameter into form Views.py def viewtemplate(request, patid): userid = patid form = templateform(request.POST) if request.method == "POST": if form.is_valid(): presciptiontemplates.patientid = userid form.save() return redirect('index') else: form = templateform() return render(request, 'presapp/prescription.html', {'form': form}) This gives me an error [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot insert the value NULL into column 'patientid' Django 1.10.4 Python 3.5.2 Windows 7 -
JSONField custom error message
I'm currently reviewing an application i'm working on which use JSONField for json entries in the model like so. json_config = JSONField(blank=True) I noticed that if I'm editing the model in django admin and if the json is invalid, the field returns the following message Enter valid JSON which is good but not entirely helpful as i sometimes don't know exactly where the error is in the JSON. For example, if i use simplejson.loads() for strings which look like json objects, it returns a message indicating approximately where the line and character is where the error occurs. Invalid control character u'\r' at: line 5 column 16 (char 78) I couldn't find something similar to it for JSONField. Is there i way to do that? Thanks