Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - queries won't return the targeted column
What I want to accomplish: Admin is logging in to see all of the members in his group. What I get in return is all the members from others group which i do not want. I only want Admin to see members who are in his group. I am not getting the filters i want. Searching for solutions here with no luck and still a newbie so appreciate your help! admin\models.py class Administrator(AbstractUser): ... asoc_name = models.CharField(max_length=100) class Meta: db_table = 'Administrator' member\models.py from pl.admin.models import Administrator class Member(models.Model): member_no = models.AutoField(primary_key=True) asoc_name = models.CharField(max_length=50) ... class Meta: db_table = 'Member' class Association(models.Model): asocnumber = models.AutoField(primary_key=True) asoc_name = models.CharField(max_length=50, null=True, blank=True) class Meta: db_table = 'Association' class member_asoc(models.Model): asocnumber = models.OneToOneField(Association) member_no = models.OneToOneField(Member) user = models.OneToOneField(Administrator) class Meta: db_table = 'member_asoc' Views.py class member_overview(ListView): model = Member template_name = 'member/member_overview.html' def get_queryset(self, *args, **kwargs): user = self.request.user return Member.objects.filter(asoc_name=user) Let me know if you need more info. -
Paramiko not saving results from 'show running-cong' command
I am using ConfiBack to run automated switch backups from my work. Currently the Telnet portion works fine, but I am running into issues with SSH and it not saving the output from a 'show running-config' command. At the moment, when I run the backup for my switch it seems to connect to the switch, run the set of commands, and saves a backup. However, when I go to the backup the file is blank. Below is the code the program runs and screen shots of what I see. from django.db import models from django.conf import settings from django.utils.translation import ugettext as _ from django.utils.encoding import force_unicode from django.contrib.admin.models import ADDITION, LogEntry from django.contrib.contenttypes.models import ContentType import re, sys #from frontend.fields import EncField class Profile(models.Model): CONNECTION_TYPES = ( (1, 'Telnet'), (2, 'SSH2'), (3, 'FTP'), (4, 'FTP with TLS'), (5, 'Telnet+TFTP+FTP'), ) name = models.CharField(max_length=50, verbose_name=_("Name")) connection_type = models.IntegerField(max_length=10, choices=CONNECTION_TYPES, default=1, verbose_name=_("Connection type")) def __unicode__(self): return self.name def build_keywords(self, device): DEFAULT_KEYWORD_MACROS = { '{blank}': '', '{devicename}': device.name, } keywords = DEFAULT_KEYWORD_MACROS for _kw in KeywordMacro.objects.filter(device=device): keywords['{{{0}}}'.format(_kw.keyword)] = _kw.value return keywords def prepare_commands(self, device): commands = [] for _c in ProfileCommand.objects.filter(profile=device.profile): if re.search('[\{\w\}]',_c.command): _cwork = _c.command for _kw,_val in self.build_keywords(device).items(): _cwork = … -
django email account activaiton
I am sending an activation email to the user containing a uuidd (activation_token), When the user clicks on the link in the email, I get an eroror 404 page cannot be found. email code accountactivation = AccountActivation( email=email, password=password ) accountactivation.save() subject = 'Account Confirmation' contact_message = 'please click the link to activate your account' + 'http://127.0.0.1:8000/accounts/account_activation/?activation_token=%s' %(accountactivation.activation_token) from_email = settings.EMAIL_HOST_USER to_email = from_email send_mail(subject, contact_message, from_email, [to_email], fail_silently=False, ) url pattern url(r'^account_activation/(?P<activation_token>[0-9A-Za-z])/$', views.account_activation, name="account_activation"), uuid code example 51094a477a14-4e26a7c84bff8b63a94d url in the browser http://127.0.0.1:8000/accounts/account_activation/?id=51094a477a14-4e26a7c84bff8b63a94d/ -
Django + mod_wsgi + apache + wamp optimization technique for windows
I am trying to host my Django App to Wamp in Windows 7. I already configured mod_wsgi correctly and had run a test project to verify it. However, the server is really taking time to load as I migrated my dev project. I have read articles about optimizing mod_wsgi performance by enabling mod_wsgi daemon mode on non-Windows platforms. My questions is: Is there a way to optimize mod_wsgi performance in Windows platform? Side note: Its already 30 minutes since I have tried to access my django project and the page is still loading. There is no error log generated in Apache error log and the Wamp server is still running. -
Cannot access Django server on EC2 instance
I created an EC2 instance. Installed Python 3.4 on it and then installed Django 1.10.6 on it. I was trying to develop my first django application I started django server. python manage.py runserver I could not access at http://n.n.n.n:8000. I get a ERR_CONNECTION_REFUSED error. I went back to the EC2 instance and added the protocol/port to the security group. This is how it looks after I add the port/proptocol Custom TCP Rule TCP 8000 0.0.0.0/0 Custom TCP Rule TCP 8000 ::/0 It did not work. I even added a rule to allow all traffic from anywhere. It still did not work. However, if I start django server the following way python manage.py runserver 0.0.0.0:8000 I get the following error: DisallowedHost at / Invalid HTTP_HOST header: 'n.n.n.n:8000'. You may need to add 'n.n.n.n' to ALLOWED_HOSTS. I can ping the IP. I can ssh (there is rule to allow ssh). Why am I not able access http/django server? Thanks -
Django - Permissions and DeleteView, is this a good way to do it?
Hi so I have a working view. I wanted to know if this is the best or a good way of doing it. I want to have a delete view that deletes a Photo object but only if the logged in user is the on associated with the object. Here is my views.py class PhotoDelete(DeleteView): model = Photo template_name = 'otologue/photo_delete.html' success_url = reverse_lazy('otologue:photos') def get(self, request, *args, **kwargs): object_instance = self.get_object() # Get the object object_user = object_instance.photoextended.user # Get the user who owns the object user = get_object_or_404(User, username=self.request.user) # Get the user in the view if object_user != user: # See if the object_user is the same as the user return HttpResponseForbidden('Permission Error') else: return render(request, self.template_name, {'object': object_instance}) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) If you need more info like the models and such, please request it. -
Install Celery & Redis with Heroku
I use Django 1.9, Python 2.7 and Heroku. Celery 3 & Redis were working well, until I switched to Celery 4.0.2 and changed the configuration. heroku logs shows the following message: 2017-03-05T16:34:22.076383+00:00 app[worker.1]: Unknown command: 'celery' Here are my configurations: __init.py__ from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] settings.py INSTALLED_APPS = ( ... 'django_celery_beat', ) if ENVIRONMENT == 'PROD': from settings_remote import * else: from settings_local import * settings_remote.py from __future__ import unicode_literals, absolute_import import os CELERY_BROKER_URL = os.environ['REDIS_URL'] CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'terradiem.settings') from django.conf import settings app = Celery('terradiem') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Procfile web: gunicorn terradiem.wsgi --log-file - worker: python manage.py celery worker --beat .env REDIS_URL=redis:// Any clue? -
Django REST Framework and combining models
I'm trying to build an API for our database. The information in the database is divided between multiple tables, all of which have the same 'Ice-code' as their primary key. I've been trying now for a better part of a week to combine the tables so I can from one url (api.something.com/ice/) be able to see a list of ice and from (api.something.com/ice/1) be able to see a detailed view of the ice combining information from all tables. Seems that no matter what I try I fail to combine the tables. Here is a rough draft of what I have so far. I would like to be able to update the fields from the front end eventually. Total number of rows per table is somewhere around 70-80k and they have more columns than the ones here but I'm just trying to make a rough working draft. # models.py class IceInfo(models.Model): ice_code = models.IntegerField(db_column='Ice-code', primary_key=True, max_length=10) ice_name = models.TextField(db_column='Ice name', blank=True, null=True) updated = models.DateTimeField(db_column='Updated') class Meta: managed = False db_table = 'Ice_Info' class IceList(models.Model): ice_code = models.IntegerField(primary_key=True, db_column='Ice-code', max_length=10) ice_maker = models.CharField(db_column='Ice Maker', max_length=255, blank=True, null=True) updated = models.DateTimeField(db_column='Updated') class Meta: managed = False db_table = 'Ice_List' def __str__(self): return … -
Weighted random choice with categories
So basically I have a database table with photos. Each photo has a rating <0,1> and categories (one or more). I need a way to efficiently chose x elements from this table at weighted random but with respect to categories, I have to do this in python3 + Django (or microservice communicating thru Redis or exposing RESTapi). eg: table: .---------.--------.------------. | photo | rating | categories | :---------+--------+------------: | Value 1 | 0.8 | art, cats | :---------+--------+------------: | value 2 | 0.5 | cats | :---------+--------+------------: | value 3 | 0.9 | night | '---------'--------'------------' And when I ask for 1 photo with categories (cats, dogs). The algorithm should return something like numpy.random.choice([Value 1, Value 2], 1, [0.8, 0.5]) Currently, every time I am asked for it I do something as follow: photos = Photos.objects.filter(category__in=[list of wanted categories]) photos, weights = zip(*list(photos.values_list('photo', 'rating'))) res = numpy.random.choice(photos, amount_wanted, weights, , replace=False) Is there more efficent approach to this? I can use any AWS service to achive it. -
Django REST framework doesn't save data
I am trying to save data with Django REST framework, but the command serializer.save() doesn't save the data contained in the serializer. I have the following code : if serializer.save(raise_exception=True): serializer.save() And I'm getting the following line in my API's terminal : "POST /questions/ HTTP/1.1" 500 14321 Does anyone have an idea ? -
What is the best way to secure calls to internal APIs?
I am quite new to the django-rest-framework and building APIs, and I am thinking of way to secure my APIs. My question is: What is the best way to allow only your front-end application to call specific API endpoints? I was thinking of creating superuser(front-end application)account and store login details somewhere so the front-end app could authenticate itself with the first request. Then I thought that as soon as user authenticates itself (by log-in) all the requests will be authenticated using that specific user details? But I am not sure if that is the way to go. I also thought about OAuth2, but not sure if this is the right use for that. I would be grateful if someone could direct me on the right path. -
Django Threading Structure
First of all to begin with 'Yes' i checked and googled this topic but can't find anything that gives me a clear answer to my question? I am a beginner in Djagno and studying its documentation where i read about the Thread Safety Considerations for render method of nodes for Templates Tags. Here is the link to the documentation Link. My question lies where it states that Once the node is parsed the render method for that node might be called multiple times i am confused whether it is talking about the use of the template tag in the same document at different places for the same user at the single instance level of the user on the server or the use of the template tag for multiple request coming from users all around the world sharing the same django instance in memory? If its the latter one does't django create a new instance at the server level for every new user request and have seprate for every user in the memory or am i wrong about this? -
invalid syntax (urls.py, line 21) django python3
urls.py SyntaxError at /admin/ invalid syntax (urls.py, line 21) Request Method: GET Request URL: http://127.0.0.1:8080/admin/ Django Version: 1.8.2 Exception Type: SyntaxError Exception Value: invalid syntax (urls.py, line 21) Exception Location: C:\Users\JiHW\AppData\Local\Programs\Python \Python35-32\lib\importlib\__init__.py in import_module, line 126 Python Executable: C:\Users\JiHW\AppData\Local\Programs\Python\Python35-32\python.exe Python Version: 3.5.3 Python Path: ['C:\\Users\\JiHW\\Desktop\\django\\StudentDemoVoteSystem', 'C:\\Users\\JiHW\\AppData\\Local\\Programs\\Python\\Python35-32\\python35.zip', 'C:\\Users\\JiHW\\AppData\\Local\\Programs\\Python\\Python35-32\\DLLs', 'C:\\Users\\JiHW\\AppData\\Local\\Programs\\Python\\Python35-32\\lib', 'C:\\Users\\JiHW\\AppData\\Local\\Programs\\Python\\Python35-32', 'C:\\Users\\JiHW\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages'] from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls',namespace="polls")), url(r'^admin/', include(admin.site.urls)), ] I know it's just SyntaxError, but I really don't know what's wrong This is an official document entry tutorial I need help I do not know what to add, this site is always to add some details to me, who can tell me where the wrong -
Django - display method result without url
I am newbie in django and try to build a simple shop system. in my store all customers must be charge their account that they can buy a product (credit system). now i want to display user credit in top of site header in all of the site. i also want to write some functions and display its result in template without special url. how can do this? -
django json response datetime field
Here is a piece of my code : response = {} response['status'] = 1 response['message'] = "Success" response['data'] = {'id': message.id, 'date': message.data} I want to respond the response through api endpoint when I do return JsonResponse(response, safe=False) it gives me error like date time object is not serializable. So I tried this response['data'] = json.dumps({'id': message.id, 'date': message.data}, cls=DjangoJSONEncoder) return JsonResponse(response, safe=False) When I do this it gives me data as string instead of javascript object when I fetch from javascript. What is the issue ? -
proper use of setup_eager_loading
I have used setup_eager_loading for optimizing the query performance in serializers. How can i use it in APIView ? If its listapiview i will override get_queryset but no idea on APIView. Here is my serializer class DeviceGroupSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) devices = DeviceIdSerializer(source="groups", many=True, read_only=True) @staticmethod def setup_eager_loading(queryset): queryset = queryset.select_related('devices') return queryset class Meta: model = DeviceGroup fields = ['id','name', 'devices'] class GroupsAPIView(APIView): def get_object(self, user, token): try: return BaseDevice.objects.filter(owner=user).get(token=token) except ObjectDoesNotExist: return error.RequestedResourceNotFound().as_response() def get(self, request, format=None): reply = {} try: groups = Group.objects.filter(owner=request.user) reply['data'] = GroupSerializer(groups, many=True).data except: reply['data'] = [] return Response(reply, status.HTTP_200_OK) -
Django get post answers
I have a Post model: class Post(models.Model): poster = models.ForeignKey('auth.User') question = models.ForeignKey('self', null=True, blank=True) post_title = models.CharField(max_length=300) post_content = models.TextField(null=True, blank=True) is_question = models.BooleanField(default=True) . . . created_date = models.DateTimeField( default=timezone.now) def __str__(self): return self.post_title This is going to be question and answer site, just like SO. If this post is a question, 'is_question' will be true. else if the post is an answer, 'question' field will refer to the id of the post which is the question and 'is_question' will be false. simple, right. Now I am trying to get all the questions and the related answers, is this possible with one or a few query (without using for loop)? The following filter will return the questions and some related things only (like number of upvotes, views, post tags): posts = Post.objects.filter( created_date__lte=timezone.now(), is_question=1, is_published=1 ).order_by( '-created_date', ).prefetch_related( Prefetch('vote_set', queryset=Vote.objects.filter( user=request.user, date_voted__gte=dt_aware), to_attr='user_voted') ).prefetch_related( Prefetch('tags', to_attr='tagss') ).annotate(total_votes=Coalesce(Sum('vote__vote_type'),0) ).annotate(views_num = Count('questionvieaw', distinct=True) ).select_related() -
Django Form, CreateView - Something wrong with this HTML for a form
so I have created a view, forms and html page which creates an new entry into one of my models. The view works fine and so does the forms, however, it only works when I place the regular django generated form such as {{ form }} and {{ other_form }}. When I use custom html, and press submit with data entered all that happens is the form is returned empty and no data is created on the database. It doesn't get into the def form_valid part. I want to use a custom form so I can add some bootstrap classes to the input fields. Here is the CreateView, views.py class PhotoCreate(CreateView): model = Photo form_class = PhotoModelForm other_form = PhotoExtendedModelForm template_name = 'otologue/photo_create_temp.html' def form_valid(self, form): other_form = self.other_form(self.request.POST) if other_form.is_valid(): form_instance = form.save() other_form.instance.user = self.request.user other_form.instance.photo = form_instance other_form.save() return super(PhotoCreate, self).form_valid(form) def get_context_data(self, **kwargs): context = super(PhotoCreate, self).get_context_data(**kwargs) context['other_form'] = getattr(self, 'other_form', self.other_form()) return context @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) Working html {% extends "base.html" %} {% block title %}Upload Photo{% endblock %} {% block content %} <h1>Upload Photo</h1> <p>Upload a photo using the following form</p> <form action="." enctype="multipart/form-data" method="post"> {% csrf_token %} {{ … -
Django: update m2m field for many objects
I have two models: class UserStatus(models.Model): name = models.CharField() type = models.CharField() class UserProfile(models.Model): user = models.ForeignKey(User, db_index=True, null=False, blank=False, unique=True) user_status = models.ManyToManyField(UserStatus, db_index=True, null=True, blank=True) def set_status(self, new_status): if not isinstance(new_status, UserStatus): new_status = UserStatus.objects.get(id=new_status) if new_status.type: self.user_status.remove(*self.user_status.filter(type=new_status.type)) self.user_status.add(new_status) One UserProfile may have unique UserStatus by type. There is method set_status to set new UserStatus. I wrote view to set UserStatus for multiple UserProfile: def ajax_change_status(request): if not request.is_ajax(): return HttpResponseForbidden() post_dict = dict(request.POST) if 'statuses_id[]' in post_dict and 'profile_ids[]' in post_dict: statuses = UserStatus.objects.filter(id__in=post_dict['statuses_id[]']) for profile in UserProfile.objects.filter(id__in=post_dict['profile_ids[]']): for status in statuses: profile.set_status(status) return HttpResponse("OK") But if I post that view about 2000 UserProfile and 2 UserStatus, it executes ~40 seconds. Is there more efficient solution to do that? -
Multiple images getting uploaded but failing validation
Here's my setup: class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo fields = ('image',) class AlbumSerializer(serializers.ModelSerializer): photos = PhotoSerializer(many=True) class Meta: model = Album fields = ('photos',) class Albums(APIView): def post(self, request): print(request.data) # checking request serializer = AlbumSerializer(data=request.data) if serializer.is_valid(): print(serializer.validated_data) # checking validation return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The image that's included in the PhotoSerializer fields is an ImageField() in the Photo model. Now, when I execute an curl -X POST -F 'photos[0].image=@/path/to/macho.jpg' \ -F 'photos[1].image=@/path/to/iron-man.jpg' I get this # print(request.data) <QueryDict: {'photos[1].image': [<InMemoryUploadedFile: iron-man.jpg (image/jpeg)>], 'photos[0].image': [<InMemoryUploadedFile: macho.jpg (image/jpeg)>]}> # response -- 400 {"photos":[{"image":["No file was submitted."]},{"image":["No file was submitted."]}]} The response says no images were submitted, contradicting the QueryDict that received them. After a lot of head scratching, I tried uploading a single photo by removing the many=True from the PhotoSerializer nested in the AlbumSerializer and curl -X POST -F 'photos.image=@/path/to/macho.jpg' I got this back # print(request.data) <QueryDict: {'photos.image': [<InMemoryUploadedFile: macho.jpg (image/jpeg)>]}> # print(serializer.validated_data) OrderedDict([('photos', OrderedDict([('image', <InMemoryUploadedFile: macho.jpg (image/jpeg)>)]))]) # response -- 201 {"photos":{"image":null}} Apparently I get an OrderedDict when it's one photo — which indicates that validation passed — but the OrderedDict is missing when it's multiple photos. But I can't understand what's happening. I … -
Custom django error templates
I wrote custom django error templates and do not need any other custom behavior than a custom path to the template (Templates are not located at root directory). I tried the following: handler400 = partial(bad_request, template_name='polls/errors/400.html') handler403 = partial(permission_denied, template_name='polls/errors/403.html') handler404 = partial(page_not_found, template_name='polls/errors/404.html') handler500 = partial(server_error, template_name='polls/errors/500.html') But it seems that I need to pass the views as a string. Do I have to write custom views which do exactly the same or how can the template name be changed? -
Django let User Update TextField value on Site via forms?
I hope someone can give me a little help on how to do the following with Django (excuse me if I don't explain everything correct, still new to Django and don't know about a lot of things) : I have a table of Movies, those Movies have a "Description" Datafield, where when they click on it a form opens up with the current description of the movie. If they double click on this description they are allowed to change it and then save the value. I've made a small gif to visualize the idea: At least thats the basic Idea behind this, so far I've managed to make most of the things run, but sadly not the Django part where the "new" data from the user is send to the Databank and replaces the old data of the Description. So could someone explain to me how I can make that work? I know that I'd probably have to write a function to my views.py and then create a new url pattern, but I just can't figure out how exactly. So any help is welcome! Below is my code (I hope I've included every file you guys need): views.py from django.shortcuts … -
Trying to Display init value in form
I am trying to display the init value (State) in my form, but it keep showing the "-------" value. I know the value is not empty because it saves the states into my database. It just wont show up in my form My form class: class AddressUpdateForm(BaseModelForm): state = ProvinceModelChoiceField(required=False, queryset=CountryProvincePair.objects.all()) class Meta: model = Address fields = ('label', 'postal', 'zip', 'city', 'country', 'state', 'custombillto') def __init__(self, *args, **kwargs): super(AddressUpdateForm, self).__init__(*args, **kwargs) print("THIS IS IT", self.instance.state) self.fields['state'].instance = self.instance.state My custom ModelChoiceField: class ProvinceModelChoiceField(ModelChoiceField): """ A model choice field that accepts custom values for province class. Should be used together with Chosen with extended functionality. This model will accept everything that is not in its Query initial values """ def label_from_instance(self, obj): return "%s, %s" % (obj.province, obj.country) def to_python(self, value): if value in self.empty_values: return None try: key = self.to_field_name or 'pk' value = self.queryset.get(**{key: value}) except (ValueError, TypeError, self.queryset.model.DoesNotExist): # If the object does not exist, does not raise an error pass return value -
Restrict foreign key values according to request.user in django
I have declared a model Category and a model Post in my Blog application: class Category(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User) desc = models.TextField(max_length=200, default='') class Post(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=200) category = models.ForeignKey(Category, default=1) text = models.TextField() What I want is to restrict the category foreign key in the Post model to the Categories where Category.author = Post.author. (Post author can select as Post Category only categories that he created). What would be your approach? Thanks in advance! -
Issue with Django form POST method
I am having a problem with the following view and form. The form loads correctly however when I edit any of the fields it does not save. After a bit of debugging I think it is due to one of two things: either request.method == "POST" is evaluating to false, or form.is_valid() is evaluating to false. So potentially something wrong with my template or my clean() method? I've searched previous questions and can't find anything that helps. I've also checked my clean() method against the Django docs and think it is OK. views.py @login_required def edit_transaction(request, pk): transaction = get_object_or_404(Transaction, pk=pk) if request.method == "POST": form = TransactionForm(request.POST, instance=transaction) if form.is_valid(): transaction = form.save(commit=False) transaction.updated = timezone.now() transaction.save() return redirect('view_transaction_detail', pk=transaction.pk) else: form = TransactionForm(request=request, instance=transaction) return render(request, 'budget/new_transaction.html', {'form': form}) forms.py class TransactionForm(forms.ModelForm): class Meta: model = Transaction fields = ('title', 'transaction_type', 'category', 'budgeted_amount', 'actual_amount', 'date', 'comments',) #new_category field to allow you to add a new category new_category = forms.CharField(max_length=30, required=False, label="New Category Title") def __init__(self, request, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) #category is now not a required field because you will use category OR new_category self.fields['category'].required=False #set to allow use of self.request.user to set user for category self.request …