Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
_io.BytesIO' object has no attribute 'name' for small size file
I'm uploading file with python/Django and getting two different attribute. When file is small in size, getting InMemoryUploadedFile object, while file is quite large, i got in temporaryFileWrapper. I m checking file mime type with magic library. when File is large, getting correctmime type with this code file_name = self.cleaned_data.get('file') file_mime= magic.from_file(file_name.file.name, mime=True) supported_format= ['video/x-flv','video/mp4','video/3gpp','video/x-ms-wmv'] if file_mime in supported_format: ........... But when file is small in size i m getting error _io.BytesIO' object has no attribute 'name for large file for small file -
Django - Save and add another functionality
I am trying to program a "Save and add another" functionality in my Django App. I put an elif condition to a button. I can't find any helpful resources and references around the web especially with my set of codes. I have tried puting two returns inside the elif and putting the self.object snippet inside. Any suggestions what I can do? I am very new with Django. Please help. Views.py def post(self, request, *args, **kwargs): if "cancel" in request.POST: return HttpResponseRedirect(reverse('skillsMatrixApp:index')) elif "another" in request.POST: #try 1 #self.object = self.get_object() #url = self.get_success_url() #return HttpResponseRedirect(url) #try 2 #return HttpResponseRedirect(reverse('skillsMatrixApp:employee-add')) #return super(employeeCreate, self).post(request, *args, **kwargs) else: return super(employeeCreate, self).post(request, *args, **kwargs) employee_form.html <div class="col-sm-offset-2 col-sm-10"> <button type="submit" formnovalidate name="cancel" class="btn btn-danger">Cancel</button> <button type="submit" formnovalidate class="btn btn-success">Submit</button> <button type="submit" formnovalidate name="another" class="btn btn-danger">Save and add another</button> </div> urls.py urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'employee/$', views.employeeList.as_view(), name='employee-list'), url(r'employee/add/$', views.employeeCreate.as_view(), name='employee-add'), -
django in Admin after save_mode() how to stay at current page view?
in my adamin.py file I want to stay at current page when if obj.question_text == '问题' instead of redirect to front page view, what should I do?Could anyone else help me? -
Remove a specific letter from form input
I am working on a Twitter-hashtag search program. Within clean(), I am attempting to check if the User included "#" in the SearchHashtagForm and, if so, remove it. For example, if the User enters "#foo" in SearchHashtagForm, I wish clean() to remove "#" and search for "foo" instead. Now, "#foo" is searched for instead. I suspect that the line: form_input = form_input[1:] doesn't work, but I'm not sure what else to use? Views.py class HashtagSearch(FormView): """ FormView for user to enter hashtag search query """ def form_valid(self, form): form.clean() return super().form_valid(form) Forms.py class SearchHashtagForm(ModelForm): """ ModelForm for user to search by hashtag """ def clean(self): cleaned_data = self.cleaned_data form_input = cleaned_data.get('search_text') if form_input.startswith('#'): # if input starts with '#', remove it. form_input = form_input[1:] cleaned_data['search_text'] = form_input return cleaned_data -
'str' object has no attribute 'strategy' - django-oscar
I am having trouble with this bug in django-oscar. I have read that promotion_tags.py was not rendering the request inside context. But I have seen the oscar code inside my virtualenv, it has the request inside the context but the weird thing is, functions inside promotion_tags.py are not being called, thus no request object in the context here is the code which needs the request object: @register.simple_tag def purchase_info_for_product(request, product): if product.is_parent: return request.strategy.fetch_for_parent(product) return request.strategy.fetch_for_product(product) anyone any idea? -
Django path() throws 404 when URL ends in Slash
Here is urls.py path('about/', about, name='about'), If I visit /about it gives 404 error, if if change it to path('about', about, name='about'), then if I visit /about works but /about/ gives 404 errors. What am I doing wrong here, this wasn't not happening prior to Django 2.0 -
django {{form.as_p}} results without input widget
So here's my form : from django import forms class PostForm(forms.Form): name = forms.CharField(), title = forms.CharField(), Here's my view : from django.shortcuts import render from .forms import PostForm def sign(request): form = PostForm() return render(request, 'guestbook/sign_extend.html', {'form': form}) and my html : {% extends 'guestbook/sign.html' %} {% block content %} <form action='.' method ='POST'>{% csrf_token %} {{ form.as_p }} <button type="submit">submit</button> </form> {% endblock %} url: from django.urls import path,include from . import views urlpatterns = [ path('sign/', views.sign,name='sign'), When I go to the url it only shows me button but no form fields. What am I doing wrong here ? I can't seem to figure that out..please help -
How do i create custom user permissions?
I have a model form, that is used to request a leave from a employees perspective. I want another user to either accept or reject the leave, for this purpose, I have a boolean field dedicated to it. models.py from django.db import models from django.contrib.auth.models import User CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave')) class Leave(models.Model): name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) employee_ID = models.CharField(max_length = 20) department = models.CharField(max_length = 15) designation = models.CharField(max_length = 15) type_of_leave = models.CharField(max_length = 15, choices = CHOICES, default = None) from_date = models.DateField() to_date = models.DateField() reporting_manager = models.CharField(max_length = 50, default = None) reason = models.CharField(max_length= 180) permission = models.BooleanField(('status'), default=False) def __str__(self): return self.name Now my goal is to make a custom permission such that another user can read-only rest of the fields except the "permission" field, where he can either accept or reject. I've tried using programmatically creating user permissions which reflected in the User Permissions Panel but didn't function as I wanted. views.py from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from .models import Leave content_type = ContentType.objects.get_for_model(Leave) permission = Permission.objects.create( codename='can_change_status', name='Can Change Status', content_type=content_type, ) Please help me in … -
Can not connect to localhost API from Android app
I am new to Django. I have created an API named http://127.0.0.1:8000/api/update/1/ and it works okay in the browser and on Postman app. However, when I am trying to access the API from the android app it is returning NULL. The android code works when the API is http://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=8190df9eb51445228e397e4185311a66 But not when the API is http://127.0.0.1:8000/api/update/1/. Although http://127.0.0.1:8000/api/update/1/ works okay in the browser and Postman app. I am attaching the code where API call is made. protected String doInBackground(String... args) { String xml = ""; String api = "http://127.0.0.1:8000/api/update/1/"; // returns NULL works in Postman app and in the browser // String api = "http://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=8190df9eb51445228e397e4185311a66"; // works in all places String urlParameters = ""; xml = Function.excuteGet(api, urlParameters); return xml; } -
Multi language website using Django 2.0
I am in finishing stage of my web page. As I am new in Django 2.0, I am having problem (actually have no idea ) with making my web page multilang. Could you give some explanation or tutorial for that? -
'tuple' object has no attribute 'get' attribute error
add_form = CarAddForm() if request.method == "POST": add_form = CarAddForm(data=(request.POST, request.FILES) or None) if add_form.is_valid: prof = add_form.save(commit=False) prof.profile = request.user.profile prof.purchase_yr = str(request.POST.get('purc_date')) prof.save() print("abc") print(add_form) messages.success(request,'Details saved successfully', extra_tags='alert') return redirect('/') else: add_form = CarAddFormCar() messages.error(request,'Something went wrong!', extra_tags='alert') prof = add_form.save(commit=False) is creating issues. **prof = add_form.save(commit=False) is creating issues. ** -
How to maintain custom order and Relay structure in graphene-django?
I have ran into an issue when using the DjangoConnectionField type in my graphql schema. I wanted to use my own custom resolver which would filter and sort a queryset from the Django models. I also wanted to make use of the relay output format. Inside my Query class used in the Schema, I setup a query field using the DjangoConnectionField. Then I wrote a custom resolver for it. My problem now is that the returned queryset from the resolver is ALWAYS returned in the very same order. My custom sorting in the resolver function is completely ignored. I checked the returned queryset and before it hits the final return, the custom sorting is intact. It only gets destroyed once it gets spit out of the graphql endpoint. Any ideas how I could keep my custom sort while also enjoying the structure provided by the relay framework (edges, nodes...)? Is this the intended behaviour of DjangoConnectionField? P.S.: I explicitly don't want to use django-filter. In order to provide a bit of reference to the problem, I have attached some code below: class Query(ObjectType): projects = DjangoConnectionField( ProjectType, filter=ProjectFilterInput(), sort=graphene.String()) def resolve_projects(self, info, **args): filterFields = args.get('filter') sortFields = args.get('sort') result … -
What are the best practices to use Django and React in a project
From youtube, I have watched a video tutorial about Django and React. The instructor made two directories named frontend and backend. In the backend directory, he made a virtual environment with Django and start a project. And a react app in the frontend directory. He used a RESTful API to establish communication between frontend and backend. I want to know if it is a best practice to do this, if not then what are the best practices -
can we change the default django files ? I have changes a file but the effect is not reflecting
can we change the default django files ? I have changes a file but the effect is not reflecting.If yes then my question is how to change the default buttons in the django which are save,save and continue editing and save and add another. -
Website for coordinating rehabilitation of people affected in the 2018 Kerala Floods
First of all sorry for violating the SO rules. Because this is that much urgent. You may heard about the flood in Kerala. If not (link) Below mentioned is the source code of the website for coordinating rehabilitation of people affected in the 2018 Kerala Floods. https://github.com/IEEEKeralaSection/rescuekerala/ It's written in python web framework (django). Anyone interested please contirbute. How can you help ? We have a lot of pull request that requires testing. Pick any PR you like, try to reproduce the original issue and fix. Also join #testing channel in our slack and drop a note that you are working on it. By fixing bugs or by adding features ? Please find the issues that we need help here. Go through the comments in the issue to check if someone else is already working on it. Don't forget to drop a comment when you start working on it. -
Django - invalid literal for int() with base 10:
I know about this exception but I don't know about how is this error is showing. I get Integer number from the request and I printed the type of number it says type of Int so how? here is my code: product = Product.objects.get(pk=self.kwargs['prod_id']) general = GeneralInfo(name=post.get('general-name'), product=product) general.save() and I tried product = Product.objects.get(pk=self.kwargs['prod_id']) general = GeneralInfo(name=post.get('general-name'), product_id=int(product)) general.save() and still getting error. What's the problem here? -
Django: serialize queryset with some custom columns and format some fields
I have the following models in my Django > 2 Project: class Post(models.Model): text = models.TextField() date = models.DatetimeField(default=datetime.now, blank=True) class Like(models.Model): post = models.ForeignKey(Post) user = models.ForeignKey(User, related_name="current_user_likes") I want to send a JSON response of list of Posts. And also show for each post show, if already liked or not, by the user logged in. For a particular user ,obtained by request.user, i want the the list of Posts to contain a boolean field "current_user_like" also. I am using the following way to create the queryset of Posts with, whether liked or not by a particular user. Same way as https://stackoverflow.com/a/33944811/2897115 posts = Post.objects.all().prefetch_related( Prefetch('current_user_likes', queryset=Like.objects.filter(user=request.user)) ) i am expecting a JSON as below: [ {"id":1, "text":"sample", "date":"whateverformat i want i.e YY-MM-DD","current_user_likes":"true/false"} ........] So want the Json with formated date and also added field of "current_user_likes". How to do it -
Django Refresh database until end of transaction
I have a long task, that is adding many records to a database table. In the table there is a field called "end". This field will be empty, until the task is done. As soon as the task ist done, I will write a value in the "end" field. Can I have a html page, that is refreshing the page every 5 seconds with the items from the table until the field "end" has a value? Does somebody has a example script for this? -
Django and Celery: scheduled task is running, but doesn't seem to do anything
I have created a Celery task in my Django app to scrape data and save it to database: #tasks.py from celery.task.schedules import crontab from celery.decorators import periodic_task from celery.utils.log import get_task_logger import datetime from .models import Listing, City #, ScrapingDate from .scrapers import AIRBNB_scraper_from_jason logger = get_task_logger(__name__) @periodic_task( run_every=(crontab(minute='*/1')), name="scrape_capitals_listings", ignore_result=True ) def scrape_capitals_listings(): default_checkin = datetime.date.today() default_checkout = default_checkin + datetime.timedelta(days=30) counter = 0 capitals = City.objects.filter(status='capital') for capital in capitals: print('Scraping listings for ' + capital.name) capitals_scraper = AIRBNB_scraper_from_jason(city=capital.name, checkin=default_checkin, checkout=default_checkout) capitals_listings = capitals_scraper.scraped_data for capital_listing in capitals_listings: listing = Listing() listing.name = capital_listing[0] listing.link = capital_listing[1] listing.price = capital_listing[2] listing.city = capital listing.country = capital.country listing.continent = capital.continent listing.date_added = datetime.datetime.now() listing.save() counter += 1 if counter == 3: break In my views.py I call the task like this: from .tasks import scrape_capitals_listings def dashboards(request): scrape_capitals_listings.delay()# I have also tried just "scrape_capitals_listings" capitals_chart = create_capitals_chart() context = {'capitals_chart':capitals_chart} return render(request, 'javascript/dashboards.html', context) The I run the server, Redis broker,celery -A test_project -l info and celery -A test_project -l info in separate terminals. I can see that the scheduled task is being sent by Celery like this [2018-08-17 07:16:00,018: INFO/MainProcess] Scheduler: Sending due task scrape_capitals_listings (scrape_capitals_listings), but nothing … -
How to work with Django using Jupyter notebook
I'm trying to work in Django using Jupyter notebook. Could someone guide me in how to start working with Django. I have installed all the necessary components like django, django-extensions and django-admin and other plugins using pip, as well as checking the INSTALLED_APPS and MIDDLEWARE in settings. I couldn't get to know, how to start working in a project. I normally work in Jupyter notebook. Please let me know how to work Django in Jupyter notebook or suggest me other options. Thanks a lot in advance. -
How can I recieve correct user email input in my email inbox?
I created a contact for to receive messages from users. But for some reason when I check my inbox the email address attached to the user is the admin email address. I have checked my view logic and it seems to be correct. How do I solve this issue? views.py from django.core.mail import send_mail from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from . import forms def contact(request): form = forms.ContactForm() if request.method == 'POST': form = forms.ContactForm(request.POST) if form.is_valid(): send_mail( form.cleaned_data['name'], form.cleaned_data['inquiry'], form.cleaned_data['from_email'], ['admin@sample.com'], ) return HttpResponseRedirect(reverse('contact')) return render(request, 'contact.html', {'form': form}) -
Verify if a user is using English or latin characters and issue a warning if not
I'm having a Django site, which is in English. For forms, I interested to know, when a user is using non-Latin characters and use a validation error to tell them to use English. -
How to add buttons in the main django admin page and how to edit the defaiting etct)ut buttons( save,save and continue ed
I want to add more functionalities in the default admin page buttons which are (save,save and continue editing ,save and add another).I want to enable a automatic mail delivery system for password reset.I have edited the submit_line.html but there is nothing happen.enter image description here -
Javascript: Enable High Accuracy Geolocation
How can I improve the geolocation by adding in Enable High Accuracy property into the code? I am a beginner and still learning Javascript. I would be grateful if someone could help me with this. Thank you. script.js var pos; var $demo; function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { $demo.text("Geolocation is not supported by this browser."); } } function showPosition(position) { pos = position; var { latitude, longitude } = pos.coords; $demo.html(`Latitude: ${latitude}<br>Longitude: ${longitude}`); $('#btn_submit').attr("disabled", null); } $(document).ready(function() { $demo = $("#demo"); $('#btn_submit').on('click', function() { var data = pos.coords; data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val(); $.post("/ajax/insert", data, function() { alert("Saved Data!"); }); }); }); index.html {% extends 'ajax/base.html' %} {% block body %} <p>Click the button to get your coordinates.</p> <button onclick="getLocation()">Get Your Location</button> <p id="demo"></p> <button type="button" id="btn_submit" class="btn btn-primary form-control" disabled>Submit</button> {% endblock %} views.py from django.http import JsonResponse from .models import Member def insert(request): if request.method == 'POST': member = Member(latitude=request.POST['latitude'], longitude=request.POST['longitude']) member.save() return JsonResponse({'message': 'success'}) -
create a list in models.py in django
So i was trying to create a quiz app where i wish to store the questions that my user has attempted which i was trying was associated with the user class. So i have two classes currently in my models.py file: class questions which contains a charfield for question, an integerfield for answer,and 4 charfields for choices named accordingly; and the second class is basically just a user class having fields to save the name,email,username and password of the user. now what i was trying was is there any method to store the questions using the questionid in an array/list/set/dict associated with the user .