Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add select all in django?
i want have a form like this https://www.jquery-az.com/boots/demo.php?ex=63.0_9 How i can make this form in django ? Thank you -
Django registration redirect to profile after login
I'm using django-registration-redux and have most of it working. I'm trying to redirect to the user profile after login. Currently the URL for user profile is: url(r'^user/(\w+)/$', views.profile, name='profile'), ...and the view for the profile is: def profile(request, username): user = get_object_or_404(User, username=username) products = Product.objects.filter(user=user) if not request.user == user: return render(request, 'no.html') else: return render(request, 'profile.html', {'user':user,'products': products}) I've added LOGIN_REDIRECT_URL = 'profile' to settings.py but am getting the error: Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['user/(\\w+)/$'] I've gone around this so many times I'm totally confused. I could simply set LOGIN_REDIRECT_URL = 'home' and be done with it, but then I wouldn't have gotten past this error. Do I need to create a different view for this? -
Access denied using Django with oAuth2 (django-oauth-toolkit)
First I made a test application, and after the user is logged in and authorizes the app, he receives the code that later will be used to grant access. As a test, I made a basic html site with many things hardcoded to check it works: <!DOCTYPE html> <html> <head> </head> <body> <form method="post" action="http://localhost:8000/o/token/"> {% csrf_token %} <input type="hidden" name="code" value="{{ code }}" /> <input type="hidden" name="redirect_uri" value="http://google.com" /> <input type="hidden" name="grant_type" value="authorization_code" /> <input type="hidden" name="client_id" value="{{ client_id }}" /> <input type="hidden" name="client_secret" value="{{ client_secret }}" /> <input type="submit" value="GO" /> </form> </body> </html> Here I get the code I received before, the client id and secret, received when I created the application, and I sent it in a post form to token. I was expecting that after clicking in GO I will be redirected to google, but it just raised an error "access denied". I tried other things but I got other errors and I stuck myself in here because it seems that "access denied" is just about the credential. Or maybe I'm not sending the right data? Thanks. -
Accessing form data in-between steps outside Django FromWizard’s class (accessing kwargs outside of class)
I’m trying to implement aRkadeFR’s solution for repeating steps of the form wizard dynamically (I'm using django-formtools 2.0). My code looks something like this: def form_factory(request, *args, **kwargs): FORMS = [ ('choose_transaction', generator_forms.TransForm), ('choose_functions', generator_forms.ChooseFunctionForm), ] print kwargs # always prints {} x_id = kwargs.get('pk') # this is always None if x_id is not None: x = ContributionDescription.objects.get(pk=x_id) try: functions_ids = request.session['wizard_return_class']['step_data']\ ['choose_functions']['choose_functions-funct_title'] if functions_ids is not None: print functions_ids # prints what I need, but never when I need except KeyError: pass # some logic to be inserted here, like # for i in list_of_x # index_in_form_list = FORMS.index(('choose_functions', enerator_forms.ChooseFunctionForm)) + 1 # placeholder logic # new_form = ('choose_f_description', generator_forms.ChooseFunctionDescriptionForm) # FORMS.insert(index_in_form_list, new_form) class ReturnClass(TestWizardView): form_list = FORMS return ReturnClass.as_view()(request, *args, **kwargs) Is accessing request.session a way to go? The print functions_ids runs not right after pressing next of the 'choose_functions' step, but after pressing next of the subsequent step (here: after the 'choose_f_description' step), which is not sufficient for me. In other examples I’ve found there is no problem with accessing wizard’s kwargs outside the wizard class, but I don’t understand how they’ve done it: DynamicQnaire’s load_questionnaire function surveyweb’s do_survey_factory function Thanks in advance. I’m beginner so I … -
(Django) How to transfer value from field to the custom ImageKit processor inside the model?
I use Django ImageKit to process/crop uploaded photos. I added my own custom processor to add text to the photo (like watermark): # ./example/processors.py from django.conf import settings from PIL import Image, ImageDraw, ImageFont _default_font = ImageFont.truetype(settings.TEXT_OVERLAY_FONT_REGULAR, 24) def add_text_overlay(image, text, font=_default_font): rgba_image = image.convert('RGBA') text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0)) image_draw = ImageDraw.Draw(text_overlay) text_size_x, text_size_y = image_draw.textsize(text, font=font) text_xy = ((rgba_image.size[0] / 2) - (text_size_x / 2), (rgba_image.size[1] / 2) - (text_size_y / 2)) image_draw.text(text_xy, text, font=font, fill=(255, 255, 255, 255)) image_with_text_overlay = Image.alpha_composite(rgba_image, text_overlay) return image_with_text_overlay class TextOverlayProcessor(object): def __init__(self, text='Lorem ipsum dolor sit amet'): """ :param text: The overlay text, string. """ self.text = text def process(self, img): return add_text_overlay(image=img, text=self.text) But how to transfer value from field to the custom ImageKit processor inside the model? Something like this: # ./example/models.py from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill from .processors import TextOverlayProcessor class Example(models.Model): description = models.CharField('Description', ...) image = models.ImageField('Picture', default=None) image_800x800 = ImageSpecField( source='image', processors=[ ResizeToFill(800, 800), TextOverlayProcessor(text=self.description) # but `self` is wrong and raise error ], format='JPEG', options={'quality': 100} ) ... I will be glad to explanatory comments and/or use cases. -
Moving margins bug that is not activating - bootstrap
I have a django project and I am working on a template. I have a template that has some html and css. I want to have an image that is inline with text. That is happening but I wan tot move the text down a little bit by adding padding or margin. So what i have right now is bootstrap incorporated with my html and css. I have added custom css to the template that over ride the bootstrap to get more refined css. Now what i want is to move the | username down a few pixels. I will have all of my code below and a sample image.. Here is my html template code: <div class="row solid-borders"> <div class=" col-md-2 border-padding"> <img src="{% static 'images/yap-logo-possible-1.png'%}" class="header-icon-size" style="display:inline;" alt=""> <h1 class="border-padding border-margin-top" style="display:inline;">| {{ user.username }}</h1> </div> </div> here is my custom css that I have added: .border-padding { padding: 8px !important; } .border-margin-top { padding-top: 25px !important; } .solid-borders { border-bottom: 1px solid black !important; } and I have bootstrap incorporated in it sample image: -
How to render Django query set as column wise into html table?
Let's say my sql table looks like this.. products table -------------------------------- | id | Model| Manufacturer | -------------------------------- | 1 | ABC | Samsung | | 2 | XYZ | LG | | 3 | ZYX | Sony | -------------------------------- in django view i fetched all records from this table and passed it to template.. def compare(request): product_ids = request.GET.get('product_ids') products = Product.objects.filter(id__in=product_ids) return render(request, 'compare.html', {'products': products}) as query_set result records comes like one after the other we can say it is following row wise but for this case in template i wanted to create an html table and the result should come like this .. -------------------------------------------- |id | 1 | 2 | 3 | |Model | ABC | XYZ | ZYX | |Manufacturer | Samsung | LG | Sony | -------------------------------------------- By looking at above example you can see data is rendered as column wise. so please suggest me a better method in Django by which i can achieve this and also please correct me if i'm wrong as i'm beginner in Django. Thanks in advance -
PyPDF2 PdfFileMerger replacing PDF in memory with blank pages when merging
I am sending a PDF via POST to Django using ajax // Set up form data var formData = new FormData(); formData.append("docfile", myPDFreport) $.ajax({ url: "{% url "process_report" %}", type: 'POST', data: formData, cache: false, processData: false, contentType: false, enctype: 'multipart/form-data', // If sucess, download file success: function(data, status, xhr) { // Get the name of the file // https://stackoverflow.com/questions/40939380/how-to-get-file-name-from-content-disposition var filename = ""; var disposition = xhr.getResponseHeader('Content-Disposition'); if (disposition && disposition.indexOf('attachment') !== -1) { var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; var matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) { filename = matches[1].replace(/['"]/g, ''); } } download(data, filename, "application/pdf"); } }); Then I am receiving the PDF in my views.py file, scraping it for some new information to create a second PDF, and am merging the two PDF files to return def process_report(request): # Handle file upload if request.method == 'POST': # Grab report report_file = request.FILES['docfile'] # Create merged coversheet and report by passing PDF object merged_pdf, coverSheetNameFinal = analyzer(report_file) response = HttpResponse(merged_pdf.getvalue(), content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="{}"'.format(coverSheetNameFinal) return response else: return HttpResponseBadRequest('Must be Post') The files are being merged in the analyzer function as def analyzer(report_filePDF): .......generate a PDF named "coverSheetFinal" using reportLab... coverSheetPDF = StringIO.StringIO(coverSheetFinal.getpdfdata()) merger = … -
Filtered Django result not getting displayed properly
I have a kanban board and there seems to be something strange going on with it. If If I move a card more than once in the same day, it won't stay even though I can see it updated the database properly. views.py def account(request): if not request.user.is_authenticated(): return render(request, 'kanban/signup.html') users_jobs = Job.objects.filter(user=request.user).exclude(status='INACTIVE') stages = create_stage_dict() for job in users_jobs: job_tracker = Tracker.objects.filter(job=job.id).latest('id') job_stage = Stage.objects.get(id=job_tracker.stage.id) stages[job_stage.reference_name]['jobs'].append(job) return render(request, 'kanban/board.html', {'navbar_template': choose_navbar(request.user.is_authenticated()), 'stages': stages.items()}) board.js function draggableInit() { var sourceStageID; $('[draggable=true]').bind('dragstart', function (event) { sourceStageID = $(this).parent().attr('id'); event.originalEvent.dataTransfer.setData("text/plain", event.target.getAttribute('id')); }); $('.panel-body').bind('dragover', function (event) { event.preventDefault(); }); $('.panel-body').bind('drop', function (event) { var children = $(this).children(); var targetStageID = children.attr('id'); if (sourceStageID != targetStageID) { var jobID = event.originalEvent.dataTransfer.getData("text/plain"); setTimeout(function () { var job = document.getElementById(jobID); children.prepend(job); }, 1); $.ajax({ type: 'POST', url: '/account/update_tracker/', data: {'job': jobID, 'source_stage': sourceStageID, 'target_stage': targetStageID }, dataType : 'json', }); } event.preventDefault(); }); views.py - view for the url called in the ajax request @csrf_exempt def update_tracker(request): if not request.POST: return render(request, 'kanban/board.html') job_id = request.POST.get('job') job = Job.objects.get(id=job_id) target_stage_id = request.POST.get('target_stage') target_stage = Stage.objects.get(id=target_stage_id) Tracker.objects.create(job=job, stage=target_stage) return HttpResponse(json.dumps({'job': job_id, 'target': target_stage_id}), content_type='application/json') The database does update when the card gets moved and I've used … -
Django form idea how to do this
I dont know how to do this in Django. I want to fill The form with data, next render The page with all information from previous page with form and then submit IT to database can anyone help me plase. -
Django: How to pass a javascript var to Django URL as parameter in ajax?
How can I pass a javascript variable to a Django URL? It presents a, TypeError at /object/Query/details view() got an unexpected keyword argument 'query' I am trying to redirect to another HTML page following this process: HTML Search Input > Pass to Javascript through input button onclick > Pass to JQuery Ajax sendQueryData> Redirect to another page using Django render() ;considering I had to do more things on the passed parameters to the URL upon passing them in AJAX. The main problem lies on this two lines (I think): url_page = url + "{% url 'view' 'query'%}"; //supposedly how we get parameters (but query is a javascript `var` and url =url.replace('query' , query); //where I intend to correctly build the url forcing the query to take its place in the url I'm just not quite sure if my urls.py, ajax call on javascript in Django url are all aligned at all. My urls.py urlpatterns = [ url(r'^$', views.index, name='homepage'), #--- Home --- url(r'^search/pass/$', views.pass_query, name='pass_query'), # View Object Details url(r'^object/(?P<query>\w+)/details', views.view(), name='view') My HTML <div id="button-group" class="button-group"> <input type="submit" class="btn btn-primary btn-lg btn-space col-sm-3" onclick="redirect_to_url(0)" value="View Routes"/> <input type="submit" class="btn btn-primary btn-lg btn-space col-sm-3" onclick="redirect_to_url(1)" value= "View City Details"/> <input … -
Nginx Gunicorn one ip multiple django sites in folders
thanks for reading my question. I'm trying to serve multiples Django sites on their own folders in one server without domain (only IP address) using Gunicorn and Nginx. Something like that: 20.20.20.20/demos/myapp1/ --> Django app 20.20.20.20/demos/myapp2/ --> Django app 20.20.20.20/demos/myapp3/ --> Django app I have tested a lot of settings but I can't make it work. When i tried to load URL 20.20.20.02/demos/myapp1/ i get a 404 not found error :( Example one site nginx conf: upstream app1_server { server unix:/webapps/myapp1/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name 20.20.20.20; keepalive_timeout 5; client_max_body_size 4G; location /static/ { alias /webapps/myapp1/static/; } location /media/ { alias /webapps/myapp1/media/; } location /demos/myapp1/ { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app1_server; } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /webapps/myapp1/static/; } } What is wrong with my myapp1.conf file? For the record, if i change "location /demos/myapp1/" to "location /" my first app works, but the others apps still not working. Thanks in advance. -
Django check upload file content
I'm new with Django. I have facing problem that I want to check the file content before letting user upload the file. Please give me some example to show how to do it. Thanks -
Uploading and processing a csv file in django using ModelForm
I am trying to upload and fetch the data from csv file uploaded by user. I am using this method for doing the same, which pretty much explains everything and gives me result also. What I am not able to get is that in his view function it says: def upload_csv(request): data = {} if "GET" == request.method: return render(request, "myapp/upload_csv.html", data) # if not GET, then proceed but when I am printing request.method: def upload_csv(request): print request.method it says "GET" not "POST". My doubt is, if the request.method is GET then why the code is not skipping the "try-except" block and how is it processing the csv file? when the HTML form method is set as "post", why is it showing request.method as "get" ? I have looked for this and this (which is somehow related to my question) but there is no final answer on these questions. I have also tried the append slash redirect by typing the proper URL but the request.method remains "GET". Can anyone clarify this? -
Django DRF JWT authentication get, refresh, verify token
I have simple Django DRF application setup which I have implemented JWT authentication. I used the Django REST framework JWT documentation I can successfully get a token using the following notation used in the documentation: $ curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/ However, when I try using this other variation, I get an error: $ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/ The error I get is: {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"} I also had the same error when trying to refresh or verify the token: Refresh: $ curl -X POST -H "Content-Type: application/json" -d '{"token":"<EXISTING_TOKEN>"}' http://localhost:8000/api-token-refresh/ Verify: $ curl -X POST -H "Content-Type: application/json" -d '{"token":"<EXISTING_TOKEN>"}' http://localhost:8000/api-token-verify/ I was adding the token as follows: curl -X POST -H "Content-Type: application/json" -d '{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNpdHJ1Y3AiLCJleHAiOjE1MTE2NDg5MjIsInVzZXJfaWQiOjEsImVtYWlsIjoiY3VydGlzLnBva3JhbnRAZ21haWwuY29tIn0.T5h_PSvzvKOZCPTS60x5IUm3DgAsRCRmbMJeGWZk3Tw"}' http://localhost:8800/api-token-refresh/ Am I perhaps adding the token incorrectly? Does it need some other formatting with quotes? -
Matplotlib's NavigationToolbar with Django
Is there any way to use NavigationToolbar (such like in tkinter) to generate interactive charts in django or the only sensible choice is to use chart.js? -
Django crispy form CrispyError for DetailView with added model
I wanted to have a form that shows (retrieves) user information in the crispy form style, based on two models using a DetailView: class DashboardView(DetailView): model = User form_class = DashboardForm template_name = 'dashboard.html' def get_context_data(self, **kwargs): context = super(DashboardView, self).get_context_data(**kwargs) pk = self.kwargs['pk'] user = get_object_or_404(User, pk=pk) context.update({'user': user}) profiles = Profile.objects.filter(owner=user) if profiles.count == 1: context.update({'profile': profiles[0]}) else: # TODO - error return context With the form defined as: class DashboardForm(forms.Form): def __init__(self, *args, **kwargs): super(DashboardForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Fieldset( '', 'user.username', 'profile.code' ), ButtonHolder( Submit('submit', 'Submit', css_class='button white') ) ) And code in the template as: {% load crispy_forms_tags %} ... <form> {{ user.username|as_crispy_field }} {{ profile.code|as_crispy_field }} <input type="submit" value="Submit" class="btn btn-success"> </form> But this gives an error: CrispyError at /dashboard/1/ |as_crispy_field got passed an invalid or inexistent field I am not sure that this is the right way to combine two related records on a crispy read only / retrieve style form. -
'ModuleNotFoundError: No module named 'MySQLdb' In Django
creating my first module in django, I am using mac Tried steps: 1.installed python 3.6.+ version, 2.cloned git project 3.setup local env, to create a module, trying with command env=dev python3 manage.py startapp supriya_module_inflow; getting error in console : Environment Selected :dev Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 24, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 35, in <module> execute_from_command_line(sys.argv)...... ... raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' -
What kind of proficiency is required for a junior developer position? [on hold]
I am interested in what would be considered as a good complexity for a project that would be used at an interview for a junior/entry level developer position. For reference I mainly use React/Flask or React/Django, if that makes a difference I am interested in what would be expected. Would a blog site with users be too sinplistic? Something like yelp to complex? Do I need an app with multiple databases using multiple api's? I am wondering how to know if I am ready for a junior position. (Obviously I can apply for jobs and find out at technical interviews etc, but I was more asking how could I know on my own) -
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail".
I am getting the common DRF hyperlinked model-detail error, and I'd like to understand what it means so I stop getting it. The view is as such: import json import time from django.http import JsonResponse from django.contrib.auth.models import User from rest_framework import serializers, viewsets from utils.general import unpack_request_body from .models import Restaurant #------------------------------------------------------------------------------------ class RestaurantSerializer(serializers.HyperlinkedModelSerializer): # answered by bovenson: # https://stackoverflow.com/questions/20550598/django-rest-framework-could-not-resolve-url-for-hyperlinked-relationship-using # what just happened here? idk what HyperlinkedIdentityField does url = serializers.HyperlinkedIdentityField(view_name="restaurant:restaurant-detail") class Meta: model = Restaurant fields = '__all__' class RestaurantViewSet(viewsets.ModelViewSet): queryset = Restaurant.objects.all() serializer_class = RestaurantSerializer #------------------------------------------------------------------------------------ def find_restaurant_owned_by_a_username(username): try: user = User.objects.get(username=username) except: return None restaurants_owned = user.restaurants.all() if restaurants_owned: return restaurants_owned[0] else: return None def restaurants_owned_by_this_username(request): """ for now only returns one restaurant """ # TODO: will need to support multiple restaurants owned by one user in the future if request.method == "POST": body = unpack_request_body(request) username = body['username'] restaurant_owned = find_restaurant_owned_by_a_username(username) if restaurant_owned: serializer = RestaurantSerializer(restaurant_owned, context={'request': request}) return JsonResponse({'result': serializer.data}) else: return JsonResponse({'result': None}) else: error_message = "This method only responds to POST" print(error_message) return JsonResponse({'error': error_message}) urls: urlpatterns = [ ... url(r'^api/restaurants-owned', csrf_exempt(views.restaurants_owned_by_this_username), name="restaurants-owned"), ] models.py: from django.contrib.auth.models import User class Restaurant(models.Model): name = models.CharField(max_length=250, null=False, blank=False) phone = models.CharField(max_length=12) owner = … -
Object of type 'Response' has no len() in DRF
ive combined two models. one model's field is annotated to another model's so they can merge. However, when I try to return the data, I get TypeError: object of type 'Response' has no len(). I've followed several examples on stackoverflow and it doesnt seem to be working. Here's what I have: class ExploreAPIView(generics.ListAPIView): def get_queryset(self): merged_queryset = Place.get_queryset(self.request.user) usr_pks = [u.pk for u in merged_queryset] queryset = Place.objects.filter(pk__in=usr_pks) serialUser = UserSerializer( User.objects.annotate(time=Extract('date_joined','epoch')), many=True).data[:] serialPlace = PlacesSerializer(queryset, many=True).data[:] chained_list = sorted(serialPlace +serialUser, key=lambda x: x.get('time')) return Response(chained_list) I dont understand why it returns no len() when it returns items if i print out the chained_list -
Access Django db by another python progra
I have a Django project working fine (deployed in nginx), using postgresql database. I have to access ORM database from another python program. I'm doing this with this code: if os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WebSite.settings'): import django django.setup() from WebSite.operation.models import Registers, OperationMode from WebSite.trend.models import TrendRegister from django.utils import timezone else: raise sys.exit(1) When i execute the program with default user (pi is my default user), works fine, but if a execute the program in root mode, the following erro occurrs: "password authentication failed for user root" I must have to execute this other program in root mode. How can i resolve this? -
Push notifications in django
I want to use fcm in django with firebase, but in the device model there are: Device ID , Registration Token and Device Type, but I dont know how to get this data. Thanks. -
How I can retrieve exact field from db table Django
someadwebsite Lets assume, that kind of site making now and I could print all object in same blocks from one database table with for loop but I don't have an idea how can I dynamicly request only exact field per link when follow the link , I need to print data on exact field Hope I understandably wrote Please help me! -
Embed opencv (jpg) image into html5 canvas in an editable form
I'm using python and opencv to segment an image. I read the image using opencv, perform the color clustering operations, and then output the image with cv2.imshow. What I want to do (and I have no idea how), is to embed the resulting segmented image into a html5 canvas (represent it like a svg or a similar "editable" format), so users can change the colors of each segmented region or hide some regions (operations are based on colors - I want to be able to dynamically change the colors of segmented regions, not just upload a "plain" jpg image in a html5 canvas). I'm using Django for implementing the web application. How can I achieve this? Note: if the question is offtopic, please kindly tell me where it would be suitable to post it?