Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
App working perfectly in Local machine but not on Pythonanywhere.com
My App working perfectly in the Local machine but not on Pythonanywhere.com, I Can't find the reasn behind this problem. Even unable to migrate the the changes to database. When execute the command python manage.py runserver this error comes Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/ananth1010/Social-media-App-Using-Django/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in exe cute_from_command_line utility.execute() File "/home/ananth1010/Social-media-App-Using-Django/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in exe cute django.setup() File "/home/ananth1010/Social-media-App-Using-Django/myvenv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ananth1010/Social-media-App-Using-Django/myvenv/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/ananth1010/Social-media-App-Using-Django/myvenv/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/home/ananth1010/Social-media-App-Using-Django/myvenv/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodi scover autodiscover_modules('admin', register_to=site) File "/home/ananth1010/Social-media-App-Using-Django/myvenv/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodisc over_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/ananth1010/Social-media-App-Using-Django/myvenv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/ananth1010/Social-media-App-Using-Django/posts/admin.py", line 2, in <module> from models import Post,Comment,User_Detailed_Info ImportError: No module named 'models' (myvenv) 07:18 ~/Social-media-App-Using-Django (master)$ python manage.py makemigrations posts Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/ananth1010/Social-media-App-Using-Django/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in … -
Not able to identify Android request
I have developed REST APIs using Django and I am not able to use session with an Android request. Each time it generates a new request from the same device that might be because of new Object of HttpURLConnection initialized in Async Task which django fails to recognise but that is not the case with Browser it works efficiently in that case. What should be done? Should we add session id generated by Django to each header in request manually in Async Task or there is another way around? -
Immediately access django-celery-results TaskResult after starting
I have several Celery tasks I'm executing within a Django view (more specifically within Django Rest Framework's perform_create method). What I'm trying to achieve is to immediately (that is, as soon as the task has an id/is in the results backend) access the TaskResult object and do something with it, like this: tasks = [do_something.s(a) for a in (1, 2, 3, 4,)] results = group(*tasks).apply_async() for result in results.children: task = TaskResult.objects.get(task_id=result.task_id) do_something_with_task_object(task) Now, this fails with django_celery_results.models.DoesNotExist: TaskResult matching query does not exist. I did not yet try it, but I could make this work with something like the following snippet. But that strikes me as plain wrong and ugly, also does it wait until the tasks are finished: while not all([TaskResult.objects.filter(task_id=t.task_id).exists() for t in results.children]): pass Is there some way to make this work in a nice and clean fashion? -
Multiple User Types In Django
I am new to Django and trying to create an App with two User Types (Freelancers and Customers). I understand how to create a User profile Class and it works well for me: class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') country = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) This works well for me on a one user type user. But now I am building an app with 2 types of users (freelancers and customers), what is the best approach to get this done. Both users will have different view and info. Should I: Create 2 different apps, and repeat the normal registeration and login for each. If I do the above, hope the freelancers when logged in won't access customers view. How do I add user type to the user profile if I decide to use one app and model for it. Please I need a step by step beginner approach, or a link to relevant source. Thanks. -
How to convert ajax json post request from Jquery to Python/Django dictionary
I am trying to convert an AJAX request retrieving JSON from JS to Python's dictionary in Django, but unsuccessfully. Please help. This is the original JS code: myJSON = JSON.stringify(myJsObject); // POST - send JSON data to Python/Django server $.ajax({ url: "/savemyexposuresituation", type: "POST", datatype: 'json', data: myJSON, async: false, success: function() { alert('Your data is saved :)'); }, error: function() { alert('Error occured :('); } }); } This is the Django side: def saveExposureSituation(request): #get es data - JSON file fromJs = request.POST fromJs = json.loads(fromJs) All I get is JSON object must be string, not QueryDict. I tried to convert this QueryDict to something else unsuccessfully. -
Use django rest api for filtering usernames starting with
This is probably a noob doubt. I am using the django rest framework and a react native front end. I am performing a search for usernames. So I want to return usernames similar to the ones typed in such as if the user starts typing, Ji then it should return: Jim Jimmy ... I am using the following to try and retreive the usernames but only when the full username is entered the data is returned. class SearchForUsers(generics.ListAPIView): serializer_class = UserAndProfileSerializer def get_queryset(self): uname = self.kwargs['username'] queryset = User.objects.all() queryset = queryset.filter(username=uname) return queryset What alternative to queryset.filter should be used to get usernames and details on the fly? -
django-tenant-schemas apps listed in TENANT_APP not migrating
I am using django-tenant-schemas for schema based multi tenancy support in Django v1.10 project. This is my SHARED_APPS: ('tenant_schemas', 'myapp.customer', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles') This is my TENANT_APPS: ('django.contrib.contenttypes', 'mptt', 'myapp.core') And finally INSTALLED_APPS: [ 'tenant_schemas', 'myapp.customer.apps.CustomerConfig', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.core.apps.CoreConfig' ] Now as per guidelines here, I created one public tenant which works fine. Next, I tried to add a new tenant TenantX with schema but migrations only run for SHARED_APPS and not TENANT_APPS. It would be really helpful if someone can point out issue with this setup. -
new virtualenv is not "empty"
This unexpected behaviour has been haunting me for many hours, now I have understood what is happening - but not why :) I have been starting a second django project, and in the newly installed virtualenv, after doing pip install -r with the copied old requirements.txt there are migrations! (in django.contrib.auth for example) First I thought it is an issue about the filesystem not really deleting the old files, but the same happens in a new project folder with a different name for the environment. Is it because of the Using cached appdirs-1.4.0-py2.py3-none-any.whl etc. ? Isn't a virtualenv meant to be an independent python installation? :) Do you understand this? -
Transform multiple values from url to json
I have this URL http://example.com?variable=1&variable=2&a=text I want to transform those values to JSON. I have tried: data = json.dumps(request.GET) But i will obtain {"variable": "2", "a": "text"} How can I get all the values from the URL transformed to JSON? -
how to host a django 1.9 application in WHM cpanel
I need to host a django application in WHM via cpanel. I've created a cpanel account in WHM for my site. I tried the following links. http://support.hostgator.in/articles/django-with-fastcgi Created an index.fcgi file and set the location for python and the application but now i'm getting an 500 Internal server error. We i checked it seems index.fcgi is deprevated in django 1.9. I've the root ssh access, but not sure were and how to configure the apache in capnel . can anyone suggest a way to host a dajngo application in cpanel. -
How to go about sorting 'trending' posts in the model?
I have a Post model for user posts, and also a PostScore model to track the score of that Post in order to sort the queryset by trending, similar to reddit's 'hot': class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=True) post = models.ForeignKey(Post, related_name='score') upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) hot = models.IntegerField(default=0) How would I go about the hot field? I'm not really asking about the algorithm for sorting them, but rather how to use my model in order to utilize the sorting algorithm. -
django email settings for app running on gcompute engine?
what do I set as the django email server in setting while running the app on the gcompute engine? I am moving the app from aws to gcloud. This is what I have: EMAIL_HOST = 'localhost' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 465 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'# #EMAIL_BACKEND = 'django_ses.SESBackend' I get: error at /accounts/password/reset/ [Errno 111] Connection refused with above. -
Django: request_POST not working properly on simple view
In my Javascript code I make an AJAX request to my Django backend like so: $.ajaxSetup({ dataType: 'json', contentType: 'application/x-www-form-urlencoded', beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); $.ajax({ url: url, type: 'POST', data: { 'notes': ... }, ... }); The view it hits is very simple -- not class-based: @require_POST def save_notes(request): ... In case it matters, here is the relevant entry from urls.py: url(r'^/save-notes/$', mymodel.views.save_notes, name="save_notes"), I would have thought this was quite a simple case, but it is consistently returning a 405, Method Not Allowed. Method Not Allowed (POST): /save-notes/ [06/Mar/2017 01:05:04] "POST /save-notes/ HTTP/1.1" 405 0 Note that the Django server logs the request as a POST. I tried breaking into the debugger in django/views/decorators/http.py just before it throws the HttpResponseNotAllowed error. The next code that would be executed to throw the error is: if request.method not in request_method_list: logger.warning( 'Method Not Allowed (%s): %s', request.method, request.path, extra={'status_code': 405, 'request': request} ) return HttpResponseNotAllowed(request_method_list) And strangely, this is what the debugger shows! > .../django/views/decorators/http.py(35)inner() -> if request.method not in request_method_list: (Pdb) request.method 'POST' (Pdb) request_method_list ['GET'] So, as you can see, here is shows that I am calling this page … -
Chart library for django
Hi everyone, I am looking for some solution to display django database queryset to django admin over graphs. I had used highcharts to do that earlier, but to use highcharts, I have to write too much scripts and functions. Is there any kind of inbuilt library that comes with django similar to highcharts by which I can display django database queryset in my django admin template ? Like in the picture above. -
I created a customer data website using web framework after that what can i do. what is the process of placing my website in google?
I'm new to networking i have a question on network. Question is : If I created a customer data website using web framework like(django, Asp.net). what is the process of placing my website in google? After that customer data will be store in my database or google data? If it stored in google database how can i get that data -
Why do you need to use Django REST API?
Why do you need to use Django REST framework to make an API? Can't you just create routes like /api/createuser with normal Django and handle all of the backend logic from there as you would normally? -
Python - Djnago Oscar UI Implementation?
I am New to PYTHON, DJANGO and DJANGO - OSCAR I am Building a B2B , B2C E-commerce website using Python and Django framework. I came to know about Django-Oscar Framework, I have been trying to use and implement it. I have successfully installed Oscar in my project, But it has its own GUI, I want to implement/Integrate my own GUI for the website. I am not able to find or do so, how can in implement my own GUI in it. Is there any tutorial or something which can point me in right direction to implement my own GUI using OSCAR E-Commerce framework. I have tried many by myself and with help of other examples, but no success so far Thanks in Advance -
Django annotate on created_at
I want to get count of records created each day in Django, but I can't make it work. So far I've got this: data = Reservation.objects\ .order_by('created_at')\ .extra({'dp': "date(created_at)"}) \ .values('dp').annotate(count=Count('id')) Which returns <QuerySet [{'count': 1, 'dp': datetime.date(2017, 2, 28)}, {'count': 1, 'dp': datetime.date(2017, 2, 28)}, {'count': 1, 'dp': datetime.date(2017, 2, 28)}, {'count': 1, 'dp': datetime.date(2017, 2, 28)}, {'count': 1, 'dp': datetime.date(2017, 3, 1)}, {'count': 1, 'dp': datetime.date(2017, 3, 1)}, {'count': 1, 'dp': datetime.date(2017, 3, 1)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, {'count': 1, 'dp': datetime.date(2017, 3, 2)}, '...(remaining elements truncated)...']> How can I count dp records together so that I'd get: <QuerySet [{'count': 4, 'dp': datetime.date(2017, 2, 28)}{'count': 3, 'dp': datetime.date(2017, 3, 1)},.. -
Validation of the reference field in mongoengine serializer
I'm using django with mongoengine and mongoengine-rest-framework. As shown in this article, specifying related_model_validations field in Meta class of a Serializer class Comment(Document): post = ReferenceField(Post) owner = ReferenceField(User) text = StringField(max_length=140) isApproved = BooleanField(default=False) from rest_framework_mongoengine import mongoengine_serializer class CommentSerializer(MongoEngineModelSerializer): class Meta: model = Comment depth = 1 related_model_validations = {'owner': User, 'post': Post} exclude = ('isApproved',) can help to achieve the following result if the document referenced by the ReferenceField is missing: { "owner":["User with PK ... does not exist."] } So instead of raising a validation exception, json is modified. However, this article is written for the old version of mongoengine-rest-framework and in the current version there is no field related_model_validations in Serializer Meta class. So how to achieve the similar result in the current version of the mongoengine-rest-framework? -
"django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." For startup code
So I'm trying to add some code to my Django 1.10 app that will only run when the server starts. I took the instructions on how to do this from here and here. Every time I try running the python console I get this: C:\Users\username\Envs\projectName [master ≡ +0 ~2 -0 !]> python manage.py shell Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\username\AppData\Local\Programs\Python\Python3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in_call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in_call_with_frames_removed File "C:\Users\username\Envs\projectName\appName\apps.py", line 2, in <module> import appName.osm as osm File "C:\Users\username\Envs\projectName\appName\osm.py", line 4, in <module> from … -
Django form field dynamic queryset field
class EventForm(forms.Form): date = forms.DateField(initial=datetime.date.today) product = forms.ModelMultipleChoiceField(queryset=Product.objects.all()) isrecurring = forms.BooleanField(required=False) week = forms.IntegerField(required=False, initial=1) days = forms.ChoiceField(choices = week_days,required=False) I have a form that has a products field which is a query set of all products. I want the field to filter products by company. How can i set the form field to have dynamically queryset in the view such that the products are filtered based on the company id? product = forms.ModelMultipleChoiceField(queryset=Product.objects.filter(company=xyz)) -
Display the objects of all users in django without login
I couldn't display the songs of all users in homepage. I want to display them like youtube or other audio streaming sites in homepage without any login. I tried objects.all() nothing happens. Please tell me what to write on views.py and what html template in homepage.html. This is my models.py: class Album(models.Model): user = models.ForeignKey(User, default=1) artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.FileField() is_favorite = models.BooleanField(default=False) def __str__(self): return self.album_title + ' - ' + self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) song_title = models.CharField(max_length=250) audio_file = models.FileField(default='') is_favorite = models.BooleanField(default=False) def __str__(self): return self.song_title This is my views.py(not all shown): def create_album(request): if not request.user.is_authenticated(): return render(request, 'music/login.html') else: form = AlbumForm(request.POST or None, request.FILES or None) if form.is_valid(): album = form.save(commit=False) album.user = request.user album.album_logo = request.FILES['album_logo'] file_type = album.album_logo.url.split('.')[-1] file_type = file_type.lower() if file_type not in IMAGE_FILE_TYPES: context = { 'album': album, 'form': form, 'error_message': 'Image file must be PNG, JPG, or JPEG', } return render(request, 'music/create_album.html', context) album.save() return render(request, 'music/detail.html', {'album': album}) context = { "form": form, } return render(request, 'music/create_album.html', context) def create_song(request, album_id): form = SongForm(request.POST or None, request.FILES or None) album = get_object_or_404(Album, pk=album_id) if form.is_valid(): albums_songs … -
Conditional filtering on Count - Django
I want to count a number of all incorrect choices in question. I have a query for a number of all choices: questions.annotate(choices_count=Count('choices')) Now, when I want to filter incorrect choices only into the Count function, it returns: Cannot resolve keyword 'choice' into field. questions.annotate(choices_count=Count(Case(When(choice__correct=False,then=1)))) Do you know how to do that? -
DropzoneJS and CreateView
I want my users to upload pictures. Dropzone looks like an easy, light tool for the job. Even with the tutorials, I keep running into an error with the Url portion of the form. Specifically, uploading a picture brings an error in the form itself (using Debug = True) and an error on the console. Nothing ever saves. As far as I can tell, the error is in the "POST" handling of the form. Any help would be appreciated (I leaned heavily on this link) views.py class AddPic(LoginRequiredMixin, CreateView): template_name = 'addpic.html' model = Photo fields = ['photo'] login_url = 'accounts/login/' raise_exception = True def get_context_data(self, **kwargs): context = super(AddPic, self).get_context_data(**kwargs) q = self.kwargs.get('match') context['match'] = Schedule.objects.get(match=q) return context def form_valid(self, form): self.object = form.save(commit=False) # Not hit database self.object.uploaded_by = self.request.user # Update user self.object.upload_date = datetime.now() # Update post_date self.object.save() # And finally save your object to database. return HttpResponseRedirect(self.get_success_url()) def get_initial(self): initial = super(AddPic, self).get_initial() q = self.kwargs.get('match') initial ['game'] = Schedule.objects.get(match=q) return initial def get_success_url(self): q = self.request.GET.get('match') url = reverse('GameView', args={q : 'game'}) return url addpic.html {% extends 'base.html' %} {% block content %} <body> <div class="w3-card w3-half"> <header class="w3-blue"> <h1>Upload a picture</h1> </header> <h4><b>{{match.home}}</b> … -
check if device already exists or not in a group
How to use list expression to check if device already exists or not in a group while posting? The user might post the same device in a same group. I have done the posting part but dont know the efficient way to check the existence of device in a group. Here is my post function def post(self, request, token=None, format=None): group_instance = Group.objects.get(token=token) for device_token in request.data['devices']: # device = Device.objects.get(token=device_token, owner=request.user) device = Device.objects.select_related('group').get(token=device_token, owner=request.user) # will not hit the db as value is already fetched in the previous query device.group = group_instance # check if device exist in a group or not print('device', device) device.save() return Response(device, status.HTTP_200_OK)