Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Edit files trough sftp Django
First of all I'm new to Django. I have just installed Django using Digitalocean Ubuntu 16.04. So i started with writing my first Django app using this tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial01/ After editing some files I'm starting to realize that it is not very practical to use ssh for editing files. So i want to use SFTP. I saw in the documentation that their is a Django user with a password. But, because this is not to secure to use a password to login, I created a new user with sudo privileges and added a ssh-key to it. So when I logged-in as my new user using SFTP and editing a file I figured out that i cannot save files. I'm getting this error: Unable to save file: Permission denied So then I tried it with the Django user, same results: Unable to save file: Permission denied Then I tried it as root and successful. But I Don't want to change files through root but as my new user name. All the files are owned by Django user and the permissions of files and folders are 644 and 755. Anyone knows how to fix this? -
how can i pass three arguments in my djnago template tags filter?
i know how to pass two parameters in template tag filter in Django but bit confused how to confussed 3 parametrers. My template tags- @register.filter("status_of_booking") def status_of_booking(status,create_date,from_time): print create_date print status return 'hola' and i am passing three arguments like this and it is showing error:- {{ item.status|status_of_booking:item.classSession.date,item.id }} and the error it shows: status_of_booking requires 3 arguments, 2 provided -
Chain multiple prefetch_related with Prefetch object in a Queryset and get results in the templates
I have 3 models Company, Product and Images: class Product(Meta): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=file_upload_to) In the Company product listing page I need to get: information/data about the corresponding Product the first image for each Product In the Company View inheriting from DetailView: def get_queryset(self): qs = super().get_queryset() qp = Product.objects.prefetch_related(Prefetch('images', queryset=ProductImage.objects.all())) qh = qs.prefetch_related(Prefetch('products', queryset=qp)) return qs.prefetch_related(Prefetch('products', queryset=qp)) In templates can access: Product by using: {% for product in company.products.all %} Image related info, excepting urls : product.images.first.file_type Issues: using first is calling again in db for each product; bad - I used the 2 prefetch objects to avoid multiple calls in db; can't use first in queryset Prefetch object or slicing because will trow errors(can filter after slicing or the return is not a queryset) seems that I can't access the image/file url using: {{ product.images.first.url }} even if the other attributes can be access -
Two different user models, Dango REST
I need two different user models, an owner and a customer. Can i do it with Django REST framework? -
django add row to pagination
I have a pagination and want to add row number to it. How is that possible? I have tried the following codes: (as answered here: this answer) {{ forloop.counter.0|add:paginator.page.start_index }} and {{forloop.counter0|add:page_obj.start_index}} but this error was result: Failed lookup for key [paginator] in "[{'True': True, 'False': False, 'None': None}, {}, {}, {'filter_form': <MyFilterForm bound=True, valid=True, fields . . . . -
ImageField / FileField Django form Currently unable to trim the path to filename
I have a ImageField that stores in AWS S3 (similar to FileField). In the form, it has this "Currently" label that shows the image file path. I would like to trim and just show the filename. referring to the latest answer in Django : customizing FileField value while editing a model, I still cant get it to work. It shows "Currently" with the file path name like this: https://imgur.com/a/xkUZi form.py class CompanySettingEdit(forms.ModelForm): display_companyname = forms.CharField(max_length=50, required=True) company_logo = forms.ImageField(widget=CustomClearableFileInput) class Meta: model = Company fields = ("display_companyname","company_logo") model.py class Company(models.Model): display_companyname = models.CharField(max_length=50) company_logo = models.ImageField(upload_to=upload_to('company_logo/'), blank=True, null=True, storage=MediaStorage()) How can I have something like this: Currently: filename.jpg -
Setting liveserver port when running tests in django
I am using django for a webapp and I'm using docker to deploy it. I need to test it in the container with selenium. I'm using selenium grid for testing. In order to connect with the liveserver on the docker, i need to port forward a specific port, but as far as i read in the django docs, LiveServerTestCase uses port 0, which means random port every time i run the tests. Since --liveserver options is deprecated, is there any other way to set the port of the test server or a smarter way to test it with selenium ? Thanks in advance ! -
django links to the comment function in the backend does not work
After transfer the website to another server with higher python version stoped working the links in the backend to the comment function. Does somebody know where could the problem be? Thank you. -
Django, how to pass a variables from the Django admin to a template?
I want to be able to set a variable in the django admin panel, wich will be passed to the template as template variable, similar to placeholder in cms. (For exapmle when I save this variable in admin panel it will be rendered to the template) -
reusable app (package) in Django - how to add extra models
I am writing a small package that extends the django app that is used by many of my colleagues locally. So right now they can simply add it via pip, and then they add this extension in INSTALLED_APPS in settings.py. But the problem is that I can't add the new models to this extension (or at least I don't figure out yet how to do it correctly) because then the guys who would like to use my extension, have to sync their database or make migrations so their database contains the models needed for extension. Is it possible (and right thing to do) to add new models to the current django project 'silently' as soon as the user adds the app to INSTALLED_APPS? -
mysqlclient-python & security issues
I can't figure out whether I'll bear any risk in terms of malicious software & security if I download mysqlclient-python from here https://pypi.python.org/pypi/mysqlclient? Is mysqlclient-python provided in PyPI reliable in your opinion? I want to install mysqlclient in my global Python environment, not virtualenv. I've started learning Python. I want to try Django framework and Mysql database. I've already installed them. I know that PyPI is a third party repository, and everyone with a bit of experience can write and upload their package to PyPI. Is it safe to install mysqlclient, using pip and PyPI? -
Django 1.11 can we create relationship between tables from two different databases?
In my project I'm trying to create central DB service with multiple database so here my question is can we create relationship between tables from two different databases? Example: MySQL DB1.table user class User(models.Model): name = models.CharField() MySQLDb2.table post class Post(models.Model): title = model.CharField() user= models.Forignkey(User) -
make login panel without using models in django
def login(request): username=request.GET.get('uid') password=request.GET.get('upass') # print(username) # print(password) connection() query = "select * from idpassword where (U_name = '%s' & U_pass = '%s')" %(username,password) cursor.execute(query) U_id = cursor.fetchone() connect.commit() print(U_id) return HttpResponse(U_id) def connection(): try: global connect global cursor connect = mysql.connector.connect(host='localhost',database = 'advanceclasses',user = 'root',password = 'admin') cursor = connect.cursor() # print("connected!") except Error as e: print(e._full_msg) return HttpResponse("Connection is not Established !") Can you please help to solve this error? I am working with MY SQL and Django and at basic-stage. I got an error as programming-error. username: S12 and password: Sabc has already stored in table idpassword of the advanceclasses database. I want to find Unique-id of that table. Please help me -
use django_filters to filter for multiple arguments
I am using Relay, Django, Graphene Graphql. I would like to use django_filters to filter for multiple arguments of type on accommodation. This is described in my schema file and atm looks like: class AccommodationNode(DjangoObjectType) : class Meta: model = Accommodation interfaces = (relay.Node,) filter_fields = ['type'] This works perfectly if I pass a single string like: {"accommodationType": "apartment"}, but what if I want to filter for all accommodations that are apartments OR hotels? something like: {"accommodationType": ["apartment","hotel"]} This is my model: class Accommodation(models.Model): ACCOMMODATION_TYPE_CHOICES = ( ('apartment', 'Apartment'), ('host_family', 'Host Family'), ('residence', 'Residence'), ) school = models.ForeignKey(School, on_delete=models.CASCADE, related_name='accommodations') type = models.CharField( max_length=200, choices=ACCOMMODATION_TYPE_CHOICES, default='apartment' ) def __str__(self): return str(self.school) + " - " + self.type Is there any way I can do this without writing custom filters as are suggested here? For only one filter field this is a great solution but I'll end up having around 50 throughout my application including linked objects... -
How can I execute Python Django runserver command in Jupyter Notebook?
I am new for Python,Django & Jupyter Notebook. And I tried my best to search and study from StackOverflow and get the Python Django and Jupyter Notebook work together. But when I tried to execute the python manage.py runserver command in the cell and get error message such as syntax error. So can anyone help me to solve this problem. My environment is Windows 10 Pro x64 with Python 3.5 Django 2.10 Jupyter Notebook 4.0 -
Delete only some django user permission
Hi is it possible to remove all permissions only of some model. Example There is type A model permissions and type B model permission, need to clear all user permission of type A -
Many to Many relationship not working in Django REST framework
I am trying to create a simple Many to Many relationship. I have two models: IP and IPCollection, an IP can belong to 0 or more collections, and an IPCollection consists of IP addresses. After following the documentation, I thought I had got it to work. But I could not select existing IP addresses when creating a new collection in the API interface. Following this post: Lists are not currently supported in HTML input I managed to solve the problem, allowing me to create a new IPCollection while choosing between the existing IP's from a form. Everything seemed to be fine. However, once I implemented the solution provided in that stackoverflow post, a new problem occured: I can't retrieve my IPs anymore. I have my two endpoints: /ipcollections and /ips, and whenever I try to do a GET request to /ips I get the following error: TypeError at /ips/ __init__() takes 1 positional argument but 2 were given I have tried searching for a solution to this problem, but so far nothing seems to work. This is wat my serializers look like after implementing the solution from the other stackoverflow post: class IpSerializer(serializers.PrimaryKeyRelatedField, serializers.ModelSerializer): class Meta: model = Ip fields … -
How to create/update nested Serializers with Filefields
I have a python 3.6 + django 1.10 + djangorestframework 3.6.4 project. I have 2 Model classes called Report and ReportFile. I want to create the CRUD operations to get, post and put those files together with a report. 1 Report has a type (which doesn't really matter here) and can have many ReportFiles that the user should be able to upload. The modelclasses look like this: class Report(CreationModificationMixin): report_type = models.ForeignKey(ReportType, on_delete=models.SET_NULL, null=True, related_name='issues', verbose_name='Report', editable=False) name = models.CharField(max_length=50, blank=True) class ReportFile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) report = models.ForeignKey(Report, on_delete=models.CASCADE, related_name='files') uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='uploads', null=True) file = models.FileField(upload_to=upload_report_to, max_length=500) and the serializer class: class ReportSerializer(serializers.ModelSerializer): files = ReportFileSerializer(many=True) formats = serializers.SerializerMethodField() class Meta: model = Report fields = ('id', 'name', 'report_type', 'files') def create(self, validated_data): rfs_data = validated_data.pop('files') rf = Report.objects.create(**validated_data) for rf_data in rfs_data: ReportFile.objects.create(Report=rf, **rf_data) return rf and the ViewSet: class ReportViewSet(viewsets.ModelViewSet): serializer_class = ReportSerializer queryset = Report.objects.all().prefetch_related('report_type') But I cannot manage to upload the files correctly. Because first I cannot manage to upload that correctly with Postman and I somehow also doubt that this is the correct way to go. Can somebody hint me how I should do this? Thank you a lot! -
Queryset in __init__ Form Django
class PaymentSelectForm(forms.Form): date_from = forms.DateField() date_to = forms.DateField() website = ModelChoiceField() paymentmethod = forms.ChoiceField(choices=PAYCODE_CHOICES) def __init__(self, *args, **kwargs): super(PaymentSelectForm, self).__init__(*args, **kwargs) applyClassConfig2FormControl(self) self.fields['website'].queryset=Website.objects.all() I have errors: TypeError: __init__() missing 1 required positional argument: 'queryset'. How can I use Queryset in __init__ Form? -
How to paginate queryset for Serializer
I'm retreiving Category and its outfits list. My problem is there are too many outfits belong to a category. class CategoryListAPIView(generics.RetrieveAPIView): serializer_class = CategoryDetailSerializer ... class CategoryDetailSerializer(serializers.ModelSerializer): outfits = serializers.SerializerMethodField() ... class Meta: model = Category fields = ( ... 'outfits', ... ) def get_outfits(self, obj): //This is returning 39 items. // Can we paginate this? if obj.outfits is not None: return OutfitListSerializer(obj.outfits, many=True).data return None Can we paginate it so that user can first see 24 outfits and refresh to see the rest of outfits? -
How to temporarily dissable django-stronghold
How do i dissable the app django-stronghold temporarily?I want to make all my urls publicly avaiable again. Commenting out 'stronghold' in INSTALLED_APPS doesnt work. -
Posting array of objects in request in form-data in django api
I am using Django Restframework for apis. I am working on a POST api where I need to send an array of objects in form-data. When I tried it in raw data it is working perfectly. But when I use form-data in postman and placing the value in array, It is causing problem. The key value pair i am using in raw data is { "services": [ { "category_image": "", "category_name": "construction", "budget_min": "0-1000", "budget_max": "0-1000", "distance_min": "200", "distance_max": "500", "projects": [ { "category_image": "", "category_name": "residential", "sub_category": [ { "project_name": "single family", "project_image": "", "parent_id": "1" }, { "project_name": "multi family", "project_image": "", "parent_id": "1" }, { "project_name": "big family", "project_image": "", "parent_id": "1" } ] }, { "category_image": "", "category_name": "hospitality", "sub_category": [ { "project_name": "health care", "project_image": "", "parent_id": "5" }, { "project_name": "hotels", "project_image": "", "parent_id": "5" } ] } ], "sub_category": [ { "service_name": "wall", "service_image": "", "parent_id": "1" }, { "service_name": "kitchen", "service_image": "", "parent_id": "1" }, { "service_name": "outdoor", "service_image": "", "parent_id": "1" } ] }, { "category_image": "", "category_name": "driving", "sub_category": [ { "service_name": "car", "service_image": "", "parent_id": "5" }, { "service_name": "bike", "service_image": "", "parent_id": "5" } ] } ] } … -
Django import export - Unable to import model with BinaryField
I'm trying to import data for a model which has nullable BinaryField. The data doesn't contain the field and I want it to be imported with a null value in the field. If the field already exists in the database for a given id, it should keep the value as it is. I removed the field from the fields whitelist in the corresponding Resource object and added it to the exclude blacklist. However, I'm getting this error while importing - can't pickle memoryview objects. Traceback: Traceback (most recent call last): File "/lib/python3.5/site-packages/import_export/resources.py", line 451, in import_row original = deepcopy(instance) File "/lib/python3.5/copy.py", line 182, in deepcopy y = _reconstruct(x, rv, 1, memo) File "/lib/python3.5/copy.py", line 297, in _reconstruct state = deepcopy(state, memo) File "/lib/python3.5/copy.py", line 155, in deepcopy y = copier(x, memo) File "/lib/python3.5/copy.py", line 243, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/lib/python3.5/copy.py", line 174, in deepcopy rv = reductor(4) TypeError: can't pickle memoryview objects Package versions - django==1.11, django-import-export==0.6 -
Converting Tex to mathematical formula in the web post (python django)?
I first built my personal website using CMS (WordPress). I have many posts which including some mathematical formula. A plugin for wordpress website like latexpage can easily convert the Latex into mathematical formula inside my post. Recently, I re-build my website by Python Django, and I know one way to use Latex is to code a .tex template which is to generate a whole PDF using Python and Latex: my_latex_template.tex {% autoescape on %} \documentclass{article} \begin{document} {{ content }} \end{document} {% endautoescape %} But many times, I don't need to write a whole Latex PDF. I mean I only have a few mathematical formulas inside one post which need to use Latex. Like the question post in /tex.stackexchange.com/. You just write something like $ ... $ or $$ ... $$. My question: is there some quick way to achieve this? -
Concatenation and validation of fields (Django)
I'm retrieving some fields using list(queryset.values(*fields)) and I want to concatenate two fields to export it in xlsx file and also put some validations on fields. For example for q in queryset: fields =['fname', 'lname', 'speed'] list_dict = list(queryset.values(*fields)) h = ['fname', "lname", 'speed'] generate_xl("sample", h, list_dict, request) I want to print fname+lname together and also change the header name. For example h = ['fullname', 'speed'] And also put validation on 'speed' field before exporting to xlsx file . For example speed = locale.format('%.3f', q.speed) Expected Output in xlsx : [Harry-Potter, 0.563]