Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to hide the next parameter appearing to the url in Django?
When I am starting my Django project from the login page the url is showing like this: http://127.0.0.1:8000/login/?next=/ But what i want only this: http://127.0.0.1:8000/login What is the way to hide this next parameter appearing to the url? I have set login url and login redirect urls to the settings.py: settings.py LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/' urls.py urlpatterns = [ url(r'^$',views.index,name='home'), url(r'login/$',views.userLogin,name='login'), ] -
apache2.2 django use python3/5
I want to run django with apache2.2 and python 3.6, after making changes in wsgy.py and virtuahost still running python 2.6 Apache/2.2.34 (Unix) DAV/2 mod_wsgi/3.2 Python/2.6.9 configured -- resuming normal operations Here wsgi.py import os, sys sys.path.append('/home/app/myapp/sivale') sys.path.append('/home/app/myvenv/lib/python3.6/site-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() And here ServerName nuevo.sivale.mx Alias /static /home/app/myapp/static <Directory /home/app/myapp/static> Allow from all </Directory> <Directory /home/app/myapp/myapp> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> WSGIDaemonProcess sivale python-path=/home/app/myapp:/home/app/myvenv/lib/python3.6/site-packages WSGIProcessGroup sivale WSGIScriptAlias / /home/app/myapp/myapp/wsgi.py WSGISocketPrefix /var/run/wsgi -
How to include model to another in django
I have this database in mongodb picture:"http://placehold.it/150x150" name:"Gushkool" email:"leilaware@gushkool.com" city:"Rabat" location:Object type:"Point" coordinates:Array 0:-6.81134 1:33.95564 I want create models like this database and this is my shot: class location(Document): type = fields.StringField() coordinates = fields.StringField() class products(Document): picture = fields.StringField() name = fields.StringField() email = fields.StringField() city = fields.StringField() location = ReferenceField(location) -
GeoDjango GDALException - OGR failure
After installing GeoDjango, I wanted to create a 'Location' object in the admin panel which uses an address and a point on a map. After submitting the form, I get an error like so... GDALException at /admin/maps/location/add/ OGR failure. I have tried looking at similar questions, like here, but none of the solutions have worked. Additionally, searching for 'unable to load PROJ.4 library' (first traceback line) didn't come with any success. Any help would be appreciated! - Let me know if I should update this question with my settings.py or other relevant files. Full traceback: GDAL_ERROR 6: Unable to load PROJ.4 library (libproj.dylib), creation of OGRCoordinateTransformation failed. Internal Server Error: /admin/maps/location/add/ Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py", line 551, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/contrib/admin/sites.py", line 224, in inner return view(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py", line 1508, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/Library/Python/2.7/site-packages/django/utils/decorators.py", … -
Python Spyne XML GET (not POST)
I am creating a simple Web Service using Spyne, the client (which I don't control) send a GET to verify that SSL is up and working. The Spyne service I created responds with an error, saying only POSTS are supported. Any ideas on how I can make it respond to a simple get on the same path? Example of the code (using Django, but that shouldn't make a difference): views.py: class QWCService(ServiceBase): @rpc(Unicode, Unicode, _returns=Array(Unicode)) def authenticate(ctx, strUserName, strPassword): print "authenticate" return ["auth","success"] app = Application([QWCService], 'my.namespace.com', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) app_service = csrf_exempt(DjangoApplication(app)) urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url('^qwc', app.views.app_service, name="root"), ] The only way I can figure out how to get around this is to flip the URL to a blank page, then flip it back after the check for SSL is done. Error from Spyne: Soap11env:Client.RequestNotAllowed You must issue a POST request with the Content-Type header properly set. -
Django on cPanel using 'Setup Python App' does not working
I have configured cPanel as below: And created a django project in below path: /home/my_username/virtualenv/mysite/2.7/bin/ This is my passenger_wsgi.py config: import os import sys cwd = os.getcwd() sys.path.append(cwd) sys.path.append(cwd + '/mysite') INTERP = os.path.expanduser("~/.virtualenv/mysite/3.6/bin/python3.6") if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) sys.path.insert(0, os.path.dirname(__file__)) sys.path.insert(0,'$HOME/.virtualenvs/mysite/3.6/bin') sys.path.insert(0,'$HOME/.virtualenvs/mysite/3.6/lib/python3.6/site-packages/django') sys.path.insert(0,'$HOME/.virtualenvs/mysite/3.6/lib/python3.6/site-packages') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() but I getting this error: We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later. I would appreciate any help! Thanks. -
How to use Django-postman and ajax-selects?
I am trying to use django-postman for user-user messaging and ajax-selects for auto completion but i am not able to do it despite going through it's documentation. I am using django inbuilt User model for signups. I want to use this model for autocompletion in recipients field of django-postman But still there is no autocomplete in my create message's recipient field. Please forgive indentation error if any, this is my settings.py AJAX_LOOKUP_CHANNELS = { 'user' : {'model':'auth.User', 'search_field':'username'}, } POSTMAN_AUTO_MODERATE_AS=True POSTMAN_DISALLOW_ANONYMOUS=True POSTMAN_DISALLOW_COPIES_ON_REPLY=True POSTMAN_AUTOCOMPLETER_APP = { 'name': 'ajax_select', # default is 'ajax_select' 'field': 'AutoCompleteField', # default is 'AutoCompleteField' 'arg_name': 'channel', # default is 'channel' 'arg_default': 'user', # no default, mandatory to enable the feature} thi is my forms.py from django-postman class WriteForm(BaseWriteForm): """The form for an authenticated user, to compose a message.""" # specify help_text only to avoid the possible default 'Enter text to #search.' of ajax_select v1.2.5 recipients = CommaSeparatedUserField(label=(_("Recipients"), _("Recipient")), help_text='') class Meta(BaseWriteForm.Meta): fields = ('recipients', 'subject', 'body') #recipients = AutoCompleteSelectField('recipients') this is my lookup.py file under django-postman app from ajax_select import register, LookupChannel from django.contrib.auth.models import User class TagsLookup(LookupChannel): model = User def get_query(self, q, request): return self.model.objects.filter(username__icontains=q).order_by('username'[:50] from my project's urls.py from ajax_select import urls as ajax_select_urls … -
Django : How can I fix this when adding facebook login to django app using social-auth?
I am using django to create a web app and add facebook login in the homepage. But whenever I run click on the facebook login link, I get the following error. Can anyone tell me where the error is and how I can fix it ? -
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