Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ajax Post does not work properly
Hello guys I'm trying to pass a variable from jquery to the views trying it returns in the DOM the value but it does not work for me. I need a hand. This is the html file. <!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> </head> <body> <script type="text/javascript"> $(function() { $(document).on('submit', '#fomulario', function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'http://127.0.0.1:8000/form_ajax/', data:{ nombre:$('#nombre').val(), 'csrfmiddlewaretoken':'{% csrf_token %}', }, sucess:function(data){ $('#valor').html(data); } }); }) }); </script> </body> <form id="fomulario"> {% csrf_token %} <label for="Nombre">Nombre</label> <input type="text" id="nombre"> <input type="submit"> </form> <div id="valor"></div> </html> Views. def form(request): return render_to_response('prueba2.html') def form_ajax(request): if request.is_ajax() and request.method == 'POST': nombre = request.POST['nombre'] HttpResponse(nombre) # message = "This is ajax" else: message = "Not ajax" return HttpResponse(message) What am I doing bad ? Thank you guys. -
Inspect a request when using testing Django rest_framework
I have a test failing in my Django rest_framework project, claiming no authentication credentials were provided, when I'm fairly certain they were. In order to really determine, I'd like to see the actual raw request being produced. Is there a way to inspect the request itself to be sure it is constructed as expected? -
Django viewable or clickable filepath field
I'm a little new to the inter-workings of Django and I would like to display a simple dynamic folder path field that opens to the given path when clicked so a user can view all the files in that path. I'm trying to do this in django admin site change form but am unclear and confused of how to do so. Below is my model. class Order(models.Model): order_number = models.IntegerField(verbose_name='LS #', unique=True) order_name = models.ForeignKey(recs.RecipeControl, related_name='recipe') # Something like this is I think what I want. folder_path = models.FilePathField(path=get_path) def get_path(self): return str(self.order_number)+"_"+self.order_name I'm puzzled as how to properly go about this because I can't seem to reference "self" to do this, especially if the record doesn't already exist. I've looked at a few other Q&A's but none of them dealt with the admin site and after a bit of reading I'm convinced that I may have to override one of the save methods but don't understand which one and where to place my method. Thanks in advanced. -
Django - MPTT - Can I use the same "category name" under different parents?
I can't seem to find a way to use the same category name under a different parent. For example I want to list "asus" brand as a sub category under both the "laptop" and the "desktop" categories but it seems to be not possible. Django is asking me to use a different name saying this "asus" category already exists. I looked at the table structure of mpttcategory table and category name is not a unique identifier. I found this SO questio, but I am not trying to assign 2 parents to the same child. I am trying to create 2 seperate childs with the same category name connected to different parent categories. Plus, that one is an old question.. Anyways, there must be a way to achieve this, right? -
Unable to copy files from pscp to ubuntu - persmission denied
I am a newbie in Linux administration. I deleted my Django project directory from the remote Ubuntu server. The project was located here: /usr/local/lib/python2.7/dist-packages/django/my_proj So I removed my_proj doing rm -rf my_proj, and then I re-created my_proj doing sudo mkdir my_proj. Then I go back to my local Windows putty app, and run the following command: pscp -r C:\Users\workspace\my_proj my_username@remove_server_url:/usr/local/lib/python2.7/dist-packages/django/my_proj I get permission denied to create folder error for every file and directory inside my_proj. I tried to run chmod command in Ubuntu, something like sudo chmod -R 777 /usr/local/lib/python2.7/dist-packages/django/my_proj/ ...but get strange error: sudo /usr/bin/sudo must be owned by uid 0 and have the setuid bit set -
How to render form input on same page as form in django
I'm new to using Python/Django, but I'm having a lot of issues printing the input of my form onto the bottom of the page that it's on. Ideally I would want it to output something like this (the text underneath Repairs Entered): enter image description here This would create an ongoing list of all repairs entered into the form. So far this is my code I've been working on, however I can't find very many up to date resources or examples for what I'm trying to accomplish. forms.py from django import forms from .models import RepairEntry #Database tuples defining the dropdown list options. DISTRICT = ( ('HA', 'Hamilton'), ('HL', 'Holland'), ('OA', 'Ottawa'), ('OP', 'Oakridge'), ('SL', 'SpringLake'), ('SA', 'Saugatuck'), ) CBMODEL = ( ('DELL1', 'Dell 11 Gen 1'), ('DELL2', 'Dell 11 Gen 2'), ('LENO1', 'Lenovo x131'), ('LENO2', 'Lenovo 11e'), ('ACER1', 'Acer C720'), ('ACER2', 'Acer CB5-311'), ('SAMS1', 'Samsung XE303C12'), ) CBPART = ( ('LCD', 'LCD Panel'), ('KEYB', 'Keyboard'), ('PALM', 'Palmrest'), ('BOTC', 'Bottom Case'), ) class RepairEntryForm(forms.ModelForm) : error_css_class = 'error' district = forms.ChoiceField(choices=DISTRICT, required=True) cbmodel = forms.ChoiceField(choices=CBMODEL, required=True) cbpart = forms.ChoiceField(choices=CBPART, required=True) class Meta: model = RepairEntry widgets = { 'kace': forms.TextInput(attrs={'placeholder': 'Enter KACE Ticket #'}), } fields = ('kace', 'district', 'cbmodel', … -
Django Session Wizard going to prev step on submit
I am trying to use django SessionWizard view for the forms. When I am clicking on submit, the form goes back to first step. I tested it using CookieWizardView and the form works fine with that. For SessionWizardView, I verified that sessions are enables in my application as per documentation here - Also verified that sessions table in my db and is non-empty. Have seen related questions, but not to much help. Below is the code snippet of my view class UploadWizard(SessionWizardView): def __init__(self, *args, **kwargs): super(UploadWizard, self).__init__(*args, **kwargs) self.uploaded_file = None self.ingestable_upload = None self.error = None form_list = UPLOAD_FORMS # TODO: sweep for old files. Maybe move to S3? upload_dir = os.path.join(settings.MEDIA_ROOT, 'uploads') file_storage = FileSystemStorage(location=upload_dir) def get_template_names(self): return [TEMPLATES[self.steps.current]] def get_form(self, step=None, data=None, files=None): if step is None: step = self.steps.current form = super(UploadBoxofficeWizard, self).get_form(step, data, files) if step == MAP_DATA_STEP: # do something return form def process_step(self, form): if self.steps.current == PICK_FILE_STEP: action = form.cleaned_data.get('action') extractor = get_upload_extractor_for_source(form.cleaned_data.get('source')) uploaded_file = form.cleaned_data.get('file') start_date = form.cleaned_data.get('start_date') end_date = form.cleaned_data.get('end_date') if action == INGEST_ACTION: #do something elif self.steps.current == MAP_DATA_STEP: # do something def done(self, form_list, form_dict, **kwargs): form = form_list[int(MAP_DATA_STEP)] num_rows= 0 if form: num_rows = form.cleaned_data[0].get('num_rows') return … -
Remove "?id=" from dynamic URLs
I'm pretty new to django and i'm working on a website that needs a dynamic URL for a database table, and it all works fine, but i would like to know how to remove the "?id=" from the url, so rather than localhost:8000/dynamicurl/?id=XXXXX The url becomes localhost:8000/dynamicurl/XXXXX Instead I did a fine amount of searching in the documentation and didn't find a lot, though it's pretty likely i missed something. -
How to run two different python version in single Django project?
Currently i am working on django project with python 3.5 and Django 1.9.2. I want to integrated one app(Module) which was build with python 2.7 and Django 1.4 from different django project in my latest project.Can i run two different app with different python and Django in single Django project. -
Merging 2 Django projects
I'm trying to merge one Django project into another one but am having difficulties. My core and Tab A were the original and then I'm trying to port over Tab B with templates folder into my core. I changed the settings.py and urls.py within the core but when loading the page I still get an error of template not found. Is there something I am missing? thank you. Both of these websites work independently 100% I just removed the managed.py within tab B because there would have been a merge conflict and just added the contents within it into core.manage.py. core manage.py core settings.py urls.py wsgi.py Tab A apps.py admin.py forms.py models.py tests.py urls.py views.py Tab B templates main.html apps.py admin.py models.py tests.py urls.py views.py templates base.html -
Best Python Web Framework for Internal Intranet Tool [on hold]
I've built a small program in Python utilizing Doc-X to output data entered in an Excel Spreadsheet along with a few input fields from the Python file out to a Word Document. I am able to execute the file flawlessly on my PC, but I would like to share this tool with several of my colleagues with no understanding of Python. I have been learning about Django of late, but I'm curious if this would be my best option for this task. I would like to just create a simple HTML page locally that my co-workers can visit and run to generate the Word Doc on their PC. I've also come across Python's internal HTTP server but not sure if this would be the best solution. I am still learning about Python so sorry if this is a dumb question, but would like help directing me to the best overall solution for my project. Thanks! -
Getting a JSON Response from the Django
I'm new to Django, and I'm trying to get the server to send a response to the same page, with a certain number. It's currently responding with a ValueError, and the template doesn't get the response. Here is my code. views.py def index(request): dB = LegacyDatabase() ints = None if request.POST: form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): files = Upload(model=request.FILES['file_upload']) try: ints = dBconnection(dB, request.FILES['file_upload'].name) except IntegrityError: ints = dBGetExistingValue(dB, request.FILES['file_upload'].name) files.save() a = [] a.append(["sessionid", ints]) sess= dict(a) return JsonResponse(sess, safe = False) return render(request, "main/index.html") urls.py from django.conf.urls import url from phast.views import index urlpatterns = [ url(r'^$', index, name='main'), ] index.html <form method="post" class = "sessionid"> <input type="text" id = "demo" readonly> </form> <script> var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(JSON.parse(xhttp.responseText)); } }; </script> Can you please help me? -
Malformed Set-Cookie headers in Django 1.9.10
My team is running into an old Django bug that seems to have come back from the dead. Here’s the original ticket from Django, closed 5 years ago: https://code.djangoproject.com/ticket/15863. We’re very occasionally seeing malformed Set-Cookie headers on responses from our application server, as described in the linked ticket. Rather than the expected format for a Set-Cookie header, something like: Set-Cookie: cookiename=XX; Max-Age: YY; Path=/ We’re instead seeing the whole header inserted as the cookie value, something like: Set-Cookie: cookiename="Set-Cookie: cookiename=XX Max-Age: YY; Path=/" This a total poison pill for users when it happens to the sessionid or csrftoken cookies: when they are sent from the server, the client browser sets these cookies to malformed values and subsequent authenticated or CSRF-protected requests fail until the user manually clears their cookies. This bug has been difficult to replicate, and I'm not entirely sure where to start looking. The ticket above describes exactly the behavior we’re seeing, but 1) it was closed and fixed 5 years ago and 2) We’re not using the file or DB cache backends—we use Redis as our cache backend. Python 3.43, Django 1.9.10. Session middleware, CSRF middleware, and cache middleware are all enabled. -
Django multilingual with pages in one language disabling switch
I am developing a website using Django Mezzanine. I have some 'static pages' translatable and this works. However I have some page relative to some events in given countries, so they are only in one language. I made special page to list and filter them, and a view only for them. In the list I tried to put links including the language of the page (like /en/events/event/eventslug ). I tried to add translation.activate(lang_code) to the view. This way I get the page in the wanted language. The problem comes when I visit the page from another language (for exemple if I am on the filter page in Spanish and go to an English event). Then the language switch (mezzanine form sending a POST request to /i18n/) doesn't work any more (I am locked in English) The switch still work in private navigation for example as long as I don't visit one of this pages from another language. How can I fix this? I am out of ideas as of why... -
Employing django management commands to do real time processing
In my application, I need to do real time processing during specific hours of the day, with my current solution, I plan to use django management commands. So it will go like this, A script will start my server, as well as the management command I write. call_command('runserver') call_command('daemon_doll') Now, the daemon_doll command will keep looping a while, which will check the current time, if it's in the specific range, it calls another module. while True: if current.hour == 9 and current.minute > 30: ModuleA.startProcessing() The function startProcessing() will itself have another loop, which will keep fetching some data from external services, perform some calculations over it, and keep the data in the cache(currently I'm using a MySQL table as cache), after every calculation, the new data would be replaced by the stale one in the cache. This will keep going on until the loop has ran for specific number of hours. class ModuleA(object): def startProcessing(self): while True: if current.hour == 14 and current.minute > 10: break # Fetch data # Do some calculations # put it in table sleep(1000) return The data in the cache, would be returned to each client requests (Android app) in JSON format. Regarding the … -
selenium scraping javascript
I'm planning on making a website that scrapes a lot of daily updated URLS (JavaScript) from many websites. I did some research and found selenium, already made some code to extract a URL from a website from selenium import webdriver chrome_path = r"C:\Users\hessien\Desktop\chromedriver_win32\chromedriver.exe" driver = webdriver.Chrome(chrome_path) driver.get("http://example.com") driver.find_element_by_xpath("""//*[@id="header"]/div/div[2]/div[3]/ul/li/label/a""").click() element = driver.find_element_by_xpath("""//*[@id="s"]""") element.send_keys("example") driver.find_element_by_xpath("""//*[@id="searchform"]/button/span""").click() driver.find_element_by_xpath("""//*[@id="contenedor"]/div/div[2]/div[1]/div[2]/article/div[2]/div[1]/a""").click() driver.find_element_by_xpath("""//*[@id="playex"]/div[1]""").click() elem = driver.find_element_by_xpath("""//*[@id="mediaplayer_media"]/video""").get_attribute("src"); print elem but after some searches I found out that selenium mainly used as a testing framework not for scraping and crawling!.. my question is can selenium do the work? if yes, how to execute the python code in an HTML button? I'm also using Django. if no, could you recommend anything that can do the task? -
Django 1.10 order_by() FieldError
With the below classes, I would like to be able select all related data for all "Ship_Back" objects and sort them by the "Ring" first, and the "Ppack" second. When trying to order my queryset based on what I think the documentation is saying, and other posts I've read from previous versions of Django, I'm getting a FieldError. I tried simplifying it to just sort on the "Ppack" related table, but that's not working either. Models: class Ring(models.Model): ring = models.IntegerField() class Ppack(models.Model): ppack = models.IntegerField() ring = models.ForeignKey('Ring', on_delete=models.CASCADE) class Ship_Back(models.Model): ring_name = models.CharField(max_length = 20) release = models.ForeignKey('Ppack', on_delete=models.CASCADE) Views: def index(request): ship_back = Ship_Back.objects.all().order_by('Ppack__ppack') This yields the following error: FieldError at / Cannot resolve keyword 'Ppack' into field. Choices are: id, release, release_id, ring_name -
How to unregister third-party app models from Django admin
Is it possible to unregister models from Django admin (allauth) outside admin.py file? The problem is that the only app I could use to unregister those models can't be switched in settings.py with allauth apps, because it has some dependencies. The only thing I figured out is to create a new app ("unreg_app") so I can put it at the bottom of INSTALLED_APPS and add admin.site.unregister(SocialApp) admin.site.unregister(SocialToken) admin.site.unregister(SocialAccount) etc. to its admin.py file. But it doesn't seem like a best way. Do you have any ideas? -
Verify login with Django rest API and react native front end
I am working on building a react native app with a django rest framework backend. I have created the registration ViewSet and have been able to successfully register a user from the front end using the following: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSeralizer I have created another ViewSet to verify the email and password of the user as follows: class LoginViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = LoginSeralizer @detail_route(['POST']) def login_user(self,request, pk=None): if request.method == "POST": email = request.POST.get("email", False) password = request.POST.get("password", False) user = authenticate(email=email, password=password) if user is not None: if user.is_active: return Response(user.data, status=status.HTTP_200_OK) else: return Response(user.error, status=status.HTTP_400_BAD_REQUEST) else: return Response(user.error, status=status.HTTP_400_BAD_REQUEST) The detail_route method is not being called when I try to access the url from the front end. I get a bad response 400 error saying that the user has already been created. Am I on the right track? What changes do I make to the detail_route method so it would be called from the front end when the url is passed into the fetch method of the react native app? The rest of the files in the django project are as follows: The url.py: from django.contrib import admin from django.conf.urls import url, … -
Not able to see converte excel to HTML through Django
I have converted on Excel(with 2 tabs) to HTML. Now I want to display this generated HTML on a webpage with Django code. But I am not able to get the entire data in my webpage. Following is my django code. @api_view(['GET']) def download_y9cfile1(request, file_name): filePath = CommonUtils.get_absolute_file_path('app','static','generated','HTML', file_name) logger.debug("File name is %s" % filePath ) try: relevantFile = open(filePath,'rb') response = HttpResponse((relevantFile), content_type='text/html') response['Content-Disposition'] = 'inline; filename="%s"' %file_name except IOError: logger.exception("File doesn't exist") return HttpResponse("File doesn't exist", status=500) return response Can anybody please help me out?? I think the issue is that django is not able to read the supporting CSS file for HTML. Thanks.. -
Show result of js function call in django template
I have simple part of django template (simplified for readability) that executes js function to calculate the result (say, result is 100): <script> function calculate() { //do calculation alert(result); //works fine: shows dialog box with "100". return result; } </script> <p>Result: <script>calculate()</script>.</p> So i expect to see "Result:100." on the rendered page, but see only "Result:.". So the "calculate" function is executed and works fine (alert shows "100") but the result of its execution isn't displayed at the html page rendered from template. Why? I guess I misunderstand some basics about page loading :( -
how to make allauth accept only gmail addresses belonging to a certain institute?
Example qwe123@pilani.bits-pilani.ac.in I think i just need to check if the "template ending" is present in the email address or not but the problem is where to check it in the allauth package -
Django form __init__ method appears to be called twice
On one of my Django webpages, I am displaying an icon for each instance of a particular model (Meeting) in the database (one icon per instance of the model). When the user clicks one of the icons, a form is displayed elsewhere on the page to allow the user, to enter details about that particular instance of the model. Once they have entered all of the details for the fields fields on the form, they can press an 'Upload' button to upload the information entered to the database (and save the information to that instance of the model). When the form is submitted, the page will refresh, displaying an icon for each instance of a particular model. If the user clicks an existing icon, and makes a change to any of the fields on its form, and clicks 'Upload', a new instance of that model is created with the form populated with those amended fields. Each click to the 'Upload' button should create one more instance of the Meeting model in the database. Each of the fields on the form represent one of the Meeting model's attributes. I have two buttons on the form, for attaching image files to the … -
install gdal on eb create/deploy failing
I'm trying to get my Django app live through AWS EB but when I follow the steps shown on the tutorial, http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html, it keeps giving me an error saying "your requirements.txt is invalid." I think I'm getting error when it's trying to install GDAL 2.1.0 I have on requirements.txt here are some of the config files I have: project.config option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "hungryboat.settings" PYTHONPATH: "/opt/python/current/app/src:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: "hungryboat/wsgi.py" command: 01_pip_update: command:"pip install --upgrade pip" packages.config packages: yum: git: [] libtiff-devel: [] libjpeg-turbo-devel: [] libzip-devel: [] freetype-devel: [] postgresql95-devel: [] geos: [] libmemcached: [] libmemcached-devel: [] cyrus-sasl-devel: [] zlib-devel: [] command: 01_gdal: command:"yum --enablerepo=epel -y install gdal" and the error message/log I get: Traceback (most recent call last): File "/tmp/pip-build-zju5440p/GDAL/setup.py", line 118, in fetch_config p = subprocess.Popen([command, args], stdout=subprocess.PIPE) File "/usr/lib64/python3.4/subprocess.py", line 859, in __init__ restore_signals, start_new_session) File "/usr/lib64/python3.4/subprocess.py", line 1457, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: '../../apps/gdal-config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/pip-build-zju5440p/GDAL/setup.py", line 166, in get_gdal_config return fetch_config(option, gdal_config = self.gdal_config) File "/tmp/pip-build-zju5440p/GDAL/setup.py", line 122, in fetch_config raise gdal_config_error(e) __main__.gdal_config_error: [Errno 2] No such file or directory: '../../apps/gdal-config' During handling of the … -
Translation in Tastypie prepended-url
I have a Tastypie Resource (with no model behind it) that exposes a bunch of prepend_url()s to perform various functions. I also use Django translation on the entire resource, and messages get translated in the user's language of choice except for when they occur in a prepended endpoint. For example, if I have: def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/recipes%s" % (self._meta.resource_name, trailing_slash()), self.wrap_view('recipes'), name="baking_recipes") ] And there is an error that I need to return in the PATCH to resource_name/baking_recipes/ endpoint, that error does not get translated as expected. However, if I return an error in the PATCH to resource_name/ endpoint, the error is translated. The following is what I use to return the error: return self.create_response(request, {"error": translated_error}, response_class=http_response_class) This same return statement works beautifully when returning from the PATCH to the resource, but not when prepended urls are in question. Anyone have any pointers as to why? Thanks!