Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send data from AngularJS 2 to Django Server?
I spent many time for this work but no result for me... so I want someone can help me!! I used to use http post method of Angular JS 2 like this: login(email:string, password:string) { let headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('X-CSRFToken', this.getCookie('csrftoken')); return this.http .post( '/accounts/login', JSON.stringify({ email, password }), { headers } ).map(response => console.log(response)) } It accessed to server with url : "/accounts/login" successfully, but when I print data post with command in django : print request.POST It shows for me : <QueryDict: {}>, I don't why QueryDict empty, this is my form.html : <div class="login jumbotron center-block"> <h1>Login</h1> <form role="form" (submit)="login(event,username.value, password.value)"> <div class="form-group"> <label for="username">Username</label> <input type="text" #username class="form-control" id="username" placeholder="Username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" #password class="form-control" id="password" placeholder="Password"> </div> <button type="submit" class="btn btn-default">Submit</button> <a [routerLink]="['/signup']">Click here to Signup</a> </form> </div> ... I can sure that is email and password not null !! -
How do I check if a function is called in a method of a class?
I need to check to see if a specific function "oscp.deactivate_user()" is being called in an instance of a method call delete() Here's what I have so far, the assert fails, when it shouldn't be. @mock.patch.object(AuthUser, 'delete') @mock.patch('oscp.deactivate_user') def test_delete(self, deactivate_user_mock, delete_mock): """Test the delete() method in AuthUser""" authUserObject = mock.Mock() authUserObject.oscp_id = 4 """If delete_from_oscp = True && oscp_id isset""" delete_mock_instance = delete_mock(self, True, authUserObject, oscp_id=4) delete_mock_instance.delete_mock.assert_called_once_with(self) -
Django login not working, with no obvious cause
I have a custom view, "mylogin", which I call via AJAX POST, for logging in with an email address and password. The account I'm trying to log into has a username as well as an email address, but both the username and the email address are unique across accounts. For some reason (even though I haven't done anything strange with my SESSION_COOKIE_SECURE setting in settings.py), I can verify that the user account does get authenticated but that "login(request, user)" doesn't stick. The three print statements near the bottom print what one would expect. The javascript gets a response of "Logged in" and then reloads the page, which is userless. from django.contrib.auth.views import login from django.contrib.auth.models import User from django.contrib.auth import authenticate from .forms import LoginForm def mylogin(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): eml = form.cleaned_data['email'] pwd = form.cleaned_data['password'] try: usn = User.objects.get(email=eml).username except: usn = "" user = authenticate(username=usn, password=pwd) if user is None: try: user = User.objects.get(email=eml) return render(request, 'topics/response.html', {'string':'Wrong password'}) except: return render(request, 'topics/response.html', {'string':'Email not found'}) else: if user.is_authenticated(): print("User is authenticated") print(user.username) print(user.email) login(request, user) return render(request, 'topics/response.html', {'string':'Logged in'}) -
Django Migration Process for Elasticbeanstalk / Multiple Databases
I am developing a small web application using Django and Elasticbeanstalk. I created a EB application with two environments (staging and production), created a RDS instance and assigned it to my EB environments. For development I use a local database, because deploying to AWS takes quite some time. However, I am having troubles with the migrations. Because I develop and test locally every couple of minutes, I tend to have different migrations locally and on the two environments. So once I deploy the current version of the app to a certain environment, the "manage.py migrate" fails most of the times because tables already exist or do not exist even though they should (because another environment already created the tables). So I was wondering how to handle the migration process when using multiple environments for development, staging and production with some common and some exclusive database instances that might not reflect the same structure all the time? Should I exclude the migration files from the code repository and the eb deployment and run makemigrations & migrate after every deployment? Should I not run migrations automatically using the .ebextensions and apply all the migrations manually through one of the instances? What's the … -
Reducing database operation time Django/ Mysql
So, the thing is I am having a moderately large list of emails ~ 250,000 entries. I have another table containing list of invalid emails ~ 50,000 which i need to remove (mark inactive) from 1st table. For that I have ran a simple django function which is taking 3-4 seconds in each loop. The code is: def clean_list(): id = 9 while id<40000: i = Invalid.objects.get(id=id) y = i.email.strip() f = IndiList.objects.get(email__contains=y) f.active = False f.save() id +=1 What would be a better way to do it? Either a SQL query or a better piece of django code or some other way. Help! -
django site ERR_SSL_PROTOCOL_ERROR after https setting
So I am trying to deploy my site and basically tried python manage.py check --deploy and followed what ever it told me: WARNINGS: ?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems. ?: (security.W006) Your SECURE_CONTENT_TYPE_NOSNIFF setting is not set to True, so your pages will not be served with an 'x-content-type-options: nosniff' header. You should consider enabling this header to prevent the browser from identifying content types incorrectly. ?: (security.W007) Your SECURE_BROWSER_XSS_FILTER setting is not set to True, so your pages will not be served with an 'x-xss-protection: 1; mode=block' header. You should consider enabling this header to activate the browser's XSS filtering and help prevent XSS attacks. ?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS. ?: (security.W012) SESSION_COOKIE_SECURE is not … -
django attribute error : object has no attribute 'get_bound_field'
Apparently a form being loaded on my template is requiring a field that isn't being passed to it. Can anyone tell me what is causing this error? Error occurs during template rendering In template C:\django\projectname\static\templates\link_list.html, error at line 114 'UserProfile' object has no attribute 'get_bound_field' 104 105 </p> 106 107 </form> 108 </div> 109 <div id="make-offer" style="display: none"> 110 111 <p>Make an offer</p> 112 <form class=".formLayout" name="offer-form" action="" method="post" enctype="multipart/form-data"> 113 {% csrf_token %} 114 {{ form.as_table }} 115 <input type="submit" class="data" style="font-family: VT323; font-size: 50%" value="Submit" /> 116 </form> 117 </div> 118 </div> 119 </div> 120 </div> This is served by the following view: def link(request): print("trying to authenticate...") if request.user.is_authenticated(): user_profile = UserProfile.objects.get(user=request.user) else: return render(request, 'login.html') if request.method == "POST": print("request was a post.") if request.is_ajax(): ... else: if request.method == "POST": form = OfferForm(request.POST, request.FILES, maker_id=user_profile.id) if form.is_valid(): if request.POST.get('location'): offer = form.save() offer.save() offer.maker = maker offer.save() else: print form.errors return render(request, "link_list.html", {'form' : form} ) else: form = OfferForm(maker_id=user_profile.id) print("request wasn't ajax.") data = {'form': form} return render(request, 'link_list.html', data) Here are the relevant models and forms: class OfferForm(forms.ModelForm): def __init__(self, *args, **kwargs): maker_id = kwargs.pop('maker_id') super(OfferForm, self).__init__(*args, **kwargs) maker = UserProfile.objects.get(id=maker_id) self.fields['maker'] … -
How do I render JSON objects in Django HTML template?
I'm trying to move Django backend to REST API in order to let a mobile app access the backend. I'm using Django REST framework for this. So if I serialize all my models and objects and render in JSON (for mobile app), how do I render the serialized models and objects in my django templates (for website). I realize there are many ways to render (TemplateHTMLRenderer, JSONRenderer, etc.). But once I serialize, I'm not able to render using TemplateHTMLRenderer. So should I just serialize and render if it's a json request and just render using TemplateHTMLRenderer if it's a regular request? So everything is just if-else? What strategies do people usually use to move to REST API? -
How does mod_wsgi know and execute the application?
I'm tying to setup Apache/2.2.22 (Debian) mod_wsgi/3.3 Python/2.7.3 I manage to get the WSGIScriptAlias executed, but only the top level module code, not the application defined therein. Apache configuration: LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so WSGIScriptAlias /testurl /home/django/test/test/wsgi_test.py <Directory /home/django/test/test> <Files wsgi_test.py> Order deny,allow Allow from all </Files> </Directory> wsgi_test.py: #!/usr/bin/python import sys print >> sys.stderr, "I'm wsgi_test" def application(environ, start_response): print >> sys.stderr, 'in application' status = '200 OK' output = 'hello World' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] When requesting the url using a browser the wsgi_test.py script gets executed ("I'm wsgi_test" appearing in the apache error log). However, no page is served (500 internal server error) and there is an additional error log entry Premature end of script headers: wsgi_test.py. As a second test, I used a simple script, which correctly serves 'Hello World': wsgi_test2.py: #!/usr/bin/python import sys print 'Content-type: text/plain\n\n' print 'Hello World' My question: How does mod_wsgi know and execute the application? From the above tests, I conclude that wsgi_test.py is immediately executed. Since there is no executable code but only a definition of application, the script does not output anything and thus the server complains about the missing html headers. How do I … -
How to use ordering in rest_framework_json_api
My settings: 'DEFAULT_PAGINATION_CLASS': 'mobile_api.pagination.OptionalPageNumberPagination', 'PAGE_SIZE': 40` My class: from rest_framework_json_api import pagination class OptionalPageNumberPagination(pagination.PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): if 'page' in request.query_params: return super().paginate_queryset(queryset, request, view) else: return queryset def get_paginated_response(self, data): if hasattr(self, 'page'): return super().get_paginated_response(data) else: from rest_framework.response import Response from collections import OrderedDict return Response(OrderedDict([ ('results', data) ])) How to use ordering? My model contains property Cod, and I want to sort by it. Help. :) -
django inline modelform foreign key related values
I'm just starting playing with django. I read the documentation and similar questions here but I couldn't find a solution, probably I'm missing something really obvious or approaching the issue in the wrong way I have the following model: class Interview(models.Model): nickname = models.CharField(max_length=25, null=False, blank=False) class Question(models.Model): phrase = models.CharField(max_length=200, null=False, blank=False) class Answer(models.Model): [...] interview = models.ForeignKey(Interview,on_delete=models.CASCADE, null=False) question = models.ForeignKey(Question,on_delete=models.DO_NOTHING, null=False) code = models.CharField( max_length=1, choices=CODE_CHOICES, null=True) the phrase field in the question could contain a '*' and when displaying the questions I would like it to be replaced with the interview's nickname. This is easy in the view to display results: answers = Answer.objects.filter(interview=interview_obj) for a in answers: a.question.phrase = a.question.phrase.replace('*',a.interview.nickname) return render(request, 'results.html', {'answers': answers }) Anyway I'm not able to do the same with the formset. The following obviously does not work but I didn't find a way to achieve what I want: class AnswerForm(ModelForm): code = ChoiceField(widget=RadioSelect(renderer=HorizontalRadioRenderer,attrs={'required': 'true'}), choices=Answer.CODE_CHOICES) class Meta: model = Answer fields = ['code'] in view: AnswerFormset = inlineformset_factory(Question,Answer,form=AnswerForm,fields=['code'],extra=0) answer_list = Answer.objects.filter(interview=interview_obj) for a in answers: a.question.phrase = a.question.phrase.replace('*',a.interview.nickname) formset = AnswerFormset(queryset=answer_list) return render(request, 'interview.html', { 'formset' : formset, }) -
Cached and restricted Django model
I have started a Django project. I need to manage groups of users (with subgroups), with caching for performance and throw an exception if someone attempts to make a cycle (a group which is directly or indirectly its own subgroup). Should I derive from models.Model or just use models.Model in my own class (not derived from Model)? -
Which static file is loaded when two files have the same name?
Referring to a comment-question asked in the answer of this question, let's say I have two static files from two different apps that both have the same name style.css: /foo /static /css /style.css /views.py /models.py /urls.py /bar /static /css /style.css /views.py /models.py /urls.py And I manage.py collectstatic all the files into STATIC_ROOT, what happens to style.css? How is precedence established for which style.css to load? How does each app's templates know which style.css to load? I guess what I'm really asking is: what is the django best practice procedure for having static files with the same name in the same project? -
How to deploy django app on heroku with edited packages using windows 10?
I tried deploying my app on heroku but it is giving me errors because it install the packages mentioned in requirements.txt. and I have made some changes in packages that are installed on my pc as heroku download new packages the changes I have made in packages on pc pc are not showing on heroku. So I their any way so that heroku uses the packages that I have installed on my pc instead of installing new packages. I have also tried to create virtual environment but again it is installing new packages. -
Can't add images in Django admin
I have a model that has an image field on it in Django. When I am in the admin trying to add an instance of that model, it reloads the page, clears the image path I just added, and says there is an error with the image. In my debugger console, I can see that these http requests are being made, and that some of them return a 404. [14/Sep/2016 18:40:58] "POST /admin/products/merchandise/add/ HTTP/1.1" 200 36610 [14/Sep/2016 18:40:58] "GET /static/admin_js/tinymce_init.js HTTP/1.1" 404 1685 [14/Sep/2016 18:40:58] "GET /admin/jsi18n/ HTTP/1.1" 200 3189 [14/Sep/2016 18:40:58] "GET /static/admin_js/tinymce_init.js HTTP/1.1" 404 1685 I checked my media_url, media_root, and everything seems to be fine, so I'm not entirely sure why this is throwing an error. urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from pca_palooza.views import view_home, view_index urlpatterns = [ ... urls ... ] if settings.DEVELOPMENT: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Product(models.Model): title = models.CharField(max_length=200) sku = models.CharField(max_length=200) status = models.CharField(max_length=20, choices=STATUS_CHOICES) palooza = models.ForeignKey(Palooza) description = models.TextField(max_length=2000, blank=True) primary_image = models.ImageField(blank=True, upload_to='product_images/primary_images/%Y/%m/%d') base_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) slug = models.SlugField(unique=True, help_text='Auto generated from the title') meta_title = models.CharField(max_length=100, blank=True, null=True) meta_description = models.CharField(max_length=180, … -
Existence of an object in many-to-many relation
Python Django code: class UserGroup(models.Model): users = models.ManyToManyField(User) def __contains__(user): pass # What should be here? (User here is another model.) How to efficiently check whether a user "belongs" to the given group of users? -
Django migrations - change model from Int to CharField and pre-populate from choice option
In a model, I have an IntegerField that is mapped to a CHOICES tuple. The requirements for that field have changed to the point that updating the options in that tuple will require too frequent maintenance, so I've decided to alter it to a CharField Is there a way I can do this inside the migrations, or would it be better to create a new column, update with the appropriate value and delete old column? -
python 3 : How to connect to external server withn in Django view using urllib?
Hello I am trying to connect to external server with in my Django app. However it is telling me that the connection is refused and authentication error. I am confident that this is an django crsf error since, when I create a local python file, I am able to connect to the server with no error. I have included the screen shot below this line. This is the local python file in which that works. This is the local python file which works well This is the Django code that even if I try to make a connection with the request module or the urllib module it both gives me an error. This is the Django App file in which there is always a connection error -
remove the default select in ForeignKey Field of django admin
There are around 1.5 lakhs entry in User model. So when i am using it in django-admin without the raw_id_fields it is causing problem while loading all the entry as a select menu of foreign key. is there alternate way so that it could be loaded easily or could become searchable. Basically i have these models as of defined above and there is a User model which is used as ForeignKey in ProfileRecommendation models. so the database entry for user model consist of around 1,50,000 entries. I don't want default select option for these foreign fields. Instead if can filter them out and load only few entries of the user table. Or anyhow i can make them searchable like autocomplete suggestion admin.py class ProfileRecommendationAdmin(admin.ModelAdmin): list_display = ('user', 'recommended_by', 'recommended_text') raw_id_fields = ("user", 'recommended_by') search_fields = ['user__username', 'recommended_by__username',] admin.site.register(ProfileRecommendation, ProfileRecommendationAdmin) models.py class ProfileRecommendation(models.Model): user = models.ForeignKey(User, related_name='recommendations') recommended_by = models.ForeignKey(User, related_name='recommended') recommended_on = models.DateTimeField(auto_now_add=True, null=True) recommended_text = models.TextField(default='') -
Django+heroku: django logs appear, app logs don't
I read all the StackOverflow answers, all the blog posts on the subject, and tried everything twice, but I still can't get my Django app's log messsages to appear in the heroku log (Django's own messages do appear). Can anyone please paste a full LOGGING config that works in heroku? # views.py import logging logger = logging.getLogger(__name__) def a_view(request): # ... logger.exception('error finding file') # ... with: # settings.py LOGGING = { "version": 1, "disable_existing_loggers": False, 'formatters': { 'simple': { 'format': '%(levelname)s [%(name)s:%(lineno)s] %(message)s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'simple', "stream": sys.stdout }, }, "loggers": { "root": { "handlers": ["console"], }, # last try :( "myapp": { "handlers": ["console"], }, "django": { "handlers": ["console"], } } } -
class based view django multiple slugs
I have cbt generic listview I want filtering with two slugs. But slug_url_kwargs only allows to pass single string. How can i update slug_url_kwarg to support multiple slugs? Or what can i do else? -
Not able to save captured image in right directory
I am working on a project related to image processing. I would like to capture an image from a webcam and want to display it on webpage. I am using django framework for web stuff. Program to capture image from webcam in views.py: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import cv2 def home(request): return render(request,'detect/home.html',{}) def get_image(camera): retval, im = camera.read() return im def webcam(): camera_port = 0 ramp_frames = 30 camera = cv2.VideoCapture(camera_port) for i in xrange(ramp_frames): temp = get_image(camera) print("Taking image...") camera_capture = get_image(camera) file = "/detect/static/test_image.png" cv2.imwrite(file, camera_capture) del(camera) @csrf_exempt def display(request): webcam() return render(request,'detect/display.html',{}) Here is a screenshot of my directory structure: If I don't mention any path and only include the name of the image file(file = "test_image.png"), the image gets saved in /moody/project. I would like to save image in /moody/project/detect/static/. -
Restrict access to view based on if request came from other view
I have a view that schedules a celery task to run when you visit the url: class ScheduleTask(View): def get(self, request, *args, **kwargs): obj = get_object_or_404(ObjModel, uuid=kwargs.get('obj', None)) context = { 'site': RequestSite(request), 'secure': request.is_secure() } schedule_task.delay(obj.uuid, context) # schedule celery task return redirect(reverse( 'users:user-list', kwargs={'user': obj.user.uuid})) I would like to prevent anyone from just entering this view's url into the browser (Because it would schedule the task.) I would like to raise a permission denied exception if they do. I only want it to be accessible from this other view: class CompletionView(TemplateView): def post(self, request, *args, **kwargs): ... if 'save_and_submit' in request.POST: # This is the only place I would like ScheduleTask to # run from. return redirect(reverse('users:schedule-task', kwargs={'obj': obj_uuid})) How can I accomplish this? I feel like I should set some sort of token or cookie, but I'm not totally sure. Maybe the ScheduleTask view is not even necessary, and I should just put the code after if 'save_and_submit' in request.POST -
redirect to another view function
As users login I'd like to redirect them simply to index instead of having '/login/' in the url. I have two view functions one for login and index. index view def index(request): context = { } return render(request, 'index.html', context) login view def login(request): username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) else: print('Wrong user') return redirect('views.index') #<------ Something like that(?) -
Registering all models in an app with admin programmatically including all fields in list_display
I am able to register all models in an app with the admin programmatically as such: app = apps.get_app_config('school') for model_name, model in app.models.items(): admin.site.register(model) Now, I would like to do further configuration to show the models with list display (grid) and include all fields available. For example: class PersonAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'last_name', 'email', 'is_superuser', 'is_staff', 'is_active', 'school_id', 'position_id', 'school_contact', 'phone', 'extension',) admin.site.register(Person, PersonAdmin) And I want to do this for each and every model in my app. How can I do that?