Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Crispy Form doesn't render hidden fields in formsets
I'm using django crispy forms to create inline formsets using a model form and a helper class. In my template, If I do {% crispy entrance_formset entrance_helper %} everything works fine when I submit. But if I try to manually render each form in the entrance_formset like this: {{ entrance_formset.management_form|crispy }} {% for entrance_form in entrance_formset %} {% crispy entrance_form entrance_helper %} {% endfor %} I get the following error when submitting. django.utils.datastructures.MultiValueDictKeyError: "'entrances-0-id'" When I look at the html, I see that the hidden fields entrances-0-idand entrances-1-id are indeed missing. What am I doing wrong? form class: class EntranceForm(ModelForm): latitude = FloatField( min_value=-90, max_value=90, required=False, ) longitude = FloatField( min_value=-180, max_value=180, required=False, ) class Meta: fields = ['name', 'location', 'latitude', 'longitude', 'directions'] widgets = { 'location': HiddenInput, 'directions': Textarea(attrs={'rows': 5}) } def __init__(self, *args, **kwargs): super(EntranceForm, self).__init__(*args, **kwargs) coordinates = self.initial.get('location', None) if isinstance(coordinates, Point): self.initial['latitude'], self.initial['longitude'] = coordinates.tuple def clean(self): data = super(EntranceForm, self).clean() latitude = data.get('latitude') longitude = data.get('longitude') point = data.get('location') if latitude and longitude: data['location'] = Point(latitude, longitude) helper class: class EntranceFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super(EntranceFormSetHelper, self).__init__(*args, **kwargs) self.layout = Layout( 'name', 'latitude', 'longitude', 'directions', ) self.form_class = 'form-horizontal' self.label_class = 'col-xs-4' self.field_class = … -
Running existing Django project
I am trying to locally run an existing Django project from my own github on a Mac. https://github.com/shanegibney/djangoForum.git Since posting to github over a year ago I've moved to a mac from linux, Fedora. I've been following instructions from, How to run cloned Django project? $ mkdir djangoForum $ cd djangoForum $ virtualenv $ git clone https://github.com/shanegibney/djangoForum.git $ source env/bin/activate $ cd djangoForum $ pip install -r requirements.txt This is where I get the following error, The error is the same whether I use pip or pip3. $ pip --version pip 9.0.1 from /Users/shanegibney/djangoForum/env/lib/python3.6/site-packages (python 3.6) $ python --version Python 3.6.3 The requirements.txt file is here, https://github.com/shanegibney/djangoForum/blob/master/requirements.txt Can anyone see why I get the error when trying to install requirements.txt? Thanks, -
How to mock media file directory in django with custom storage property?
django version: 1.11, python version: 3.6.3 According to this two blogs/articles: https://joeray.me/mocking-files-and-file-storage-for-testing-django-models.html https://www.caktusgroup.com/blog/2013/06/26/media-root-and-django-tests/ we would, ideally, use a temporary directory to upload the mock-files. Now, mocking the files is easy. But mocking the directory and using a temporary directory is not working with custom storage property in settings.py i have a protected root to upload non public images: MEDIA_URL = '/media/' MEDIA_ROOT=os.path.join(BASE_DIR, "cdn", "media") PROTECTED_ROOT = os.path.join(BASE_DIR, "cdn", "protected") in products/models.py i have: from django.conf import settings from django.db import models from django.core.files.storage import FileSystemStorage class Product(models.Model): media = models.ImageField( # custom storage property storage=FileSystemStorage(location=settings.PROTECTED_ROOT) ) and the test in products/tests/test_views.py: from django.test import TestCase from unittest import mock from products.models import Product from django.core.files import File class ProductViewSetup(TestCase): @classmethod def setUpTestData(cls): file_mock = mock.MagicMock(spec=File, name='FileMock') file_mock.name = 'test.jpg' cls.product = Product.objects.create( media=file_mock ) i thought i could just customize the code described in caktusgroup blog to: class TempMediaMixin(object): "Mixin to create MEDIA_ROOT in temp and tear down when complete." def setup_test_environment(self): "Create temp directory and update MEDIA_ROOT and default storage." super(TempMediaMixin, self).setup_test_environment() settings._original_media_root = settings.MEDIA_ROOT settings._original_file_storage = settings.DEFAULT_FILE_STORAGE settings._original_protected_root = settings.PROTECTED_ROOT self._temp_media = tempfile.mkdtemp() self._temp_protected = tempfile.mkdtemp() settings.MEDIA_ROOT = self._temp_media settings.PROTECTED_ROOT = self._temp_protected settings.DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' def teardown_test_environment(self): "Delete … -
Django doesn't allow to add record to DB due to not table instance
I have a DB model: class building_list(models.Model): building_id = models.CharField(max_length=25, verbose_name="Building ID", unique=True) def __unicode__(self): return self.building_id class data(models.Model): oDate = models.DateField() building_id = models.ForeignKey( building_list, to_field = "building_id" ) content = models.CharField(max_length=25, verbose_name="Content") def __unicode__(self): return self.content There is no problem to add record via Admin Portal, I can choose building_id from SELECT list and everything is okay. But, there is a problem when I am trying to add record via view. Let me show you my code: url(r'^(?P<building_id>[\w-]+)/$', views.test, name='test'), def test( request, building_id ): if request.method == 'POST': oDate = request.POST.get('oDate', '') content = request.POST.get('content', '') row = data( oDate = oDate, building_id = building_id, content = content ) return True I see that Cannot assign "u'BrI9'": "data.building_id " must be a "building_list" instance. Can anyone explain what I am doing wrong ? -
Django database table missing columns
I am trying to implement my own custom token to have greater functionality with token-based authentication. I have created a custom token model in models.py, shown below. I followed this question and the rest_framework docs when creating it. Custom token: class ScrumScrumUserToken(models.Model): """A custom Token class. This implementation includes the client type for which the token is created. """ key = models.CharField(_("Key"), max_length=40, primary_key=True, default='0') user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='scrum_tokenr', on_delete=models.CASCADE, verbose_name=_("User"), default=-1 ) created_on = models.DateTimeField(_("Created"), auto_now=True) client = models.CharField(max_length=10) class Meta: verbose_name = _("Token") verbose_name_plural = _("Tokens") def save(self, *args, **kwargs): if not self.key: self.key = self.generate_key() return super(ScrumScrumUserToken, self).save(*args, **kwargs) def generate_key(self): return binascii.hexlify(os.urandom(20)).decode() def __str__(self): return self.key To show that all fields are in the migration: migrations.CreateModel( name='ScrumScrumUserToken', fields=[ ('key', models.CharField(default='0', max_length=40, primary_key=True, serialize=False, verbose_name='Key')), ('created_on', models.DateTimeField(auto_now=True, verbose_name='Created')), ('client', models.CharField(max_length=10)), ('user', models.OneToOneField(default=-1, on_delete=django.db.models.deletion.CASCADE, related_name='scrum_tokenr', to=settings.AUTH_USER_MODEL, verbose_name='User')), ], options={ 'verbose_name': 'Token', 'verbose_name_plural': 'Tokens', }, ) The problem: MariaDB [(none)]> desc scrum_scrum.scrum_scrum_api_scrumscrumusertoken\G *************************** 1. row *************************** Field: client Type: varchar(10) Null: NO Key: Default: NULL Extra: 1 row in set (0.00 sec) MariaDB [(none)]> As you can see, only the client field shows up in the database. For the life of me I cannot figure out why the … -
Django tests apis model object does not exist
I have created 2 Django models, User and Account Model. In User model, i have all info and in account part, i have account details of that user. I have designed Views that when I create a user, respective account object also created. URLs: '/user/' will create new user and account object. but when I am writing tests to check APIs, I created a new user. User object is accessible but when I access account detail it throws models.object doesn't exist. class User(models.Model): user_name = models.CharField(max_length=35) first_name = models.CharField(max_length=35) last_name = models.CharField(max_length=35) email = models.EmailField(max_length=255) class Account(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) balance = models.IntegerField(default = 0) def post(self, request): received_json_data = json.loads(request.body.decode("utf-8")) user = User(user_name=received_json_data['user_name'], first_name=received_json_data['first_name'], last_name=received_json_data['last_name'], email=received_json_data['email']) user.save() account = Account(user=user); account.save(); class TestUser(TestCase): def setUp(self): self.c = Client() usercreate = User(user_name = 'saveuser', first_name = 'usersave', last_name = 'lastsave',email = 'save@gmail.com') usercreate.save() account = Account.objects.get(pk =1) -
django dynamic create models
I am stucking on the django dynamic create models.I have no any experience and ideas to do this. I want to create models and fields by html forms, My problem is: Is there any example? I need to customize the database and fields, how to do it? Thanks! -
Django context processor doesn't display new context values in template
I'm using Django 1.11 and this is my first time trying to use a custom context processor. The problem is that the context variable I'm supposed to be adding from the context processor does not return anything in the template. I don't receive any errors. I know the context processor file is being executed from some testing. So below {{ testcontext }} should return "IT WORKED!", but returns nothing. Every question I've read on the subject has something to do with the RequestObject not being included in the response, but from what I've read generic class based views are supposed to include RequestObject by default. settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'appname.context_processors.test_context', ], }, }, ] context_processors.py: def test_context(request): return {'testcontext': 'TEST WORKED!'} views.py: from django.views.generic import ListView from appname.models import MyModel class MyView(ListView): model = MyModel urls.py from django.conf.urls import url from appname.views import MyView urlpatterns = [ url(r'^$', MyView.as_view(), name="home"), ] template.html {{ testcontext }} -
Organize the checkout page with steps
I have developed a checkout page where a form(guest form and login form) is shown at first if user is not authenticated. When user fills the form, then only the user is redirected to the same checkout page where now he will be shown a shipping address form which when filled will redirect to the same page but now billing address form is shown and after completing that steps, a review is shown.Instead I want to show the steps like Login > Shipping > Billing > Review How can i organize the form or content based on the steps they are in? Here is the checkout view with template def checkout(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.furnitures.count() == 0: return redirect('carts') login_form = LoginForm(request=request) guest_form = GuestForm(request=request) address_form = AddressCheckoutForm() guest_email_id = request.session.get('guest_email_id') billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) if billing_profile is not None: order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj) context = { "order": order_obj, "login_form": login_form, "guest_form": guest_form, "address_form": address_form, "billing_profile": billing_profile } return render(request, "carts/checkout.html", context) {% block content %} <div class="checkout_area section_padding_100"> <div class="container"> <div class="row"> {% if not billing_profile %} <div class="col-sm-12"> <div class="checkout_details_area checkout-1 mt-50 clearfix"> <div class="row"> {% comment %} <!-- {% … -
Why models delete method not getting called?
I have a mapping model, and i am deleting its objects but delete method not getting called: My mapping model is: class StudentSeasonCourseMap(models.Model): student = models.ForeignKey('ProgrammeStudentMap', db_column='student_id', related_name='studentseasoncourses', null=True, blank=True, verbose_name=_('Student'), limit_choices_to={'status': 'A'}) """ Student can be mapped to the ProgrammeStudentMap model """ season_course = models.ForeignKey('SeasonCourseMap', db_column='season_course_id', related_name='studentseasoncourses', null=True, blank=True, limit_choices_to={'status': 'A'}, verbose_name=_('Course')) def delete(self, *args, **kwargs): super(StudentSeasonCourseMap, self).delete(*args, **kwargs) my view's post method is: class StudentUpdate(View): def post(self, request): StudentSeasonCourseMap.objects.filter(id__in=[1,2]).delete() There is no admin for this model. still models delete method for bulk operation not getting called. Does anyone know why? -
Django CMS 3.4 apphooks not "hooking"
I am trying to follow the tutorial here just with my own "app". It's called currencies. cms_apps.py is inside currencies directory and apparently it gets called since I can see the CurrenciesHook in the CMS admin later. However the custom view class is not executed and/or template is not displayed. All I get is a blank page with Django's toolbar at the top and navigation (i.e. what's in base.html template). @apphook_pool.register class CurrenciesHook(CMSApp): name = _("Currencies application") app_name = "currencies" def get_urls(self, page=None, language=None, **kwargs): return ["currencies.urls"] urls.py is also inside currencies dir: urlpatterns = i18n_patterns( url(r'^$', views.DesktopView.as_view(), name="desktop"), ) views.py in the currencies dir has a single class for testing: class DesktopView(generic.TemplateView): template_name = 'desktop.html' and finally template desktop.html inside currencies/templates is simply: {% extends "base.html" %} TEST The command line displays no errors. If you can't tell what may possibly be wrong from the info provided, I'd appreciate any suggestions how to debug this. I'm very new to Django and I last worked with python 5 years ago. -
Django many-to-many through query simplification?
I have a Project, User and a many-to-many through table called ProjectMembership: class Project(models.Model): '''Project model ''' name = models.CharField(max_length=255, unique=True) users = models.ManyToManyField( settings.AUTH_USER_MODEL, through='ProjectMembership' ) is_active = models.BooleanField( default=True, ) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) is_active = models.BooleanField( default=True, ) projects = models.ManyToManyField( Project, through=ProjectMembership ) class ProjectMembership(models.Model): '''Project Membership model ''' user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT ) project = models.ForeignKey(Project, on_delete=models.PROTECT) is_project_manager = models.BooleanField(default=False) Now I want a list of all the active project managers on all the active projects that a specific user is on. I have used the following query and loops below, but perhaps there is a way to do this without the loops? projects = self.leave_not_required_user.projects.filter(is_active=True) users = [] for project in projects: project_memberships = project.projectmembership_set.filter( is_project_manager=True, user__is_active=True ).all() for project_membership in project_memberships: users.append(project_membership.user) -
is django db able to have a secondary db set as back up? django
What I am trying to say is, I have two database and they are replicates. Is it possible for django to have settings that if first (primary db) is down / cannot be connected then connect to the second one until the first one is back up? I believe this can be done in server side, but I am wondering if it can be done with django easily instead of touching the db servers? -
Aligning text when converting from html to pdf in django
After following a tutorial, I successfully was able to convert html to pdf, however, when trying to align text on the same line (half of it to the left and the other half to the right) it would not convert properly. The html file looks as follow: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Title</title> <style type="text/css"> body { font-weight: 200; font-size: 14px; } .header { font-size: 20px; font-weight: 100; text-align: center; color: #007cae; } .title { font-size: 22px; font-weight: 100; padding: 10px 20px 0px 20px; } .title span { color: #007cae; } .details { padding: 10px 20px 0px 20px; text-align: left } .hrItem { border: none; height: 1px; color: #333; background-color: #fff; } </style> </head> <body> <div class='wrapper'> <div class='header'> <p class='title'>Invoice # </p> </div> <div> <div class='details'> Bill to: <span style="float:right">some text here</span> <br/> Amount: <br/> Date: <hr class='hrItem' /> </div> </div> </body> </html> The render_to_pdf function: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None The html file looks more than proper, but is not being converted properly in pdf. Aligning on separate lines does,however, convert normally to pdf … -
Running supervisord in AWS Environment
I'm working on adding Django Channels on my elastic beanstalk enviorment, but running into trouble configuring supervisord. Specifically, in /.ebextensions I have a file channels.config with this code: container_commands: 01_copy_supervisord_conf: command: "cp .ebextensions/supervisord/supervisord.conf /opt/python/etc/supervisord.conf" 02_reload_supervisord: command: "supervisorctl -c /opt/python/etc/supervisord.conf reload" This errors on the 2nd command with the following error message, through the elastic beanstalk CLI: Command failed on instance. Return code: 1 Output: error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /opt/python/run/venv/local/lib/python3.4/site- packages/supervisor/xmlrpc.py line: 562. container_command 02_reload_supervisord in .ebextensions/channels.config failed. My guess would be supervisor didn't install correctly, but because command 1 copies the files without an error, that leads me to think supervisor is indeed installed and I have an issue with the container command. Has anyone implemented supervisor in an AWS environment and can see where I'm going wrong? -
How to retrieve form data using AJAX in django
I know to save the form in Django using AJAX but don't know how to retrieve the form data from Django using AJAX. I need to retrieve the form data through return HttpResponse(jhjson, {'content_type' : 'application/json'}) instead of return render(request, 'task/mobileInventory.html', {'form': form}) View.py def get_try(request, sid): print (sid) member = get_object_or_404(TaskMaster, pk=sid) form = CreateTaskMaster(instance=member) return render(request, 'task/mobileInventory.html', {'form': form}) -
How to handle a js request that sends json data to django?
I basically want to implement a simple Form along with js in django. So for that a js request is been sent along with json data containing info from the form filled by the user but I am not able to parse the received json and am getting the following error - Error Traceback - http://dpaste.com/38NXD77 Any help would be appreciated. Thanking you in advance :) script.js function submit_add_participant() { // Retrieve Form Data here var formData = serializeArray(document.getElementById('add-participant-form')); add_name = formData[0].value; add_clgname = formData[1].value; add_sport = formData[5].value; add_city = formData[2].value; add_email = formData[4].value; add_mobile = formData[3].value; var add_gender = ''; if (formData.length > 6) { add_gender = formData[6].value; } if (add_name && add_clgname && add_sport && add_city && add_email && add_mobile && add_gender) { document.getElementById('add-participant-err-msg').style.display = 'none'; // Send Data to Backend // alert('Send'); newParticipant["data"].push({ "name": add_name, "gender": add_gender, "college": add_clgname, "sport": add_sport, "city": add_city, "email": add_email, "mobile": add_mobile }); // var csrf_token = getCSRFToken(); csrf_token = getCookie('csrftoken'); newParticipant["csrftoken"].push({ "csrfmiddlewaretoken": csrf_token }); alert(JSON.stringify(newParticipant)); var ourRequest = new XMLHttpRequest(); var url = "/add_participant/"; ourRequest.open("POST", url, true); ourRequest.setRequestHeader("Content-type", "application/json"); ourRequest.setRequestHeader("X-CSRFToken", csrf_token); // POST var sendParticipant = JSON.stringify(newParticipant); // alert(sendParticipant); // alert(data); ourRequest.send(sendParticipant); footer_display(5); // Obtain ourRequest.onreadystatechange = function() { // alert('Hello'); … -
Django: Message App
I'm trying to create a messaging app. Everything is working fine accept the fact I couldn't re-order users if request.user sends a message or vice versa. Here's what I tried, Here's the model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) Here's what I tried in view to filter the User if conversation between any user & request.user occurred, def profiles(request): users = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('receiver__first_name', 'receiver__id').annotate(Max('id')).order_by('-id__max') return render(request, 'chat/users.html', {'users': users}) Here's the template, {% for user in users %} <a href="{% url 'chat:messages' user.receiver__id %}">{{ user.receiver__first_name }}</a> {% endfor %} Here I can filter out the users but problem is either I can filter the senders or receivers not both of them depending upon the conversation as we see on social networks. How can I do that? -
I am not able to render existing Django App's in Mezzanine CMS?
Check the code there is main urls.py and there is one more urls.py for the app about us with the code views.py check out this, I am not able to render django app's in mezzanine cms, what I am missing. :- [About us- urls][1] [about us- views][2] [1]: https://i.stack.imgur.com/S3wQS.png [2]: https://i.stack.imgur.com/fEA09.png #URLS.py from __future__ import unicode_literals import mezzanine from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.views.i18n import set_language from aboutus import views from home import views from mezzanine.core.views import direct_to_template from mezzanine.conf import settings admin.autodiscover() # Add the urlpatterns for any custom Django applications here. # You can also change the ``home`` view to add your own functionality # to the project's homepage. urlpatterns = i18n_patterns( # Change the admin prefix here to use an alternate URL for the # admin interface, which would be marginally more secure. url("^admin/", include(admin.site.urls)), ) if settings.USE_MODELTRANSLATION: urlpatterns += [ url('^i18n/$', set_language, name='set_language'), ] urlpatterns += [ # We don't want to presume how your homepage works, so here are a # few patterns you can use to set it up. # HOMEPAGE AS STATIC TEMPLATE # --------------------------- # This pattern simply loads the index.html template. It … -
How to Upload file from ajax to django rest api?
I want to upload file via ajax to api but i couldn't get file url while fetching the file from ajax. Please look at the code below and give me a solution code for ajax call : $(document).ready(function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $(".add-content").submit(function(event){ event.preventDefault() var this_ = $(this) console.log(this_); var form = this_.serializeArray() // $.each(form, function(key, value){ // // }) var formData = this_.serialize() console.log(form); var fileSelect = document.getElementById('file'); console.log(fileSelect.value); var temp= { "content_name": form[1].value, "content_url": fileSelect.files[0], "employee": {{ id }}, "course": form[2].value } console.log(JSON.stringify(temp)); $.ajax({ url: "/api/content/create", data: JSON.stringify(temp), beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, method: "POST", contentType: "application/json; charset=utf-8", dataType: 'json', success: function(data){ console.log(data) }, error: function(data){ console.log("error") console.log(data.statusText) console.log(data.status) } … -
Django DateTimeField date filter not working
I have a DateTimeField named created_at in my model. I Would like to query the objects which are created today. From this question I have used the following query set, In [70]: today = datetime.datetime.today().date() In [72]: Business.objects.filter(created_at__date=today) Out[72]: <QuerySet []> It returns zero results. I have make sure that there is an entry in the database, which was created today. I know that I can also use Business.objects.filter(created_at__contains=today) But it yields results with a warning: django/db/backends/mysql/base.py:71: Warning: (1292, "Incorrect datetime value: '%2017-12-21%' for column 'created_at' at row 1") I'm using MySQL database. -
NoReverseMatch in Django 1.11
I know there are lot of questions already ask about this error but for some reason none of them work for me. What i am trying to do? I am trying to pass a variable from view ActivateAccount to another view result upon email confirmation. What is the problem? I am doing everything right according to docs and previously posted question about the same error but i still get this error: Reverse for 'result' with keyword arguments '{'test': 'Email confirmed successfully!'}' not found. 1 pattern(s) tried: ['(?P<test>[\\w-]+)/$'] caller view.py: def ActivateAccount(request, uidb64, token): test = '' if uidb64 is not None and token is not None: ... test = "Email confirmed successfully!" return HttpResponseRedirect(reverse('result', kwargs={'test': test})) urls.py: url(r'^(?P<test>[\w-]+)/$', views.result, name='result') receiver view.py: def result(request, test=None, *args, **kargs): data = {'msg': test} return JsonResponse(data) And i would also like to know why is there double backslash \\ in the regex ([\\w-]) instead of single in the error. As in my url i have a single \ ([\w-]). thanks for your time. -
How to go to a specific external URL from your API using Django?
I being new to Django is learning how to go to an external URL from my API, so I made a project and in that project made an app like 'linker' and in the views of app I wrote this code 1 # -*- coding: utf-8 -*- 2 from __future__ import unicode_literals 3 import urllib3 4 from django.shortcuts import render 5 from django.http import HttpResponse 6 # Create your views here. 7 8 def index(request): 9 http = urllib3.PoolManager() 10 r = http.request('GET', 'www.google.com') 11 return HttpResponse(r) Now this is the views.py, is the code right? -
Error when install psycopg2 on mac
When i try to install psycopg2 on mac using pip install -r requirements.txt I got error. Collecting psycopg2==2.6 (from -r requirements.txt (line 30)) Using cached psycopg2-2.6.tar.gz Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/psycopg2.egg-info writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: could not determine PostgreSQL version from '10.1' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/r6/0rwq93rx6n59lbn8jrng11gm0000gn/T/pip-build-hat1f3jy/psycopg2/ I could not solve it.python3.4.3 mac10.12 could anyone suggest any solution? -
Custom the `on_delete` param function in Django model fields
I have a IPv4Manage model, in it I have a vlanedipv4network field: class IPv4Manage(models.Model): ... vlanedipv4network = models.ForeignKey( to=VlanedIPv4Network, related_name="ipv4s", on_delete=models.xxx, null=True) As we know, on the on_delete param, we general fill the models.xxx, such as models.CASCADE. Is it possible to custom a function, to fill there? I want to do other logic things there.