Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent URLconf settings from being carried onto new project?
I recently worked on a project that had an app named 'catalog'. While I was working on it, I changed the URLconf so that the root URL could be redirected to the app. I wrote the below code to do this: # within the project's URLconf file from django.views.generic import RedirectView urlpatterns += [ url(r'^$', RedirectView.as_view(url='/catalog/', permanent=True)), ] I was working on the local development server, and the root URL (127.0.0.1:8000) was successfully redirected to the 'catalog' app (127.0.0.1:8000/catalog/). However, when I created a new project, the root URL of this NEW project ALSO tried to redirect to the 'catalog' app of the previous project. So where as I should be seeing the "it worked!" page at the root URL for the new project, I am instead redirected to the 'catalog' app's URL of the previous project, where the 404 page is displayed (obviously, because the 'catalog' app is not part of the new project). Instead of this: It Worked Page Seeing this: 404 Page It seems to me that the settings from the previous project have somehow affected the local server permanently so that the modified URLconf setting is carried on to any subsequent projects. I could not find … -
RequestError: TransportError(400, {u'line': 1, u'root_cause': [{u'reason': u'no [query] registered for [filtered]
I am using Elasticsearch as backend for haystack in my Django project. I have gone through the Haystack official document and various other sites, But when i search it throws a traceback error with TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]'). I also downgraded the elasticsearch backend version to 1. But the errors remains same: raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) RequestError: TransportError(400, {u'line': 1, u'root_cause': [{u'reason': u'no [query] registered for [filtered]', u'type': u'parsing_exception', u'line': 1, u'col': 24}], u'type': u'parsing_exception', u'reason': u'no [query] registered for [filtered]', u'col': 24}) -
Why is page reloaded when button is clicked even if I don't use JavaScript?
I'm making a Django application. I have a <button> in html. When I click this, page is reloaded. I don't use JavaScript. Why is page reloaded? -
how to generate token using username and pin field in django auth toolkit for a phone app while keeping username and password for the web application?
I am using DRF with auth toolkit and it is working fine. However, I want to have a second login api so a user can log in using username and pin number. It is cos we have a USSD application and it is easier to give them a pin based login system. Currently, I have the following URL that, when called, generates token: url(r'^signin/', include('oauth2_provider.urls', namespace='oauth2_provider')), For the ussd app, I want something like that but the auth2 should check pin field, defined in a separate model defined as follows: class Members(models.Model): pin=models.IntegerField() user=models.ForeignKey(User) I am a little lost where to start. -
how to make approvals in django 1.10
I'm creating a website in django where users can upload post but the post would not be save to the website database unless it is approved by the site admin, and I don't know how to implement this please can somebody help me out -
Python regex search and replace all ocurrences
I hope you can help me with this, I'm writing a code in python to replace all occurences on a string that includes: @[username](user: id) I tried with the following code, but only works if my string is something like this: mystring = '@[otheruser](id: 100)' and match and replace it's ok. But if I pass a string like this: mystring = 'He is @[otheruser](id: 100) and he is @[newuser](id: 20)' doesn't work, nothing gets replaced. Code: import re mystring = 'He is @[otheruser](id: 100) and he is @[newuser](id: 20)' regex = re.compile(r'^@\[([a-zA-Z0-9]+)\]\((id: ([0-9]+))\)', re.S) iter = re.finditer(regex, mystring) for result in iter: match = result.group() g1 = result.group(1) g2 = result.group(2) g3 = result.group(3) print(match) # full match print(g1) # otheruser print(g2) # id: number_id print(g3) # number_id parsed_string = re.sub(p, '<a href="view/'+g3+'">@'+g1+'</a>' , mystring) Output should be something like: He is <a href="view/100">@otheruser</a> and he is <a href="view/20">@newuser</a> doesn't work, nothing gets replaced. -
Gitpython check repo cloned
I am working with Django Rest Framework, build some functionality interacts with git repository. I am using gitpython. Now, I used clone_from to clone remote repository. repo = Repo.clone_from("REMOTE_REPOSITORY", "LOCAL_PATH") But sometimes it fails with some network connection problems. How can I know repo is cloned or not? -
Ajax POST file upload in django
I'm trying to process a POST request with a file field via Ajax post in my djano app. I'm getting this error: Forbidden (CSRF token missing or incorrect.): /user/instance/create/new/awod/ Here's what I have tried: From template.html <div class="container" style="background-color: lightgray; opacity: 0.7;margin-top:10%;margin-left: 2%; padding-bottom: 10%;"> <form method="post" class="form-horizontal" action="" id="gitForm" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label class="control-label" for="inputGroupSuccess1">Deployment Name:</label> <div class="input-group"> <span class="input-group-addon">@</span> <input type="text" class="form-control" name="name" id="inputGroupSuccess1" aria-describedby="inputGroupSuccess1Status"> </div> </div> <div class="form-group"> <label class="control-label">Select File</label> <input type="file" id="inputGroupSuccess2" name="archive" class="file" multiple data-allowed-file-extensions='["zip", "tar"]'> <small id="fileHelp" class="form-text control-label" style="color:black">Upload a Tar or Zip archive without a Dockerfile, otherwise your deployment will fail.</small> </div> <div id="spinner" style="display: none;"> <div class="f_circleG" id="frotateG_01"></div> <div class="f_circleG" id="frotateG_02"></div> <div class="f_circleG" id="frotateG_03"></div> <div class="f_circleG" id="frotateG_04"></div> <div class="f_circleG" id="frotateG_05"></div> <div class="f_circleG" id="frotateG_06"></div> <div class="f_circleG" id="frotateG_07"></div> <div class="f_circleG" id="frotateG_08"></div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-lg pull-right" value="Submit"> Submit </button> <span style="padding-right: 5%;float: right;"><a href="{% url 'users:new-instance' %}" class="btn btn-primary btn-lg"><img src="{% static 'images/go-back-arrow.svg' %}" style="width: 24px; height: 24px;"> Go Back! </a></span> </div> </form> </div> </div> </div> </div> my javascript <script type="text/javascript"> $(document).ajaxStart(function() { $('#spinner').show(); console.log("ajax start") }); $(document).ajaxStop(function() { $('#spinner').hide(); }); $(document).on('submit', '#gitForm', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url : '/user/instance/create/new/awod/', data: { … -
Django 1.11 Python 3.6 ImageField 404 Error
Not sure how to display my ImageField in Django. Currently, my images are located in /media/static/ and the paths on my terminal all match up to where the images are locally. How come the images do not display? <img src="{{o.image.url}}"/> ^^ using above code in index.html to display the image. ^^ settings.py ^^ urls.py within the current application -
Django views database value remains '\'\
I am pretty new to web-dev and was asked to write a survey using Django and Ajax. I am have a bit of trouble on getting values updated in database. As shown in this screenshot of CMD, my SQL values is always blank even though there's value printed (The RxCx is value it got from request.POST.get) Models.py class Office(models.Model): Office_Space = ( ('R1B1', 'R1B1'), ('R2B1', 'R2B1'), ('R3B1', 'R3B1'), ('R1B2', 'R1B2'), ('R2B2', 'R2B2'), ('R3B2', 'R3B2'), ('R1B3', 'R1B3'), ('R2B3', 'R2B3'), ('R3B3', 'R3B3') ) space = models.CharField(max_length=4, choices=Office_Space) Forms.py from django import forms from Survey.models import Office class officeForm(forms.ModelForm): class Meta: model = Office fields = ['space',] Function in views (views is poorly written but if I do it other ways the form ends up being invalid...) def get_Office(request): form_class = officeForm if request.method == 'POST': space = request.POST.get('result') response_data = {} print(space) # here is the RxCx printed for debugging response_data['space'] = space form = Office() form.save() print (connection.queries) #the SQL log return JsonResponse(response_data) else: form = officeForm() return render(request, 'Front.html', {'officeform': form}) Thanks in advance. -
Django – generate a plain text version of an html email
I want to improve deliverability rates by providing both text-only and html versions of emails: text_content = ??? html_content = ??? msg = EmailMultiAlternatives(subject, text_content, 'from@site.com', 'to@site.com') msg.attach_alternative(html_content, "text/html") msg.send() How can I do this without duplicating email templates? -
Django cannot call migrate after makemigrations utilizing call_command
I am using django 1.11 on python 3.6. The easiest way I can explain my problem is that I am creating a test database on the fly in my code. I do this with the following script: from uuid import uuid4 as uuid db = '_' + uuid().hex + 'db.sqlite3' os.environ.setdefault('DJANGO_TEST_DB_NAME', db) print(db) import django from django.apps import apps from django.conf import settings from django.core.management import call_command os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") django.setup() print("Setting up test database\n") print("Clearing migrations...\n") _dir = os.getcwd() _search = ['project', 'email_auth', 'google', 'app2', 'app3'] for _d in _search: _walk = os.walk(_dir + os.path.sep + _d) for _walkObj in _walk: if _walkObj[0].split(os.path.sep)[-1] == 'migrations' or \ (_walkObj[0].split(os.path.sep)[-2] == 'migrations' and _walkObj[0].split(os.path.sep)[-1] == '__pycache__'): for _fName in _walkObj[2]: os.remove(_walkObj[0] + os.path.sep + _fName) print("Calling manage:makemigrations\n") call_command('makemigrations', *_search[1:]) apps.clear_cache() apps.populate(settings.INSTALLED_APPS) print("Calling manage:migrate...\n") call_command('migrate') print("Creating objects...\n") call_command('create_objects') print("Starting server...\n") call_command('runserver') No matter what I do to the apps object (I tried some hacky things to clear out everything inside of it to reload, but no dice) or anything else I cannot get django to realize that there are migrations created for any of my apps when calling migrate. I have even attempted just calling into migrate, email_auth and it states that django.core.management.base.CommandError: … -
Django Template view url or FileField
I have a model form with file1=forms.FileFiled(required=False) , the template shows it fine, with the default widget when using {{ f.file1 }} if the form has data from an instance, how can I know the file name and url in the template? I would like to serve the file myself with a function instead of how django shows it in the template, which does not work. -
Are django session variables secure?
I am creating an app for use in our organization that will login users based on their Office 365 credentials using OAuth2.0. I am fetching an access token that I will store in a session variable. Here is an example of what I am doing: @never_cache def authorization(request): microsoft = OAuth2Session(client_id,scope=scope,redirect_uri=redirect_uri) token = "" try: users = 'https://graph.microsoft.com/v1.0/me' ##msgraph query url- ##This query is purelyjust used to ##authenticate user! token = microsoft.fetch_token(token_url,client_secret=client_secret,code=request.GET.get('code', '')) ##Code is the authorization code present ##in request URL header = {'Authorization': 'Bearer ' + token['access_token']} response = requests.get(url = users, headers = header) if int(response.status_code) != 200: ##if status code is not 200, then authentication failed. Redirect to login. print ('Not validated. Return to login.') request.session.flush() return redirect('http://localhost:8000/login') except Exception as e: print ('User not does not have authentication rights') request.session.flush() return redirect('http://localhost:8000/login') request.session['oauth_state'] = 'authorized' response = HttpResponseRedirect('http://localhost:8000/search') return response I am then using this to cross-reference in the redirected search function if the session variables 'oauth_state' and 'token' are the same, like was set above. However, I may change this so that the token is used to query the MS Graph API in each function in order to check if the user has proper … -
How to get a list of all many related models
I currently have 2 models as such. The model modelToolName has a many-to-many relationship with modelNormalBodyPark. I currently have a body_part= "Head" and a tool_name="hammer" class modelNormalBodyPartResult(models.Model): body_part = models.ForeignKey(modelBodyPart, default=None) tool_name = models.ManyToManyField(modelToolName, default=None, blank=True) class modelToolName(models.Model): tool_name = models.CharField(max_length=250,unique=True) Now somewhere in my code i am doing this nqset = modelNormalBodyPartResult.objects.filter(body_part=body_qset, tool_name__tool_name__iexact=tool) This returns back an object however when I do this toolname = nqset[0].tool_name.tool_name I get the error ManyRelatedManager object has no attribute too_name Now from the reading I have done I believe this is because (correct me if I am wrong) the modelNormalBodyPartResult may have many modelToolName attached to it instead of only one. So my question is how can I get a list of all the modelToolNames associated with modelNormalBodyPartResult. I would like to get the string hammer. -
Show ImageField in Angular template
I'm using Django with Angular to build a blog, and would like to use Django's built-in ImageField. <img src="{{ post.image }}"> is not rendering the image though. It is rendering the other fields though (This HTML - <span>{{ post.title }}</span> - works fine). models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=200, blank=True, null=True) date_added = models.DateField(editable=True) author = models.ForeignKey(User) image = models.ImageField(blank=True, null=True) text = models.TextField(null=True, blank=True) def __str__(self): """Return a string representation of the model""" return self.title -
Nginx not show urls of angular 4
I am deploy my web server in Django with Angular4 into my LightSail server but I have a problem, because I try access to my page example.com and redirect to example.com/home, no problem I see my page without problems, but If I try to reload the page it sends me a message as if the route did not exist, being that in my local if I can do it without problem. this is my config in vim /etc/nginx/sites-enabled/trackerServer, I will be honest, I followed a guide since I do not handle much with nginx from LightSail with Django server { listen 80; server_name 54.175.253.151; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/tracker-web/trackerServer; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/tracker-web/trackerServer/trackerServer.sock; } } I discard that my problem is with gunicorn. Someone has gone through the same and has managed to solve this problem of routing? -
Finding Where a Filename is Used in Django
I am currently working on a project in Django (1.9) and used a filename convention that was suitable for my needs. Such a need was rebuilding the entire site using Django, and using the same filenames but with 'django_' in front. Example: home.py became django_home.py Not that this explanation or example is necessary, just wanted everyone to see just what I am talking about. Anywho, I am now done transitioning over to Django and want to get rid of the django_ in front of the filenames. Question: How can I see what functions are using my filenames? I am currently using Atom as my IDE, maybe that has a tool? I can manually go through all my files and see what is affected (change names and see what comes up as an error in the dev server?) but I would love a more autonomous way of doing this. -
transfer from parent class to child class with same id and info? django
I have a model such as class UP(models.Model): # lots of fields some are unique fields user = model.ForignKey(User) # default user model from django class M(User): # a few extra fields I have lots of UP objects created already. I want to be able to transfer an object selected in UP into M vise-versa. Is this possible? So all the id and info will be kept as is. But there are unique fields and Foreign key in UP I know that if I create a M myself as a new object, I can use the same id and look up in UP but then what I get in return would be UP object not M object. Anyone able to give me a hand with this?, thx in advance -
django - override User model entries
Is it possible to override the name of both is_superuser and is_staff to custom values? Nothing I'm seeing would make it possible I'm guessing the alternative would be to do an AbstractUser and then make new values for what is required like is_admin and then reference that boolean instead and hide the is_staff as an example from all forms? -
How to open FileField object in validator function, without disrupting view?
In my Django app, I'd like to validate that the input to a FileField is a CSV file, before using the data inside. I'd like to not only look at the extension of the file, but also try to create an iterable with csv.reader(), then calling next() on the iterable. My thinking is that those actions might cause errors that I'd be able to catch before actually using the data in the CSV file. In my forms file, I have: def validate_csv(value): if not value.name.endswith('.csv'): raise ValidationError("not a .csv file") try: csvreader = csv.reader(value.file) header = next(csvreader) except csv.Error: raise ValidationError('Failed to parse the CSV file') class UserPass(forms.Form): file = forms.FileField(validators=[validate_csv]) And in my views file I have: def get_vars(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = UserPass(request.POST, request.FILES) # check whether it's valid: if form.is_valid(): f = TextIOWrapper(request.FILES.get('file')) csvreader = csv.reader(f) l = [(x, y) for x, y in enumerate(csvreader, 1)] return HttpResponse(l) else: return HttpResponse(form.errors) # if a GET (or any other method) we'll create a blank form else: form = UserPass() … -
Django, Looping Through Zipped Lists Twice
So in essence the problem that I have is I cannot iterate through a zipped list twice. I've tried to copy the zipped list twice . list = zip(vmarray, uuidarray) This is where the list containing the vm's, in the view portion of the code is instantiated. def malware(request): list, dictofvms = listofvms() listcopy = iter(list) list, listcopy = tee(listcopy) malwarelist = listofmalware() return render(request, 'malware.html', {"malwarelist": malwarelist, "list": list, "listcopy": listcopy}) This is the part of the code that transmits the request through to the actual webpage. Now when accessing it in the code when i loop through the malware list. It only allows me to loop through the list once, due to it being zipped/ an iterator. If there's any way that I can loop through the items that'd be fantastic. (there must be something simple) [i'm probably just being stupid] {% for malware in malwarelist %} {{ malware }} {% for vm, uuid in list %} {{ vm }} {% endfor %} {% for vm, uuid in listcopy %} {{ vm }} {% endfor %} {% endfor %} -
How to handle django long task on aws
i am beginner in django and aws and i'm trying to run my django app on aws, i have this view that make some process on video and displays a loading template while this process is running to make the user wait, so it takes about 3 min or more depending on the video size, it did work on developpement mode but once on aws, the process get stopped after 2700ms maximum. How could i run such long task on aws ? My views: ######################### Call load template ############################### def process(request): return render(request, 'testgif.html') ######################### Process the video and send notification email to user when process is done ################################### def getor(request): # get video from s3 bucket mounted on ec2 instance var = Video.objects.order_by('id').last() v = '/mnt/s3/media/videos/' + str(var) # process subprocess.call("./step1.sh %s" % (str(v)), shell=True) #send email notification current_site = get_current_site(request) user = User.objects.values('username').order_by('id').last() us = user['username'] subject = 'Notification of end of process.' message = render_to_string('notify.html', { 'us':us, 'domain':current_site.domain, }) eml = User.objects.values('email').order_by('id').last() toemail = eml['email'] email = EmailMessage(subject, message, to=[toemail]) email.send() return render(request, 'endexecut.html') My loading template: {% extends 'base.html' %} {% load staticfiles %} {% block content %} <div class="container"> <div class="row"> <div class="jumbotron"> <div class="row"> … -
Running scripts on another system through Django View
I need my Django View to be able get data from the user and then use this data to create and run scripts on another VM/System. I figure that I would have to spawn threads for this process to run. Is there a best practice for this? -
xlwings + Django: how to not loose a connection
I am trying to deploy a spreadsheet model with a web page front end using Django. The web "app" flow is simple: User enters data in a web form Send form data to a Django backend view function "run_model(request)" Parse request object to get user inputs and then populate named ranges in the excel model's input sheet using xlwings to interact with a spreadsheet model (sheet.range function is used) Run "calculate()" on the spreadsheet Read outputs from another tab in the spreadsheet using xlwings and named ranges (again, using sheet.range function). The problem is that the connection to the Excel process keeps getting killed by Django (I believe it handles each request as a separate process), so I can get at most one request to work (by importing xlwings inside the view function) but when I send a second request, the connection is dead and it won't reactivate. Basically, how can I keep the connection to the workbook alive between requests or at least re-open a connection for each request?