Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating random URLs in Django?
I'm creating a project where: A user submits an input into a form That data is input into the database A random URL is generated (think imgur / youtube style links) The user is redirected to that random URL The input data is display on that random URL forms.py class InputForm(forms.Form): user_input = forms.CharField(max_length=50, label="") random_url = forms.CharField(initial=uuid.uuid4().hex[:6].upper()) models.py class AddToDatabase(models.Model): user_input = models.CharField(max_length=50, unique=True) random_url = models.CharField(max_length=10, unique=True) views.py def Home(request): if request.method == 'POST': form = InputForm(request.POST) if form.is_valid(): user_input = request.POST.get('user_input', '') random_url = request.POST.get('random_url', '') data = AddToDatabase(user_input=user_input, random_url=random_url) data.save() return render(request, 'index.html', {'form':form}) else: form = InputForm() return render(request, 'index.html', {'form':form}) index.html <form action="" method="POST"> {{form}} {% csrf_token %} <input type="submit"> </form> I'm new to Python / Django, which is probably obvious. The above code allows users to submit an input which is succesfully added to the database. It also generates a 6 character UUID and adds that to the database. The problem is I don't know how to turn that UUID into a URL and redirect the user there after submitting the form. I've tried a couple of methods so far, such as adding action="{{ random_url }}" to the index.html form, as well as … -
AppConfig.ready() is Running Twice on Django Setup (Using Heroku)
I have a function that needs to run in the background on one of my web applications. I implemented a custom AppConfig as shown below: class MyAppConfig(AppConfig): run_already = False def ready(self): from .tasks import update_products if "manage.py" not in sys.argv and not self.run_already: self.run_already = True update_products() However, this command is being executed twice (the update_products() call) As stated in the documentation: In the usual initialization process, the ready method is only called once by Django. But in some corner cases, particularly in tests which are fiddling with installed applications, ready might be called more than once. In that case, either write idempotent methods, or put a flag on your AppConfig classes to prevent re-running code which should be executed exactly one time. I feel like I am following what the documentation says to do. What gives? -
Deploy django as war - Jython
I'm trying to deploy a django app as war (to use with JBOSS server).I have seen the documentation and I made this: jython manage.py builder --include-java-libs=/usr/share/java/jython/jython.jar And I have this error: Traceback (most recent call last): File "manage.py", line 16, in <module> raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? What should I do? Thanks. -
Looping over JSONResponse() result from django in jquery
I am interested in getting the results of an insert operation from views.py in form a JSON. I am getting the results alright, I think. my view looks like this: added={} if request.method=='POST': #Post method initiated. try: for id in allergies: allergy=PatientAllergy(patient=patient,allergy_id=id,addedby=request.user) allergy.save() added[allergy.id]=id except BaseException as e: pass return JsonResponse(added,safe=False) The records, passed from JQUERY, added successfully to the database. What I want to get now is a JSON result in the form of {12:1, 13:2}. My firebag shows the response as: 12:1 13:2 I am not sure if this a valid JSON or not. If I do list(added), it gives instead: 0: 12 1: 13 which I don't want. The problem I am having now I want to go thru the returned items but I am getting incorrect results. I basically want to get 12:1, 13:2. $.ajax({ type: "POST", url: "/patient/addallergy/", data: postForm, dataType : "json", cache: "false", success: function (result) { alert(result.length); //gives undefined, rendering the below line meaningless if (result.length>0){ $.each(result,function(key,value){ alert(key); alert(value); }); } }, fail: function (result){ } }); -
Django models.Manager custom SQL query "more than one row returned" error
So I'm trying to get the result of the age() function on PostgreSQL from a column in the DB. The goal is to append a new virtual column with the age or time elapsed since the datetime stored the database. I tried this by creating a models.Manager in Django to add this new column: class PriorityManager(models.Manager): def get_queryset(self): time_elapsed = RawSQL('SELECT EXTRACT(EPOCH FROM age(datetime)) AS age FROM backend_post', params=(), output_field=models.IntegerField()) return super(PriorityManager, self).get_queryset().annotate(score=time_elapsed) I need a score column to help sort the objects later, and the score is based on the time elapsed. The query SELECT EXTRACT(EPOCH FROM age(datetime)) AS age FROM backend_post; works in the dbshell but when running it on Django, the following message comes up: ProgrammingError at /api/post/list/ more than one row returned by a subquery used as an expression I suspect the problem is that the query returns a whole column of elements while the models.Manager expected only one result. I believe there should be something sent as a parameter in the RawSQL query but I couldn't figure out what it is... Anyone knows what to do? Thank you very much! -
ListSerializer object is not iterable
Hi django newbie here, I have permissions model which is about door and door_groups. There is between ManyToMany realationship between Door and Door_Group models. And they have OneToMany realation with Permission. I want to ask, how can I get a spesific Door all distinct permissions? permissions_list = [] permissions_list.append(door.permission_set.all()) for group in door.door_group_set.all(): permissions_list.append(group.permission_set.all()) serializer = PermissionSerializer(permissions_list, many=True) return Response(serializer.data) I am getting all permissions but I can not serialize it with ModelSerializer class. Permissions Model: class Permission(models.Model): user = models.ForeignKey('users.EmailUser') door = models.ForeignKey('doors.Door', null=True, blank=True) door_group = models.ForeignKey('doors.Door_group', null=True, blank=True) days = models.CharField(validators=[validate_comma_separated_integer_list], max_length=13, null=True) start_hour = models.TimeField(default='00:00') end_hour = models.TimeField(default='00:00') created_date = models.DateTimeField(default=timezone.now) updated_date = models.DateTimeField(auto_now=True) def __unicode__(self): return 'Days: ' + self.days + ' Start:' + str(self.start_hour) + ' End: ' + str(self.end_hour) + ' User: '+ self.user.username def clean(self): # Don't allow draft entries to have a pub_date. if self.door_group is not None and self.door is not None: raise ValidationError('Choose between, group of doors or one door to give permission. Can not choosable both.') if self.door_group is None and self.door is None: raise ValidationError('Choose between, group of doors or one door to give permission.') -
Django Interchanging the urls by overiding regex part
When requesting[GET] 127.0.0.1:8000/restaurant/1 i get a clean json and 200 status code urlpatterns = [ url(r'^restaurant',views.Restaurant_List_Create.as_view(), name='all_restaurants'), url(r'^restaurant/(?P<pk>\d+)',views.Restaurant_Retrive.as_view(), name='specified_restaurant'), ] but when i interchange the url codes it runs the views.Restaurant_List_Create.as_view() (overrides the regex url) urlpatterns = [ url(r'^restaurant/(?P<pk>\d+)',views.Restaurant_Retrive.as_view(), name='specified_restaurant'), url(r'^restaurant',views.Restaurant_List_Create.as_view(), name='all_restaurants'), ] -
Django Python runserver error: Project is using Twilio for surveys
I'm currently working on a project that uses Twilio to have an automated survey. I'm trying python manage.py runserver and I get the following results: System check identified no issues (0 silenced). April 23, 2017 - 12:15:51 Django version 1.11, using settings 'vizeserver.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x04406FA8 > Traceback (most recent call last): File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\uti ls\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\cor e\management\commands\runserver.py", line 147, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\con trib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super(Command, self).get_handler(*args, **options) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\cor e\management\commands\runserver.py", line 68, in get_handler return get_internal_wsgi_application() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\cor e\servers\basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\uti ls\module_loading.py", line 20, in import_string module = import_module(module_path) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\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 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 "C:\Users\Thomas\Documents\Development\TwilioSurvey\vizeserver\vizeserver\wsgi.py", lin e 16, in <module> application = get_wsgi_application() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\cor e\wsgi.py", line 14, in get_wsgi_application return WSGIHandler() … -
Use javascript to set action in django form
In django 1.10, I need to pass parameters from one html template back to view.py, and finally render again the same view. The problem is in setting action in the html to use javascript. This is my html template: <form method='POST' action='/res/{{link}}/{{page_id}}/{{email}}/'> <input type="hidden" name="email" value="{{email}}"> <input type="image" type='submit' src={% static "assets/images/twitter_icon.png" %}> </form> {{page_id}} in action changes as the user interacts with the web page (using a drop-down selector). The following javascript would be able to catch this: <script> function post_redirect_link() { var page_id = document.getElementById("sel1").options.selectedIndex; return '/res/{{link}}/'+page_id+'/{{email}}/' } </script> And I tried to set action dynamically as: <form method='POST' action='post_redirect_link()'> <input type="hidden" name="email" value="{{email}}"> <input type="image" type='submit' src={% static "assets/images/twitter_icon.png" %}> </form> BUT instead, I get a redirect of the type /res/correct_link/post_redirect_link()/correct_email, where "post_redirect_link()" is taken as string rather than being the value returned by the js method. Any suggestion? -
string indices must be integers, not str - django
I am trying to pass this into a post from front end but I keep on getting this error on this line and I cannot figure out why is that {"isUpdated": true} passing this in my django, I have these body_unicode = request.body.decode('utf-8') data = json.loads(body_unicode) if data['isUpdated'] is not False: # more codes I keep on getting error on this if data['isUpdated'] is not False: Can someone give me suggestions what is happening? -
How to access Manager of through model
I've created a Manager for a through model and want to use it when accessing the Many-to-many objects. class Contact(models.Model): first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) email = models.EmailField() class ContactList(models.Model): name = models.CharField(max_length=50) contacts = models.ManyToManyField( Contact, through='ContactListEntry', blank=True, ) class ContactListEntry(models.Model): contact_list = models.ForeignKey(ContactList, related_name='contact_list_entries') contact = models.ForeignKey(Contact, related_name='contact_list_entries') removed = models.BooleanField(default=False) # Used to avoid re-importing removed entries. # Managers. objects = ContactListEntryManager() Manager: class ContactListEntryManager(Manager): def active(self): return self.get_queryset().exclude(removed=True) Is there any way to access the Manager of the through field? This here: class ContactListView(DetailView): model = ContactList template_name = 'contacts/contact_list.html' context_object_name = 'contact_list' def get_context_data(self, **kwargs): ctx = super(ContactListView, self).get_context_data(**kwargs) contact_list_entries = self.object.contacts.active() # <-- THIS HERE. ctx.update({ "contact_list_entries": contact_list_entries, }) return ctx Throws: AttributeError: 'ManyRelatedManager' object has no attribute 'active' -
Django page genarte from set of inclusion_tag
I have an idea but I don't know how this should work. I have page class where I have saved list of component on page: class Page(object): title = None slug = None inMenu = False parent = None # place for register parent page # array of components in page # { componentName: 'carousel', htmlConent: '', images: ['slide_01.jpg', 'slude_02.jpg'] } #(from carousel model) components = [] template = Template ('index.html') I have the components now as a templateTags as inclusion_tag in django I need render page component with args. I want do something like: {% extends 'base.html' %} {% block content %} {% for component in page.components %} {% render_component component%} {% endfor %} {% endblock %} Have you tried something like that? I don't know how exactly render the templateTags from the array with args. Could someone help me with this?. -
Django Table data POST form
I have a question about how to pass a table( or List) items to the server when sending data in a form using the POST method, both on the client side using jquery, and on the server side using django forms. And Thank you -
Minimal max_length of a Django CharField to store the output of the sign method of a Signer object (django.core.signing)
I have to sign a value, in my case emails, and I have to store the signed value in a Django CharField. I am using the Signer.sign method of the django.core.signing module. Since I would like to insert also the max_length parameter for the db field, my question is, what would be the minimal value I can put in the max_length in order to always successfully store it in the db. -
Update view not working? Django
The users are able to create an aircraft post at this url: url(r'^upload/aircraft/$', aircraft_create, name="aircraft_create"), I've created a summary page where all of the users posts are displayed. They're able to edit and delete their posts here. The url: url(r'^account/uploads/$', upload_overview, name="account_uploads"), However, I want the user to be able to edit their posts on their summary page. The way I got it set it now, is that they can edit at upload/aircraft/edit, but I want to to be account/uploads/edit. I've set it up like that but it's not doing anything? Any clues as to what it might be? Aircraft/views.py def aircraft_create(request): form = aircraft_form(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() messages.success(request, "Your upload has been successfully added!") return HttpResponseRedirect(instance.get_absolute_url()) else: messages.error(request, "There seems to be something wrong. Have a look again..!") context = {"form":form,} return render(request,'aircraft/aircraft_form.html', context) Template {% if UploadedAircraft %} {% for upload in UploadedAircraft %} <div class="col-lg-offset-0 col-md-4 col-sm-3 item"> <div class="box"><a href="{{ upload.get_absolute_url }}"><img src="{{ upload.image.url }}" width="200px" height="200px" alt="{{ upload.title }}"/></a> <h3 class="name"><a href="{{ upload.get_absolute_url }}">{{ upload.name }}</a></h3> <a href="{% url 'aircraft_update' %}"><button class="btn">Edit</button></a> <a href="{% url 'aircraft_delete' %}"><button class="btn">Delete</button></a> </div> Summary page view def upload_overview(request): uploaded_aircraft = Aircraft.objects.filter(user=request.user) … -
django-schedule openURL is not defined
I have installed django-scheduler in my project but when trying to click on an event to edit or delete it I get to following error in console Uncaught ReferenceError: openURL is not defined at HTMLAnchorElement.onclick This is happening on the following html (which is in the django-scheduler url schedule/calendar/daily using the standard templates): <a href="#" onclick="openURL('/schedule/event/delete/29/?next=/schedule/calendar/daily/contractor2/%3Fyear%3D2017%26month%3D4%26day%3D23', event);"> <span class="glyphicon glyphicon-remove"></span> </a> What have I got wrong? -
Modifying django form field choices with few hundred items causes freeze / not responsive
I want to dynamically modify a field choices in django form. Because item's list is pretty long (more then 650 items), I store them in django cache. However, when I want to inject them as field choices, application become unresponsive (sometime returns ERR_EMPTYRESPONSE). My view: class HomeView(TemplateView): template_name = 'web/pages/homepage.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) categories = cache.get_or_set('categories_list', Category.objects.values('uuid', 'code', 'name'), 3600) categories_choices = [(o['uuid'], '{} ({})'.format(o['name'], o['code'])) for o in categories] print(categories_choices) #its printing proper choices here context['form'] = SearchForm() context['form'].fields['category'].choices = categories_choices #this line causes freeze/timeout return context Any idea what is happening there? Maybe 600+ items as dropdown choices is too many? -
Django check if authenticated user is same as the author of the post?
I want to display edit button only if the user is authenticated as the author of the post. example: 1.example.com/username1 2.example.com/username2 i want to take to user to the edit profile page, i got all the permission working correctly and set the views accordingly. My Problem: i loggedin as username1 so i should not be able to access example.com/username2/edit/. i got this to work in the views by adding some permissions, but i dont want to display the edit button when the loggedin username1 views the page of username2. Now i use {% if user.is_authenticated %} and this results in display the edit button on page of username2 even though the loggedin user is username1. Any simple solutions that can be used in the templates directly? -
Extending Django Admin templates
I try to modify django admin templates I created custom template with the name corresponding to template, that I want to override. I try the following {% extends "admin/change_form.html" %} <h1>HELLO</h1> If I reload the page I dont see h1 tag. If I try {% extends "admin/change_form.html" %} {% block field_sets %} <h1>HELLO</h1> {% endblock %} I seen only h1 tag and dont see model's editing fields. What have I do to see form and h1 tag in same time ? -
Django-paypal works in IPN simulator but not in sandbox
I have written an IPN following the django-paypal IPN tutorial, however mine does not seem to work. It works no problem on the PayPal IPN Simulator, and I receive the IPN and the code executes, however when I try to do it in Sandbox mode, the payment goes through by no response. Views: from django.core.urlresolvers import reverse from django.shortcuts import render from paypal.standard.forms import PayPalPaymentsForm def view_that_asks_for_money(request): # What you want the button to do. paypal_dict = { "business": "receiver_email@example.com", "amount": "100.00", "item_name": "Yep", "invoice": "Turbo deadly", "notify_url": "http://myip/paypal/", "return_url": "https://www.example.com/your-return-location/", "cancel_return": "https://www.example.com/your-cancel-location/", "custom": "Upgrade all users!", # Custom command to correlate to some function later (optional) } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render(request, "payment.html", context) from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received def show_me_the_money(sender, **kwargs): ipn_obj = sender category = Category(name="Got IPN") category.save() if ipn_obj.payment_status == ST_PP_COMPLETED: category = Category(name="Good Buzz, complete") category.save() else: category = Category(name="Bad Buzz, not complete") category.save() valid_ipn_received.connect(show_me_the_money) invalid_ipn_received.connect(show_me_the_money) URLS: etc etc etc... url(r'^paypal/', include('paypal.standard.ipn.urls')), url(r'^test/$', views.view_that_asks_for_money, name='ask') ] When I send my IPN to : http://myip/paypal/ it works but not through sandbox. -
Some ambiguities with the nesting of modules in the structure (Django)
I have module "patientmodule" and template in it where I point on the <a href="{% url 'appointments' id=patient.id %}">List of appointments</a> but this pattern doesn't exist in the urls.py he exists in the inner module "appointments/urls.py" How I can correctly point url, becouse now I see next error: "Reverse for 'appointments' with arguments '()' and keyword arguments '{'id': 1}' not found. 0 pattern(s) tried: []" -
Django: reverse() and get_absolute_url() returns different output for same object?
When used with flatpages reverse() and get_abolute_url() returns different outputs: >>> about = FlatPage.objects.get(id=2) >>> >>> about <FlatPage: /about-us/ -- About us page> >>> >>> about.get_absolute_url() '/about-us/' >>> >>> >>> reverse('django.contrib.flatpages.views.flatpage', args=[about.url]) '/%2Fabout-us/' ## from where %2F comes from ? >>> Here is the sitewide urls.py (sitewide): from django.conf.urls import url, include from django.contrib import admin from django.contrib .flatpages import urls as flatpage_urls # from . import blog urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include(flatpage_urls)), ] Although, I am able to access to about page at http://127.0.0.1:8000/about/ but what's going on ? -
nginx, django, gunicorn can't reach domain. Bad Request(400)
I can reach my site when going to my IP address but I can not when I go to my domain name. Here is my nginx config file (I have changed the IP and domains for privacy): server { listen 80; server_name my.ip.address example.com www.example.com; location = /facivon.ico { access_log off; log_not_found off; } location /static/ { root /home/tony/vp/vp/config/; } location / { include proxy_params; proxy_pass http://unix:/home/tony/vp/vp/vp.sock; } } And this is my productions settings.py file: from .base import * DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '0.0.0.0', 'my.ip.address', 'example.com', '.example.com'] ROOT_URLCONF = "urls.production_urls" SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_DIRECT = True SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True X_FRAME_OPTIONS = 'DENY' SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'vp', 'USER': 'vp', 'PASSWORD': os.environ["VP_DB_PASS"], 'HOST': 'localhost', } } MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL ='media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') And yes my domain is connected to digital ocean. What could be causing the Bad Request? Thanks in advance! -
Django Admin - ModelAdmin.add_form_template example
I want a custom template for one of my models Docs say that there is ModelAdmin.add_form_template method. How can I use this method ? How can I pass data from js in custom template to Django, so I can save it ? -
Django pagination with bootstrap
I am about to add a pagination to my list of contacts. I am sitting over it the whole day and have no idea what I mixed up. Important thing is that I do have a working filters - so I can narrow the list. But from my understanding pagination should work anyway. In my case I see nothing so my guess is first "if" fails. If you could point me in the right direction. Best regards. Views.py def ContactsList(request): contacts_list = Contact.objects.all() Contacts_filter = LFilter(request.GET, queryset=contacts_list) #pagination page = request.GET.get('page', 1) paginator = Paginator(contacts_list, 20) try: contacts = paginator.page(page) except PageNotAnInteger: contacts = paginator.page(1) except EmptyPage: contacts = paginator.page(paginator.num_pages) return render(request, 'index.html', context, {'filter': contacts_filter}) Template part: {% if contacts.has_other_pages %} <ul class="pagination"> {% if contacts.has_previous %} <li><a href="?page={{ contacts.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in contacts.paginator.page_range %} {% if library.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if contacts.has_next %} <li><a href="?page={{ contacts.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %}