Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check current time continuously in a django app?
As a fresher in django i am trying to make an django app which will take name and date of birth from user and will send a birthday reminder to user. Now i have setup model for it but i am stuck at how can i check the current date time continuously in background so that we can send reminder to the user. Below is my sample Model for it. models.py class BirthDayModel(models.Model): name=models.CharField(max_length=30) birthdate=models.DateTimeField() user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) timestamp=models.DateTimeField(auto_now_add=True) Please suggest on it. Thanks -
User Profile Creation on User model's post_save signal
I have UserProfile model that I instantiate whenever a User is created by using post_save signal everything is working fine except the ImageField in the userprofile. I am using django-allauth for signup and login. When I try to access the profile page of any user, the console repeatedly prints this : [28/Dec/2016 12:22:06] "GET /media/C%3A/Users/shagu/Desktop/zorion-develop/project_1 /media/profile/images/Users/shagu/Desktop/zorion-develop/project_1/media/profile/images/... and says this is the end ../zorion-develop/project_1/media/profile/images/nobody.jpg HTTP/1.1" 302 0 [28/Dec/2016 12:24:26] code 414, message Request-URI Too Long [28/Dec/2016 12:24:26] "" 414 - The profile model is as follows : class UserProfile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) image = models.ImageField(width_field="width_field", height_field="height_field", upload_to=os.path.join(settings.MEDIA_ROOT,'media', 'profile','images'), default = os.path.join(settings.MEDIA_ROOT,'media', 'profile','images', 'nobody.jpg'), ) height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) age = models.IntegerField(null=True, blank=True) gender = models.CharField( choices=( ('M', 'male'), ('F', 'female'), ), default='M', max_length=1) profile_confirmed = models.BooleanField(default=False) settings related to media are as follows : MEDIA_ROOT = os.path.join(os.path.dirname(PROJECT_ROOT)) MEDIA_URL = "/media/" And this is how I am trying to access the image in my template : <div align="center"><img alt="User Pic" src="{{ user.userprofile.image.url }}" id="profile-image1" class="img-circle img-responsive"> I am kinda new to django. Please let me know where I am messing up. -
How to make Django Application open the CORS whitelist to anyone?
I have a Django application that looks similar to the one described in the official tutorial mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py However, my application is just a series of RESTful endpoints. I have no HTML templates or any other behavior like they have in the tutorial. Inside the mysite/mysite/settings.py file, I have the following setting defined: CORS_ORIGIN_WHITELIST = ['localhost:8080'] This allows only front end applications running in the browser at localhost:8080 to send HTTP requests to hit my Django endpoints. Requests coming from other sites through the browser will cause the browser to give CORS errors. I would like my Django endpoints to accept HTTP requests from anywhere. IE: I want there to be no whitelist (or a whitelist that allows anyone to hit it). How can I do that? If that is not possible (presumably because it is a security hole?) how can I specify a command-line argument such that I specify the CORS whitelist on the command line when I run the application? This is how I run the application: gunicorn mysite.wsgi:application \ --name mysite \ --bind 0.0.0.0:8000 \ --workers 3 \ "$@" -
Django - Manual form field rendering adding a class
I am working with Google Re-Captcha and would like to enable the submit button once the Re-Captcha have been filled. I want to add a callback function to the Div class my code looks something like this: <div class="input-field col s12"> {{ form.captcha.errors }} <div data-callback="enableBtn"></div> {{ form.captcha }} </div> This currently returns the data-callback outside of the function. How can I add the data-callback attribute to the form.captcha? -
Django 'save and create new' button. How?
I need help in my django project. I need a button 'save and create' in my form in template. How I create button 'save and create' in Django? What does views.py? What does in templates? -
local variable 'template' referenced before assignment
I have model called template in my models.py file class template(models.Model): id = models.AutoField(primary_key=True) customer_id = models.ForeignKey(customer,on_delete=models.CASCADE) name = models.CharField(max_length=255,blank=False,null=False) data = RichTextField() def __unicode__(self): return self.name def __str__(self): return self.name def get_absolute_url(self): return reverse("templatedetail",kwargs={"id": self.id}) Then i'm importing this model in my views.py from .models import template Then when i try to get all objects in a method def assign_user_template(request): templates = template.objects.all() but i'm getting this local variable 'template' referenced before assignment error. the model is imported in a correct way. when i try this on a different model it is not giving any error. -
Error: NoReverseMatch at / (after modifying code to include Bootstrap)
As an overview, I'm making this website where users can make an account to take notes online and store it in their account. My folder directories are as follows: site1 -> mynotes -> users -> mynotess mynotes is the main project directory, while users and mynotess (double s) are both the apps (Sorry for bad naming but it's too late to change it now). I've got this NoReverseMatch at / error. It also says: Error during template rendering In template C:\Users\Steven\site1\mynotess\templates\mynotess\index.html, error at line 0 This is the traceback from Command Prompt: Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Steven\site1\mynotess\views.py", line 15, in index return render(request, 'mynotess/index.html') File "C:\Python34\lib\site-packages\django\shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Python34\lib\site-packages\django\template\loader.py", line 68, in render_to_string return template.render(context, request) File "C:\Python34\lib\site-packages\django\template\backends\django.py", line 66, in render return self.template.render(context) File "C:\Python34\lib\site-packages\django\template\base.py", line 208, in render return self._render(context) File "C:\Python34\lib\site-packages\django\template\base.py", line 199, in _render return self.nodelist.render(context) File "C:\Python34\lib\site-packages\django\template\base.py", line 994, in render bit = node.render_annotated(context) File "C:\Python34\lib\site-packages\django\template\base.py", line 961, in render_annotated return self.render(context) File "C:\Python34\lib\site-packages\django\template\loader_tags.py", … -
In django how to move objects from a sessions foreign key to a user foreign key when the user logs in
I have a model that saves a endusers progress on a task. class TaskCompleted(models.Model): session = models.ForeignKey('sessions.Session', on_delete=models.SET_NULL,blank=True, null=True) user = models.ForeignKey(User, blank=True, null=True) task = models.ForeignKey(Task, blank=True, null=True) The enduser might be logged in or might not be. If they are logged I save the it against the user and if they are not I save it against the session. When the a user logs in I want to find any tasks they have completed while unauthenticated and then update the user foreign key to relate it to their account. I am finding that the session is destroyed thus setting the session to Null. I am interested in other's suggestions on how to handle this? -
LITERAL_STARTS_FROM_LETTER expected unexpected end of file
While in PyCharm, if I run Tools > Run manage.py Tasks... I get the normal manage.py@{System} environment that can correctly run tasks, such as runserver, makemigrations, etc. Though, before I type the task to run (auto-complete correctly works as well), I am presented with a prompt that has a warning. My prompt manage.py@{System} > is followed by a red squiggly-underline with the popup warning of: LITERAL_STARTS_FROM_LETTER expected, unexpected end of file Because everything still works it's not a pressing issue, but I believe resolving this would allow PyCharm to run as intended. I have not found anything online or from JetBrains support. PyCharm Version: PyCharm 2016.3.1 Build #PY-163.9735.8, built on December 14, 2016 Licensed to {Me} Subscription is active until October 25, 2017 For educational use only. JRE: 1.8.0_112-release-408-b6 x86_64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o -
Unable to use Django Authenticate
I am receiving this error: TypeError at /auth/ authenticate() missing 1 required positional argument: 'request' I am using Django and also Django Rest Framework. The HTTP POST looks like this: { "username": "HelloUser", "password": "Hello123" } VIEW @csrf_exempt @api_view(['POST']) def authenticate(self, request): print(request.data) user = authenticate(username=request.data['username'], password=request.data['password']) if user is not None: return Response({'Status': 'Authenticated'}) else: return Response({'Status': 'Unauthenticated'}) URLS urlpatterns = [ url(r'^', include(router.urls)), url(r'create/', views.create), url(r'retrieve/', views.retrieve), url(r'auth/', views.authenticate), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -
How to annotate the result of a model method to a django queryset
From the django docs on annotate(): Annotates each object in the QuerySet with the provided list of query expressions. An expression may be a simple value, a reference to a field on the model (or any related models), or... Is it possible to annotate the results of a method for the model? I've tried like this: my_queryset.annotate(ann=my_method(request.user)) and my_queryset.annotate(my_method(request.user)) But I get an error that my_method is not defined. The method exists and works fine normally: object.my_method(request.user) I think there is a decorator to have a method treated like a field, but I can't seem to find any info on that (it might have been for django template based method calls, so possibly not related) An alternate solution is provided in this question. But I would like to know if it is possible to annotate method results. -
django Bring data from the database for editing
Hello i'm new with django. I am starting a small project to start understanding the operation of the forms and I have run into a problem. I created a form to create a client and another to modify it the problem is that the modification form does not bring the information of the database. Bring a basic form without fields with data. view: def cliente_update(request, id=None): queryset = get_object_or_404(Cliente, id=id) if request.method == 'POST': form = ClienteForm(request.POST or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() # return HttpResponseRedirect(instance.get_absolute_url()) else: form = ClienteForm() context = { "titulo": "Editar informacion del Cliente", "queryset": queryset, "form": form, } return render(request, "clientes/form.html", context) -
Adding localhost 127.0.0.1 to ALLOWED_HOSTS
A couple times a day, but not in any pattern I can see, I get this in my django logs: ERROR Invalid HTTP_HOST header: u'127.0.0.1:9000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. I've tried to match the time of the error to a request in nginx access_log, but I'm not seeing a connection. I currently have ALLOWED_HOSTS set to ['.mydomain.com'] What could be causing these localhost requests? Is it common/harmless to add 127.0.0.1 to ALLOWED_HOSTS? Setup: Ubuntu 14.04 Django 1.8.17 nginx 1.4.6 gunicorn 17.5 -
How to generate a unique auth token in python?
I am trying to write a token based auth in flask for my android app. For that I need a unique token using which I can verify the user. Itsdangerous library provide a JSONWebSignatureSerializer function using which I can create JWT token. So my first question is, is it safe to use JWT for mobile based auth ? Secondly, I did a little bit research on how django rest framework generates its token. def generate_key(self): return binascii.hexlify(os.urandom(20)).decode() Is this token unique or just a random one? Which one should I use for a mobile based auth? What is the based way to generate a unique token for mobile application in python ? -
Django 1.10 Using csrf Token
Novice Django user here. I am trying to use csrf for my form because if I don't I get this message: (and of course protection against forgery) CSRF verification failed. Request aborted. Here is my code: from django.views.decorators.csrf import csrf def login(request): c = {} c.update(csrf(request)) return render_to_response('login.html', c) So in django 1.9 and older there was something like this: from django.core.context_processors import csrf But I get the following error: 'module' object is not callable Any help? Thanks -
Unable to access values in Request
I am not understanding how to access values in my POST request from within my Python API. Why can I not access the values in my API Request? I am clearly getting them in the request.body, but am unable to retrieve them. I have tried the following methods: request.POST['username'] request.POST.get('username') I receive an error stating django.utils.datastructures.MultiValueDictKeyError: Here is the request.body, which does not seem like JSON at all. "{\n \"username\": \"TestUsername\",\n \"password\": \"TestPass\"\n}" POST REQUEST { "username": "TestUsername", "password": "TestPass" } HEADERS Accept: application/json Content-Type: application/json VIEW @csrf_exempt @api_view(['POST']) def create(request): user = User() if 'username' in request.POST and 'password' in request.POST: user.username = request.POST['username'] user.set_password(request.POST['password']) user.save() return Response({'Status' : 'Complete'}) else: return Response({'Status': 'Incomplete'}) -
I want to redirect users upon login and filter out their details in a template
Here is the statement verifying whether a user exists. if user is not None: auth.login(request, user) return HttpResponseRedirect('/studentloggedin/') Here is the template I define for the users to be routed to. Student is a foreign key to user in the admin and registration is a foreign key to student model. Student is also a foreign key to other models and I want to query out everything related to that user. def studentloggedin(request): registration = Registration.objects.get() student = Student.objects.filter(registration=registration) context = { 'registration': registration, 'student': student, } return render(request, "studentloggedin.html", context) And here is one of the fields that I'm querying in the html template: {{ student.previous_school }} But no information displaying upon login right now. I don't really know why. -
Proxy server using Django
I am trying to create a local proxy server in django but I am unable to redirect the proxy requests to my view.In my system settings I have set my django server as the proxy. I am getting logs as such in my server. [27/Dec/2016 22:01:40]"CONNECT www.google.co.in:443 HTTP/1.1" 404 1783 My url configration is : url(r'^.*$', RedirectView.as_view(pattern_name=u'homepage', permanent=False)) What am I doing wrong while trying to redirect any browser request to my view ? -
Django userena group and role based permission setup and customization
I am using django-userena application to handle user-registration, user-profile and log-in. Now I'm writing an application where - All users can create a profile(buyer or seller) A user(seller) can create a gig(gig is like a profile(service rendered) where we store information about the gig and a user can have upto 5 gig). Other users(buyers) can order for any gig(service). Ordering requires seller's approval. Only sellers can add,edit and delete the gigs page and he can create an offer for "the default price" or a "custom order for the buyers order on a gig" . All registered users(buyers and sellers) can view their profile and other gigs profile. How should I architect this application? setting my groups(sellers and buyers) and permissions roles. i have only setup the default userena functionality. how do i extend this. -
Javascript real-time voice streaming and processing it in django backend
Hi I'm currently working on a project where I want to stream users' voice, using js, in realtime - from user's perspective, think Google's speech recognition API demo. So far I tried few jquery libraries but they doesn't seem to work like I expected - there was either no compatibility with web browser, they couldn't detect microphone or sending to server failed. Recently, I was exploring webrtc and it seems it could do the job, but I'm not sure if it's possbile to stream from web browser to django backend. I don't want to use neither node.js nor java's apllets. I will appreciate any help with js as well as with receiving voice stream in django. Thank you! -
Serializer works in the Django shell but fails in the view
I have those models: class ServiceCategory(models.Model): class Meta: db_table = 'service_categories' category = models.CharField(max_length=24) def __str__(self): return self.category class Service(models.Model): class Meta: db_table = 'services' service = models.CharField(max_length=24) category = models.ForeignKey('ServiceCategory') def __str__(self): return self.service And their serializers: class ServiceCategorySerializer(serializers.ModelSerializer): class Meta: model = ServiceCategory fields = ('id', 'category') class ServiceSerializer(serializers.ModelSerializer): category = ServiceCategorySerializer() class Meta: model = Service fields = ('id', 'service', 'category') After this setup, I quickly bumped into a problem creating a new Service via its associated ServiceSerializer: I have to also pass a complete ServiceCategory with all its fields even though I only need its id. The ServiceCategory above looks simple enough but that's hardly the case since I've omitted a lot of its other fields for brevity. So passing the complete attributes of a ServiceCategory into a form on the front end seemed terribly inefficient to me so I tried another approach: class UpsertServiceSerializer(serializers.ModelSerializer): category = serializers.IntegerField() # not ServiceCategorySerializer() class Meta: model = Service fields = ('service', 'category') def create(self, data): c = ServiceCategory.objects.get(pk=data['category']) return Service.objects.create(service=data['service'], category=c) My intention is to use UpsertServiceSerializer for creates and updates, with ServiceSerializer now being used for reads. UpsertServiceSerializer worked without a problem in the Django shell — … -
Two submit buttons for different actions on same form, how?
I have a nice form on my django app with a nice form declared in forms.py class EntityGlobeForm(forms.Form): #checkboxes yay! layer = forms.ChoiceField(choices=MY_CHOICES, widget=forms.RadioSelect()) Simple, and this works when the submit button is hit I can consume the data in the views action: def globe(request): if request.method == 'POST': form = EntityGlobeForm(request.POST) if form.is_valid(): #you are going to have to make a panel and paginate footprints #object_list = ChangeDetectCSV.objects.filter(processing_level='RAW') #AND DATE sensor = form.cleaned_data.get('layer') #it is really sensor #if sensor is not object_list = CesiumEntity.objects.filter(sensor = sensor) jdata= serialize('geojson', object_list, geometry_field='mpoly', fields=('name','file_name', 'id', 'dzi_location', 'country_code', 'corner_coords', 'sensor', 'targetName', 'collection_date')) #get the selection check box that was clicked to know what entities to get #grab entities #object_list = ChangeDetectCSV.objects.filter(processing_level='RAW') #AND DATE #wrap it up with a listing of which ones work, and html and all and pass it back to the view. # do something with your results return HttpResponse(json.dumps({'data': jdata})) else: form = EntityGlobeForm return render_to_response('swsite/sw_nga_globe.html', {'form':form }, context_instance=RequestContext(request)) All fantastic, but what I need is another button on/for the same form to do something else (this button will instead export a KML document). So I want it to look, behave the same, be on the same form, reference the … -
How to get the requesting application details from DRF with DOT
I am using Django Rest Framework along with the Django oAuth toolkit. The flow is currently: 1) Third party application registers with the Authorization Server 2) User uses my application oAuth2 to login into the third party application 3) The third party application makes some requests to my server with the user's auth token in the Header 'Authorization' 4) DOT converts the token to a user object and passes it to the request object My question is, a few views require the application id of the application that is requests on behalf of the user. DRF and DOT documentation doesn't show how to do this. Does anyone have any ideas how to implement this flow? -
Django request.is_ajax returns False for
I'm sending cross-domain ajax request and on another end request.is_ajax() gives False var text = getSelectedText(); text = 'text'; if (text){ var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText) } }; xhttp.open("GET", "http://example.com/text=" + encodeURIComponent(text), true); xhttp.send();} -
How to create a class based view using a custom form to perform an action on an object
For a stocktaking interface I want a user to insert a decimal for new amount items in stock. Having this decimal a transaction is issued setting the item from stock taking to the actually value by adding difference. To do yo I have added a view providing just a field for inserting the decimal views.py: class StorageItemStockTakingView(FormView): form_class = StockTakingForm success_url = reverse_lazy('storage_item_list') template_name = 'pmgmt/storageitem/stocktaking.html' def form_valid(self, form): si = StorageItem.objects.get(pk=self.kwargs["pk"]) si.stock_report( Decimal(self.request.POST["amount"]), self.request.user) return super(StorageItemStockTakingView, self).form_valid(form) based upon a custom form inside forms.py class StockTakingForm(forms.Form): amount = forms.DecimalField( _("Parts now inside storage"), max_digits=10, decimal_places=4, help_text=_("The amount of currently inside storage place.")) The used template is quiet simple: {% extends "base.html" %} {% load i18n %} {% load semanticui %} {% block content %} <h1>{{ object }}</h1> <p>{% trans "It will create an Transaction adjusting the amount for items on stock to reported one.." %}</p> <form method="post" class="ui form segment"> {% csrf_token %} {{ form|semanticui }} <input class="ui button blue" type="submit" value="Submit"> </form> {% endblock %} This did work with Python2. But when I'm using this on Python3 I'm getting an error 2016-12-27 19:17:57,206 django.request 24760 Thread-2 ERROR Internal Server Error: /pmgmt/storageitem/1/stocktaking/ Traceback (most recent call last): File "/home/frlan/quellen/partuniverse/p3/lib/python3.5/site-packages/django/core/handlers/base.py", …