Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to compress the image before uploading to s3 in django?
I am working on an application where a user can upload an image. I want to reduce the size of the image in 200-500kb. This is my models.py file class Report_item(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity') image = models.ImageField(default="add Item image", upload_to=get_uplaod_file_name) def __str__(self): return self.title + " " + str(self.publish) And this is my views.py file class ReportCreate(generic.CreateView): model = Report_item fields = ['title','image'] def get_form(self, form_class=None): if form_class is None: form_class = self.get_form_class() form = super(ReportCreate, self).get_form(form_class) form.fields['title'].widget = TextInput( attrs={'placeholder': '*Enter UID e.g. CBSE Marksheet Roll nunber 0506***'}) return form def form_valid(self, form): self.object = form.save(commit=False) self.object.owner = self.request.user self.object.save() return FormMixin.form_valid(self, form) I am using Django 1.11 and S3 storage. Kindly help me to compress the image before uploading to s3. -
Python mysql database sync
I have 3 servers(2 Local host servers and 1 Cloud server) where mysql is installed on each of them on daily basis i need to move all the data from server 1 to cloud server and move all the data from server 2 to cloud server now cloud server will have data from server 1 as well as server 2. Now after moving all the server data to cloud i need to move the complete data from cloud to local servers 1 and server 2 in this way the local server is also update. How can i use it i am using django framework 2 and python 3. There system should check whether all the servers are sync then it should start the complete data to the respective servers. -
django two class data in one table how to append
i want Mvouchar and Mycheque details append in one list that is reports and field is also same can i append this in one function bcoz in my way it append only Mvouchars value how can i do this for both..plz help views.py def all_report(request): reports = [] for report_obj in Mvouchar.objects.all(): reports.append({'topay': report_obj.to_pay, 'chequeno': report_obj.cheque_no, 'chequedate': report_obj.cheque_date, 'date': report_obj.dated}) return render(request, 'cheque/report.html', {'reports': reports}) def all_report(request): reports = [] for report_obj in Mycheque.objects.all(): reports.append({'topay': report_obj.to_pay, 'chequeno': report_obj.cheque_no, 'chequedate': report_obj.cheque_date, 'date': report_obj.dated}) return render(request, 'Cheque/report.html', {'reports': reports}) -
Django - How to group multiple records based on multiple columns
I am new to python/django so please bear with me. I have QuerySet qrySet.values_list('group_id', 'date', 'time', 'mobile') with that I get list like this [1, datetime.date(2018, 9, 8), datetime.time(18, 39), 'phone1'] [2, datetime.date(2018, 9, 12), datetime.time(4, 0), 'phone1'] [2, datetime.date(2018, 9, 19), datetime.time(4, 0), 'phone2'] [2, datetime.date(2018, 9, 19), datetime.time(4, 0), 'phone4'] [9, datetime.date(2018, 9, 10), datetime.time(4, 35), 'phone3'] [9, datetime.date(2018, 9, 17), datetime.time(4, 35), 'phone3'] [9, datetime.date(2018, 9, 18), datetime.time(4, 35), 'phone3'] I am trying to put all phone numbers together that have same group_id, date and time something like this [[group_id, date,time, [phone1, phone2, phone9]] Is there anything built-in in Django or python for this kind of thing? I tried some SO solutions using lambda but they group based on one value while I have three. Thank you -
Update an Object/Instance by overwriting the save method of another Model, by using the FK
I have the following models: class User(AbstractBaseUser, PermissionsMixin): acc = models.ForeignKey(Acc, blank=True, null=True, related_name='owner', on_delete=models.CASCADE) class Note(models.Model): name = models.CharField( max_length=35 receiver = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) class Item(models.Model): note = models.ForeignKey(Notification, on_delete=models.CASCADE,) acc = models.ForeignKey(Acc, on_delete=models.CASCADE) def save(self, *args, **kwargs): ..... # update note Note.objects.filter(id=self.note_id) .update(receiver=self.account.owner) I overwrite the save' method on theItemObject/Model, to update the 'Note' Modelreceiver` using the ForeignKey. I get the following error: int() argument must be a string, a bytes-like object or a number, not 'RelatedManager' -
Django Viewflow - How do apply the same activation for multiple tasks
With viewflow, My usecase is this: A user is assigned multiple tasks. He wants to select some of the task and apply the same activation(Approve/Reject) to them. How can we do this? -
DRF : how to get the verbose name for choices?
Let's say I have this model: class Student(models.Model): YEAR_IN_SCHOOL_CHOICES = ( (FR, 'Freshman'), (SO, 'Sophomore'), (JU, 'Junior'), (S, 'Senior'), ) year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) If I use DRF to expose the value for the year_in_school field, I get the first parameter of the choice, for example: "FR". How can I expose the second parameter "Freshman" instead of "FR"? -
Django REST Framework translation does not work
I have a problem with translating custom exception in Django rest, the problem is when I change the LANGUAGE_CODE in the settings, every things work fine and i get correct translation for both of my languages, but when I tried to use Accept-Language in the header to change the translation, it does not work as it should! my settings is: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'core.middleware.auth_middleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'core.middleware.dates_middleware', 'core.middleware.translation_middleware', ] #LANGUAGE_CODE = 'fa-ir' LANGUAGE_CODE = 'en-us' LANGUAGES = [ ('fa', _('Farsi')), ('en', _('English')), ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True my exception: from rest_framework.exceptions import APIException from django.utils.translation import ugettext as _ class WrongUsernamePassword(APIException): status_code = 401 default_detail = _('username or password is wrong') default_code = '401' my view: class UserViewSet(viewsets.ModelViewSet): ... @list_route(methods=['POST'], permission_classes=[AllowAny]) def app_login(self, request): lang = translation.get_language() # here the value is fa raise WrongUsernamePassword when I send the request with this header (Accept-Language=fa-ir) I can see that the lang variable value is fa so framework know that I change the language but the response is still in english: { "detail": "username or password is wrong" } any idea? -
How to perform stock updation process in Django Oscar
I was going through the code for the stock record model here, and above the num_allocated field it says in the comment, #: The amount of stock allocated to orders but not fed back to the master #: stock system. A typical stock update process will set the num_in_stock #: variable to a new value and reset num_allocated to zero So, how do I do the stock update process as specified in the comment when the product is out of stock?I need to set the num_in_stock variable to new value and set the num_allocated to zero. So far if the order is being shipped, I call the consume_stock_allocations() method in the EventHandler Class and the num in stock for the products in the order is being reduced. If someone has implemented this please do share some code or some example as I am new to oscar. -
This is from python and django framework question
How do you handle asynchronous task in Django? Mmmmmmmmmmm -
DJANGo Ajax request sometime return response and some time error
error:: jquery.min.js:2 POST http://127.0.0.1:9000/xyz/test 0 () path('test', views.test,name="test") enter code here def test(request): json_data= json.dumps({"query_id":"213"}) return HttpResponse(json_data, content_type='application/json') function call_ajax(){ $.post({ url: "{%url 'home:test'%}", data: { 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function (data) { console.log(data.query_id); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.responseText); } }); } -
Resize image when uploading with Pillow using ModelForm
Hey I have a following code but, it return no error but the image is not being resized, at the beginning it was 6.2 MB and after running the code it is the same: My model: class Photo(models.Model): user_name= models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) photo= models.ImageField() photo_name= models.TextField(max_length=300) def __str__(self): return self.photo_name def get_absolute_url(self): return reverse('photo:add_photo',{'pk':self.pk}) my Model.Form class PhotoForm(ModelForm): def clean_image(self): img = self.cleaned_data.get('photo') if not img: return img maxdim = 1024 if any(dim > maxdim for dim in img.image.size): # Resize too large image up to the max_size i = Image.open(img.file) fmt = i.format.lower() i.thumbnail((maxdim, maxdim)) # We must reset io.BytesIO object, otherwise resized image bytes # will get appended to the original image img.file = type(img.file)() i.save(img.file, fmt) return img class Meta: model = Photo exclude= ('user_name',) My views.py class PhotoCreateView(View): form_class = PhotoForm template_name = 'photo/photo_form.html' def get(self,request): form = self.form_class(None) return render(request,self.template_name,{'form': form}) def post(self,request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): return redirect('travel:main') return render(request, self.template_name,{}) Anyone knows why it returns no error but still the image has a same size. I want to upload my images on my app which is hosted on pythonanywhere.com and they have a limit of 512 MB storage which is … -
django - While using get_user_model for user creation
How do I override the .save() method for the model which uses get_user_model? forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): class Meta: fields = ("first_name", "last_name", "username", "email", "password1", "password2") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Username" self.fields["email"].label = "Email address" On creation of user I want to send user data into another model. As it has no written model (rather I'm importing it as from django.contrib.auth import get_user_model), how do I override the save method like- def save(self, *args, **kwargs): super(Model, self).save() Record.objects.create( employee_ID = self.employee_ID, first_name = self.first_name, last_name = self.last_name) where my Record model is - class Record(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) employee_ID = models.CharField(max_length = 20) -
Django: View with conditional login_required
Given the view, latest_objs, I wanted the view to require login conditionally if there is a parameter in the URL. The goal: If the URL passed is latest-objs, then return the non-authentication view with objs not related to any specific users. If the URL passed is latest-objs/mine, I want to require login if the user isn't authenticated, as that version of the view is supposed to return objs related to the authenticated user. Questions: Is the right way to do this to check request.GET.get('some-param')? How would I define these two scenarios in my urls.py file? Current I have this: url(r'latest-objs', views.latest_objs, name='latest_objs'), A little off-topic: I'm wondering if it's worth bothering with this, or simply creating two different views. -
How to use image that is stored to ImageField in the template?
I have the following the models.py: class Insurance(models.Model): area = models.CharField(max_length=100) title = models.CharField(max_length=50) insurance_type = models.CharField(max_length=50) area_photo = models.ImageField(upload_to='static/image') And this template: {% for product in insurance.insuranceproducts_set.all %} <li class="one_third btmspace-10 holder"> <figure><img src="{% static 'img/320x320.png' %}" alt=""> <div class="content"> <p><a href="{% url 'insurance:farmer_type' product.id %}">{{ product.title }}</a></p> </div> </figure> </li> {% endfor %} The problem is the page needs to load short description about the product. Here it needs load the image that is related to that insurance product. How can I do that? -
Allow duplicates in SlugRelatedField many-to-many relation
I have a SlugRelatedField set up as so: items = serializers.SlugRelatedField( slug_field='name', many=True, queryset=Item.objects.all()) Currently, I am sending a request to the database in the following form: { items: [ "item1", "item1", "item2", ] } However, if I query the same object then I get the following: { items: [ "item1", "item2", ] } How do I make it so that DRF will insert exactly what I send it and not remove duplicates. -
Getting a Model Foreign Key name and value?
I have the following model: class Item(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) I want to write a general function/utility to get the ForeignKey name and the value. In the code below I get the FK for field in self._meta.get_fields(include_parents=False): if isinstance(field, models.ForeignKey): How do I get the name(owner) and the value (owner_id) ? -
Get time from timestamp having timezone in Python
I am trying to get time values from the following datetime format "2018-08-28 11:30:37.490685+05:30" in python. I use Django rest framework. I tried using strftime and strptime but unable to get a solution. In the models the field is defined as: created_on = models.DateTimeField(default=timezone.now) -
What is the optimum file size for django error log. Does the large fiel size cause slowness of server?
The httpd server is taking 100% cpu. My log file size is 747 mB. Can this be the reason for high CPU usage? -
Django QuerySet OR with different annotations
When I retrieve two subsets of objects from the same model class MyModel and add different annotations to each (something to the first, other to the second -- neither of these attributes is a field in MyModel), I get strange results: mgr = MyModel.objects q1 = mgr.filter(pk=1).annotate(something= \ djdm.Value("is", output_field=djdm.CharField(null=True))) q2 = mgr.filter(pk=2).annotate(other= \ djdm.Value(123, output_field=djdm.CharField(null=True))) queryset = q1 | q2 print([(obj.pk, getattr(obj, 'something', 'NO_something'), getattr(obj, 'other', 'NO_other')) for obj in queryset.all()]) What I am getting is: [(1, 'is', 'NO_other'), (2, 'is', 'NO_other')] Questions: I would have hoped for None instead of the first 'NOother'. Is there a way to make Django add the other column from q2 to q1 in the OR? The second 'NO_other' is disappointing. Where did my 123 annotation go? The second 'is' is completely ridiculous. How can the something from q1 possibly creep over to q2?? That makes no sense. What is going on there? I am sure making some mistake here (at least I hope so), but which? -
Django type object 'Template' has no attribute 'objects'?
i am using Django 1.10.5. this error comes when i click on AttributeError at /rentacar/list/ Views @csrf_protect def rentacar_list(request, page_number=1): menu_config_list = MenuItemRentacarList.objects.all()[0] menu_config = MenuItemRentacarList.objects.get(id=menu_config_list.id) all_cars = Car.objects.all().order_by('-id') if menu_config.menu_item_rentacar_list_show_unavailable == 0: all_cars = all_cars.exclude(car_available=0) else: all_cars = all_cars cars_page = Paginator(all_cars, menu_config.menu_item_rentacar_list_pagination) args['cars'] = cars_page.page(page_number) template = Template.objects.get(template_default__exact=1) args['main_menu'] = MenuMenu.objects.get(id__exact=template.template_main_menu_id) args['menu_items'] = MenuItem.objects.filter( menu_item_menu=args['main_menu'], menu_item_published=1, ) template_page = template.template_alias + str("/rentacar/rentacar_cars_list.html") args['current_menu_item'] = menu_config.menu_item_rentacar_list_menu_item all_modules = Module.objects.filter( module_show_option__exact='all', module_published=1 ) selected_modules = Module.objects.filter( module_show_option__exact='selected', module_published=1, module_menu_item=args['current_menu_item'] ) excluded_modules = Module.objects.filter( module_show_option__exact='except', module_published=1, ).exclude( module_menu_item=args['current_menu_item'] ) args['modules'] = list(chain(all_modules, selected_modules, excluded_modules)) return render(request, template_page, args) Urls url(r'^rentacar/list/$', extension_views.rentacar_list), i am using template as a model and defining the template object and getting it from my template app.is there any easy way to render my template. Exception Location: D:\buggy\extension\views.py in rentacar_list, line 766 -
How trigger field changes in Django ORM
I have project written on Django. In another projects I use SQLAlchemy and I use very usefull method to trigger field change: @event.listens_for(ClassName.field_name, 'set') def func_name(target, value, oldvalue, initiator): if value == oldvalue: return In my Django project I have Order class: class Order(models.Model): PAYMENT_CHOICES = ( ('Paid', 'Paid'), ('Not Paid', 'Not Paid') ) EXECUTION_CHOICES = ( ('Done', 'Done'), ('In Progress', 'In Progress') ) name = models.CharField(max_length=255, default='') skype = models.CharField(max_length=255, default='') email = models.CharField(max_length=255, default='') status_of_execution = models.CharField(max_length=255, choices=EXECUTION_CHOICES, default='In Progress') status_of_payment = models.CharField(max_length=255, choices=PAYMENT_CHOICES, default='Not Paid') client_comment = models.TextField(blank=True, null=True) admin_comment = models.TextField(blank=True, null=True) total_price = models.IntegerField(null=False, blank=False, default=0) buyer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) status_of_execution field change only in admin panel, so I want to trigger when this field change and do something if it change on value Done. But I doesn't find solution like in SQLAlchemy, because Django only have signals like "pre_save, post_save ..." Can anyone know how can I resolve my problem using Django ORM? -
Create Database - PostgreSQL - Tom Aratyn's book
I am reading the Tom Aratyn Book - Building Django 2.0 web application. I am on a basic level. Before migrating my app to the database, he asks to create a database for our Django project. I didn't understand very well how to create this database, he didn't detailed the process. Follow what he says: " Now that we have a model, we will need to create a table in our database that matches it. We will use Django to generate a migration for us and then run the migration to create a table for our movie model. While Django can create and run migrations for our Django apps, it will not create the database and database user for our Django project. To create the database and user, we have to connect to the server using an administrator's account. Once we've connected we can create the database and user by executing the following SQL:" CREATE DATABASE mymdb; CREATE USER mymdb; GRANT ALL ON DATABASE mymdb to "mymdb"; ALTER USER mymdb PASSWORD 'development'; ALTER USER mymdb CREATEDB; I don't know where to type this line of code. Shell? I know his book uses the PostgreSQL database. Thank you, -
Dynamic multiple forms: Change select options based on previous select value
I dynamically generate additional forms on a page using Django Model Formsets. The user can generate as many forms as they need. This is done in a Vuejs method. My issue is changing the options of the second select of the form that the first select value was chosen. I was thinking about trying on focus or on click to get the select that was last changed, but I'm not sure how that would work. I do track the current count of forms on the page. In the example below. If the user changed form_select_0 to One, I need form_subselect_0 to only have options C and D, but the selects in form_1 should not be altered. Example: <form id = form_0> <select id="form_select_0"> <option value="one">One</option> <option value="two">Two</option> </select> <select id="form_subselect_0"> <option value="A">A</option> <option value="B">B</option> <option value="C">C</option> <option value="D">D</option> </select> </form> <form id = form_0> <select id="form_select_1"> <option value="one">One</option> <option value="two">Two</option> </select> <select id="form_subselect_1"> <option value="A">A</option> <option value="B">B</option> <option value="C">C</option> <option value="D">D</option> </select> </form> -
files add before after running server
when i run python manage.py runserver 8000 one file fuzzy.xml comes first and when i delete that file from that directory it send error /home/yelesee/Desktop/Mirab/Mirab/web/data/fuzzy.xml System check identified no issues (0 silenced). September 05, 2018 - 06:51:30 Django version 1.11, using settings 'Mirab.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C and the last line of error is File "/home/yelesee/anaconda3/envs/venv/lib/python2.7/xml/etree/ElementTree.py", line 647, in parse source = open(source, "rb") IOError: [Errno 2] No such file or directory: '/home/yelesee/Desktop/Mirab/Mirab/web/data/fuzzy.xml' i dont know where to serach and remove that from code. where should i find that?