Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add django admin read-only permissions?
How to add read-only permissions in Model in django? By default there are three permissions available for users Can add, Can delete, Can change. How to add Can read permission in Model in Django. -
How do I store the uploaded file inside a folder having the name from the model field in django?
Using the upload_to argument of FileField I want to store the file uploaded by the user in a folder named TestNameie the test name entered by the user. I've written the following code, but it creates a folder named "models.CharField(max_length=255)" instead. How can I fix this? from django.core.validators import FileExtensionValidator from django.db import models from django.contrib.auth.models import User class TestInfo(models.Model): TestName = models.CharField(max_length=255) MaxMarks = models.IntegerField() TimeDuration = models.IntegerField() PosMarks = models.IntegerField() NegMarks = models.IntegerField() InputTextFile = models.FileField(upload_to='Tests/{}/'.format(TestName),\ validators[FileExtensionValidator(allowed_extensions['txt'])],blank=False) def __str__(self): return self.TestName -
Best way of get data from input and display in the same template on django
Summing Up At the moment i'm showing the data from database on a table. However i want the user fill the inputs, and when he click on a Insert Button, i pass the data from input, to the table and save in cache or memory. Note 1: the inputFields are extended from forms.py In that stage i have 2 another actions Save button, for cookies Send button, for save data in database. For now i am showing the database data like this: {% for doc in data %} {% for doc in documento %} <tr class="card-body"> <!-- Data1 --> <td class="col-auto"> <label type="search" class=""> {{ doc.data1 }} </label> </td> <!-- Data2 --> <td class="col-auto"> <label type="search" class=""> {{ doc.data2 }} </label> </td> <!-- Data3 --> <td class="col-auto"> <label type="search" class=""> {{ doc.data3 }} </label> </td> <!-- Data4 --> <td class="col-auto"> <label class="float-right"> R$ {{ doc.data4 }} </label> </td> </tr> {% endfor %} Questions: I need to use tags.py or filters.py for something like this?! it's possible do this only in template? I guess i shouldn't do busnisses code in templates. Can i manipulate HTML objects?(Like <input>) With Django views.py Note 2: I already tried some ways, like search resources to … -
How can I force scrapy to use postgres instead of a local sqllite database?
I set this line MySpider.custom_settings['JOBDIR'] = 'jobs/scrapy But now I have ran out of room on my EC2 instance, I get the error: “[Errno 28] No space left on device” The JOBDIR seems to be keeping track of what what scrapy spider has seen / not seen yet. Ideally I would use a postgres database to store this instead of JOBDIR, does anyone know how I can transfer this? Is there a setting I can set that points the JOBDIR storage to a table in a postgres DB, instead of this local sqlite file? Alternatively, is there a way I can just clear out some of the data without the spider having to start over from scratch? -
Django: How can I get a dictionary populated with form's fields?
I need to know if there's any way to get all the fields of a form in a dictionary. Form example: my_form.fields.all(); #or something like this (I know fields is not a form attribute, this is just an example) And put it into a dictionary like: my_form_dict = { 'field': 'value', } Is this possible? Thanks! -
Upload permissions for django firebrowser
Django filebrowser addon allows enabling or disabling file uploading for users. I generate top level directory for each user. How can i i allow him upload files only in this directories? I need something like classic unix '/home/user', with 755 but in django filebrowser So other users can see, but can not change. -
Type error to create and update my list in django rest framework
I'm trying to use my api to create and update products in a bundle. I did so: model.py class Product(models.Model): business = models.ForeignKey( on_delete=models.CASCADE, blank=True, null=True, ) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class Meta: verbose_name = "Product" class Bundle(models.Model): business = models.ForeignKey( on_delete=models.CASCADE, blank=True, null=True, ) name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) products = models.ManyToManyField(Product, related_name="bundles",blank=True, null=True, through="BundleProduct") class Meta: verbose_name = "Bundle" def __str__(self): return self.name class BundleProduct(models.Model): bundle = models.ForeignKey(Bundle, on_delete=models.CASCADE, related_name="bundleproducts") product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="bundleproducts") number = models.IntegerField(default=1) class Meta: verbose_name = "Bundle of Product" def __str__(self): return str(self.product.name) + " do " + self.bundle.name def get_absolute_url(self): return reverse("BundleProduct_detail", kwargs={"pk": self.pk}) And here is my serializers.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = "__all__" class BundleProductSerializer(serializers.ModelSerializer): class Meta: model = BundleProduct fields = "__all__" class BundleSerializer(serializers.ModelSerializer): class Meta: model = Bundle fields = "__all__" When I try to post some products in bundleproducts I receive "Incorrect type. Expected pk value, received list." Reading about this error, I found some issues relating to PrimaryKeyRelatedField and SlugRelatedField. I know I need to override but I have no idea how to do … -
A lifelong journey, are you up to it developers? [on hold]
I started a project 16 years ago to help people to get out of debt by showing them how to use their expenses to earn an income. I have done a lot of research and ask a lot of help but it seems to me that there is not a lot of people willing to help others to help themselves succeed in the end. I learned HTML, CSS, and Javascript at w3schools.com and create a few sites. Because I want to help businesses and individuals to create an extra income in areas where they never thought of is possible. I'm struggling to create a database that a hacker save, I jump from one platform of computer language to the another and I know enough to be dangerous, that only means that it's not enough to do it. Here is a link to the demo sites Advertron and Consumer Warehouse. As you will see it's a classified and e-commerce site. The e-commerce site will be a platform for all manufacturers, suppliers and vendors and whoever that want to sell their products and services. Advertron is the affiliate referral marketing company for Consumer Warehouse. Now I need to get these to totally … -
How to convert string to CharField
In my project there is an opportunity even for unauthorized users to leave a comment to a post. So, I have commentForm: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text',) and model: class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() If user is authorized, I want to substitute to author fileld username and don't show the input on page, otherwise site visitor should fill this input himself. I've tried to write this in appropriate view: if request.user.is_authenticated: form = CommentForm(request.POST, initial={'author': request.user.username}) But form.is_valid is false. Then I've tried: if request.user.is_authenticated: form.fields['author'] = request.user.username During form validating appeared 'string' object has no attribute 'disabled'. The question is how to deal with it the right way? Thanks. -
Django/Nodejs - upload large chunked files
i have a node server and a django server. I try to send large file from the node to the django server. I send the large file from node server by using fs.createReadStream() function. Each chunk created is send to the django server. I'am new in Django, so i don't know how to handle chunks. I tried to look the doc, but nothing seems clear for me. I need to store entire file in MEDIA_ROOT path. var output = fs.createWriteStream("../tmp_upload/" + pathname.split('/')[0] + ".zip"); archive.pipe(output); archive .directory('../tmp_upload/' + pathname.split('/')[0]) .finalize(); output.on('close', function(){ const stats = fs.statSync("../tmp_upload/" + pathname.split('/')[0] + ".zip") const fileSizeInBytes = stats.size let content = fs.createReadStream("../tmp_upload/" + pathname.split('/')[0] + ".zip") var chunk_sum = 0 var index = 0 content.on('data', chunk => { chunk_sum += chunk.length const data = { token: req.session.userToken, patientfile: { file: chunk.toString(), sumOfChunks: chunk_sum, fileSize: fileSizeInBytes, index : index, label: pathname.split('/')[0] + ".zip", category: "OT", } }; index += 1 Store.patientFileAdd(data) // here is where i send the chunk to django }); here is a part of my nodejs function class PatientFileAdd(views.APIView): permission_classes = (AllowAny, ) def post(self, request, *args, **kwargs): try: filedata = request.data['patientfile'] file = filedata['file'] file_start = filedata['index'] upload_folder = "/patient/patient_%s" % … -
What is advantage of formset with inline in django - admin.py?
There are two models DfHeaderInfo, DfInpValidation in django source code I am trying to understand. Both these models have foreign key to another model DfInpAdmin. Both these models are coming as tabularinline in the main DfInpAdmin form. But in the admin.py I can see DfHeaderInfo have DfHeaderInfoInline , DfHeaderInfoForm and corresponding formset DfHeaderInfoFormSet as well. But for DfInpValidation there is no corresponding formset. There is only DfInpValidationForm and `DfInpValidationInline'. I cant figure out what is the requirement or special functionality that using formset adds to DfHeaderInfo? I can update both models from DfInpAdmin in similar fashion. So what extra benfit formset provides? class DfHeaderInfoFormSet(BaseInlineFormSet): def get_form_kwargs(self, index): kwargs = super().get_form_kwargs(index) kwargs['parent_object'] = self.instance return kwargs class DfHeaderInfoForm(forms.ModelForm): class Meta: model = DfHeaderInfo fields = "__all__" def __init__(self, *args, parent_object, **kwargs): try: self.parent_object = parent_object print(self.parent_object) self.df_inp_fk = self.parent_object.df_inp_pk super(DfHeaderInfoForm, self).__init__(*args, **kwargs) self.fields['alias'] = forms.CharField( widget=forms.TextInput(attrs={'size': 30}), label="Alias Name", help_text='Alias of XPATH/Header)', required=False) self.fields['expression'] = forms.CharField( widget=forms.TextInput(attrs={'size': 30}), label="Expression", help_text='Expression for XPATH/Header)', required=False) except ObjectDoesNotExist as e: super(DfHeaderInfoForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = self.cleaned_data alias = self.cleaned_data.get("alias") if not alias: raise forms.ValidationError("Alias cannot be Blank") return cleaned_data class DfHeaderInfoInline(PaginationInline): model = DfHeaderInfo extra = 0 formset = DfHeaderInfoFormSet form = … -
Python Django Celery AsyncResult Memory Leak
The problem is a very serious memory leak until the server crashes (or you could recover by killing the celery worker service, which releases all the RAM used) There seems to be a bunch of reported bugs on this matter, but very little attention is paid to this warning, In the celery API docs, here Warning: Backends use resources to store and transmit results. To ensure that resources are released, you must eventually call get() or forget() on EVERY AsyncResult instance returned after calling a task. And it is reasonable to assume that the leak is related to this warning. But the conceptual problem is, based on my understanding of celery, that AsyncResult instances are created across multiple Django views within a user session: some are created as you initiate/spawn new tasks in one view, and some you may create later manually (using task_id saved in the user session) to check on the progress (state) of those tasks in another view. Therefore, AsynResult objects will eventually go out of scope across multiple Views in a real world Django application, and you don't want to call get() in ANY of these views, because you don't want to slow down the Django … -
How to write all logs of django console to to custome file file?
I just Started to try django logging module in my project... I am following django docs for loging all logs from Django’s default logging configuration to a custome log file. I copied the following code to my settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/project/debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } Here I assume that all of my console logs must be written in debug.log file, But its not happening. Can anyone please suggest me whata wrong here or is there any other way to do so? -
Django passing objects to a new template
Lets say I have a list of objects being displayed in HTML like so: {% for instance in object_info %} <li><a href="object">{{ instance.name }}</a></li> {% endfor %} And when an object is clicked, a new template will be shown with details about the clicked object. As I understand, this can be done by passing the objects primary key in the url. Is there another way to solve this problem without putting any additional information in the urls (ie. just passing the parameters to the next view)? -
How to insert element into a field with django
What would be the best way to insert a variable into a field in django, similar to insert element into a list in python. I am not trying to update a record field "first_name" in the database but rather "insert" or "add" a second "first_name" from someone else in the database that share the same last name. Ex: First Name Last Name Alan Smith Eric Jones Inna Smith Result: First Name Last Name Alan, Inna Smith, Smith Eric Jones Any help would be much appreciated. Thank you. -
How to remove Wagtail Core, Images, Documents from Django Admin
I have a project that uses a Django app and a Wagtail App. In my Django admin (localhost/django-admin/) I get Wagtail panels that I want to hide. How could I do that? -
Creating custom generics for get, update, delete and post with Django Rest Framework in Django
I am thinking of refactoring my code because I think I'm repeating too much ending up with lines of code. Take of this instance below I have implemented a class based view to GET,PUT,and DELETE for the Unit Model. Later I will create another view for Department to do CRUD and will follow the same pattern,is there a way I can make custom generic model views that can be dynamically used in any other view. class UnitDetailView(generics.RetrieveAPIView): """ Class based view for Unit Details. """ serializer_class = UnitSerializer queryset = Unit.objects.all() def get_object(self, pk, org_id=None): try: return Unit.objects.get(pk=pk, org_id=org_id) except Unit.DoesNotExist: raise Http404 def get(self, request, pk, format=None): """Get a unit instance.""" unit_obj = self.get_object(pk, org_id=get_auth(request)) serializer = UnitSerializer(unit_obj) return Response(serializer.data) def put(self, request, pk, format=None): """Update a unit instance.""" unit_obj = self.get_object(pk, org_id=get_auth(request)) serializer = UnitSerializer(unit_obj, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): """Remove a unit instance.""" unit_obj = self.get_object(pk, org_id=get_auth(request)) unit_obj.delete() return Response(status=status.HTTP_204_NO_CONTENT) -
Django rest framework best way to validate POST request parameters
When I receive a POST request on a Django rest framework APIView class, I would like to filter/validate the parameters that are passed to prevent to be modified. For example, for this serilizer: class MediaSerializer(serializers.ModelSerializer): class Meta: model = Media fields = ('id', 'title', 'content', 'url', 'createdByUser', 'karma', 'type', 'issue', 'creationDate', 'updatedDate') Some parameters such the id, creationDate or createdByUser shouldn't be modified. So for my class class MediaDetail(APIView) I have: def validateRequest(self): user = self.request.data.get('createdByUser', None) karma = self.request.data.get('karma', None) creationDate = self.request.data.get('creationDate', None) if user is not None or karma is not None or creationDate is not None: return Response(status=status.HTTP_400_BAD_REQUEST) @method_decorator(login_required) def post(self, request, pk, format=None): self.validateRequest() media = self.get_object(pk) self._throwIfNotMediaAuthor(media, request.user) serializer = MediaSerializer(media, data=request.data) if serializer.is_valid(): # serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Is there a better way to make this validation? Maybe on the serializer? I didn't found enough documentation -
Django Rest Framework urls.py getting messed up
I am having my models.py file defined as below:- from django.db import models from django.contrib.auth.models import User class Custom_User(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=20) REGISTRATION_CHOICES = ( ('Learner', 'Learner'), ('Trainer', 'Trainer'), ) primary_registration_type = models.CharField(max_length=15, choices=REGISTRATION_CHOICES) def __str__(self): return self.user.email As you can see that my Custom_User model uses Django's User model as its foreign Key. For the above model I have defined my serialziers.py file like this:- from django.contrib.auth.models import User from rest_framework import serializers from .models import * class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email') class Custom_UserSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: model = Custom_User fields = ('__all__') Now I am using this serializers in my viewsets like below:- from django.contrib.auth.models import User from rest_framework import viewsets from .serializers import * class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() serializer_class = UserSerializer class Custom_UserViewSet(viewsets.ModelViewSet): queryset = Custom_User.objects.all() serializer_class = Custom_UserSerializer class TrainerViewSet(viewsets.ModelViewSet): queryset = Custom_User.objects.filter(primary_registration_type="Trainer") serializer_class = Custom_UserSerializer class LearnerViewSet(viewsets.ModelViewSet): queryset = Custom_User.objects.filter(primary_registration_type="Learner") serializer_class = Custom_UserSerializer And Finally inside my urls.py file I register them as below:- from rest_framework import routers router = routers.DefaultRouter() router.register(r'users', api_mailing_list_views.UserViewSet) router.register(r'custom_users', api_mailing_list_views.Custom_UserViewSet) router.register(r'trainers', api_mailing_list_views.TrainerViewSet) router.register(r'learners', api_mailing_list_views.LearnerViewSet) … -
django same localhost not responding in another browser or second instance
my new created django project working fine with this information Django version 2.1.7, using settings 'django_server_api.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. running fine then i opened in one browser is loaded quickly working quickly. but if i open same local host in another browser it is taking more than 5 minutes, i dont know what is the issues? may be django is like this? or do i need to change any config in the setting,py file ? -
How can I build a pinterest like photo picker with django?
I am building a django application where users can upload multiple images and store it as an album. In my current implementation, I have two models Photo and Album. In the Album model I have a many-to-many field to the Photo model. Thus, a user can select multiple photos in the Album model. Is there a way by which I can implement a photo picker in Album model instead of a simple many-to-many field? Here is my code: class Photo(models.Model) : def get_gallery_path(self, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return 'static/uploads/images/gallery/' + filename uploader = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=date.today) image = ProcessedImageField(default='', verbose_name='Image', upload_to=get_gallery_path,validators=[validate_file_size], **processed_image_field_specs) caption = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return str(self.id) + str(self.uploader.username) + str(self.date) class Meta: verbose_name_plural = "Photos" verbose_name = "Photo" class Album(models.Model) : title = models.CharField(max_length=200) uploader = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=date.today) description = models.TextField(null=True, blank=True) tags = models.ManyToManyField(Tag, blank=True) category = models.ManyToManyField(Category, blank=True) photos = models.ManyToManyField(Photo, blank=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Albums" verbose_name = "Album" PS: I am only using the built-in admin interface to store data. -
Django: Pass form data through Ajax
I'm creating a "well-dynamic" form list in my "configurations" area on my webpage with django. I will explain how does this works. I have a Django class called configurations, its table looks like: +--+----+----------------------+---------------------------------------+---------------------------------+-----+------------------------------+ |id|user| title | body | form | form_instance |class| update_fields | +--+----+----------------------+---------------------------+-----------+---------------------------------+-----+------------------------------+ |0 |John|Profile Configurations|Configure your profile here|ProfileForm|ProfileForm(instance=my_instance)| User|(name=forms.cleaned_data...etc| +--+----+----------------------+---------------------------------------+---------------------------------+-----+------------------------------+ So I have a Django view rendering all this table info and an Ajax sending the post to a Django view. These views are dynamic, per every row I add to this table, my Configurations view will render a new form with another new configuration option that I can configure directly from the DB. It's working perfect so far at this point. The problem comes when Ajax sends its data to the Django's ajax receiving form. def validate_config(request): form = request.POST.get('form', None) class = request.POST.get('class', None) var_valid = request.POST.get('var_valid', None) update_fields = request.POST.get('update_fields', None) data = { 'form': eval(form), 'class': eval(class), 'update_fields': eval(update_fields), 'var_valid': eval(var_valid), } form = data['form'](request.POST) if request.is_ajax(): print('This is an Ajax post method. ') var1 = data['var_valid'] # my_filter = {} my_filter[var1] = request.session['username'] item = data['class'].objects.filter(**my_filter).update(update_fields) Almost everything works properly. Form view is being rendered properly, validate_config view is filtering the … -
django single form two models with Foreign Key __init__() got an unexpected keyword argument 'isinstance'
I Apologize for possibly stupid question, I am new to coding and I not even sure if this is the best way to do it. Here is my problem, I would really appreciate any help. I have Question and Answer models related by foreign key. In the admin panel I applied inlines to list answer choices corresponding to the question with the following lines: class QuestionAdmin(admin.ModelAdmin): list_display = ('content', 'subject','exam') inlines = [AnswerInline] Data entry through admin panel works well. To the best of my understanding the rule of thumb is not to give admin access to users. Therefore, I am creating a form to insert questions and related choices in a template. Please have a look at the codes below forms.py class QuestionEntryForm(forms.ModelForm): class Meta: model = Question fields = ['exam', 'subject', 'figure', 'content','solution'] views.py def QuestionChoiceCreateView(request): ChoiceFormSet = inlineformset_factory(Question, Answer,fields=('choice','correct'),extra=4) if request.method == "POST": qform = QuestionEntryForm(request.POST) formset = ChoiceFormSet(request.POST,isinstance=qform) if all( [qform.is_valid(), formset.is_valid()]): print("all validation passed") qmodel = qform.save() for inline_form in formset: if inline_form.cleaned_data: choice = inline_form.save(commit=False) choice.question = qmodel choice.save() return render(request, 'dataentry.html',{'questionsub':'question submitted succefully'}) else: qform = QuestionEntryForm() formset = ChoiceFormSet() return render(request, "dataentry.html", {'qform': qform,'formset':formset}) template {% extends "base_generic.html" %} {% block content … -
uwsgi and CSRF_TRUSTED_ORIGINS nin django
I have a problem with uwsgi and the CSRF verification. I have set up the domain in my settings.py like: CSRF_TRUSTED_ORIGINS=['https://example.com'] and this also works with python manage.py runserver, but when I use uwsgi I get the error message: Reason given for failure: Referer checking failed - https://example.com/ does not match any trusted origins. It is actually complaining about the exact domain that I have setup in the CSRF_TRUSTED_ORIGINS list, how can that be? And why does it work with the django runserver? -
html, css, JavaScript building a hybrid app
Html, CSS, JavaScript are all used to build hybrids app and Cordova which wraps it into a native application, so my questions is do I also need to learn a server side languages like e.g python/Django etc to create a hybrid app?