Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need help implementing django user defined table
I am developing a work management tool with Django. The tool is a general domain tool (any industry can use it), so there is no fixed table called "tasks" or "projects". I have a table called "tables" and another table called "table_details". In table, id will have the user-defined tables/entities and in table_details, i will have the structure of those tables. We need a 3rd table for the entities data. I am not getting how to achieve this.. I tried a lot to do it. I didn't find any tutorial for this to user Need to be able to dynamically add User-Defined fields of any data type. Can anyone help me with how i can solve this problem with Django? Thanks -
Django file upload returns None
I' trying to upload the image file using Django. I'm able to get the other form data but not the image file. request.FILES is blank. Below is my code. models.py class Module(models.Model): title = models.CharField(max_length = 50) slug = models.CharField(max_length = 50) description = models.TextField(max_length = 500) Forms.py class ModuleAddForm(forms.ModelForm): title = forms.CharField(max_length = 50, widget = forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Title'} )) description = forms.CharField(max_length = 50, widget = forms.Textarea(attrs = {'class': 'form-control', 'placeholder': 'Description'} )) image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) class Meta: model = Module fields = ['title', 'description', 'image'] Views.py form = ModuleAddForm(request.POST, request.FILES or None) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] image = request.FILES['image] When I print request.FILES it returned blank and also when I tried to get it using Key it returned MultiValueDict error. But when I print request.POST, image was there. But it was of no use because an image wasn't uploaded. I'm using another model to store the image files of this model (Module) because it can contain multiple images. I've implemented the same logic in my other model and function. It's working there properly but not working here. Please help me with this. I'm using Django 2.2 -
How can I render a template and link to a particular section of the page?
In my question_detail_solution.html I have got this div: <div id='answer'></div> When I render the template in views.py I want something like an html anchor link to this div. What is the solution? This doesn't work: return render(request, 'tasks/question_detail_solution.html#answer', context) -
Is there a way to change language in django-mdeditor
I'm using django-mdeditor and it works fine just as i expect the only problem is the language. I believe its Chinese. How can I change it to English? -
Is Django framework a good fit for my use case?
I just came to learn about Django. I am going through the tutorials to learn some of its features but I wanted to get some basic idea of whether it can satisfy my use case. Problem Statement - We need to process a large number of files (say 2000) on a farm of linux machines to convert them from format A to format B. To do that, the user will take the following actions. Go to a website (landing page), and select a product. A form show up. Fill out the form and submit the files. At the backend (Linux), we will do some sanity checks on the files first. If the checks pass, the files will be "submitted" for processing, and we want to show a dynamic dashboard/status page of all the files. If the sanity checks fail, we want to send an email to the user that their submission failed. In order for the file processing to work, we need to maintain some configuration information in a DB (say MySQL or SQLite). We want the user to be able to add/modify/delete this information through the web interface using some sort of form or lightweight DB editor. We also … -
Save binary file through multipart curl
I want to save a file into binary field and some other details through DRF post request. Below is my code: class TestUpload(models.Model): id = models.AutoField(primary_key=True, editable=False) code = models.CharField(max_length=64) name = models.CharField(max_length=128) description = models.CharField(max_length=1024) data = models.BinaryField() class WidgetRoutingConfigViewSet(APIView): parser_classes = (MultiPartParser, FormParser,) def post(self, request, format=None): serializer = TestUploadSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({'received data': request.data}) class TestUploadSerializer(serializers.ModelSerializer): class Meta: model = wm.TestUpload fields = [ 'code', 'name', 'description', 'data', ] Below is my postman curl code: curl -X POST \ http://localhost:80/testupload/ \ -H 'cache-control: no-cache' \ -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \ -H 'postman-token: 447d7078-faa5-37e9-30ae-5ade00e626e6' \ -F code=code \ -F name=name \ -F 'description=Description' \ -F data=@test.js With the above code the row in the database successfully added to the database but the data column is empty so the file is not inserted. What am i missing ? -
form Choice Field not updating immediately when the QuerySet is loaded form view
I have a ModelChoiceField in forms and I want to fill it based on customized QuerySet form View. The QuerySet will be added to ModelChoiceField if I refreshed the page how can I passes it immediately without refreshing? I tired to add the QuerySet in the forms.py class but I couldn't because I need the request.user and I can't get it form here. in forms.py I have this departments = forms.ModelChoiceField(queryset=Department.objects.none(), required=True, label=_('department')) and in View.py I did this department_ids.append(self.request.user.profile.department.key) for department in departments_list: if department.get_level_number > current_user_department.get_level_number: if department.is_inheritance(current_user_department): department_ids.append(department.key) department_ids = map(str, department_ids) department_queryset = departments_list.filter(key__in=department_ids) context['form'].base_fields['departments'].queryset = department_queryset return context I want the ModelChoiceField filled immediately without refreshing the page how can I do that? -
Change Function + ajax cant send value parameter from select box to django views (to make a dependent dropdown)
So i have 2 select box , first select box has a list of schema that the database has (i use oracle in DBEAVER) so the directory is like Oracle - databasename |Schema |A |B |C |D |E |Tables |POLLS_TableAll |DJANGO_ADMINUSER |etc |Views |Sequence |Types |etc |F |G polls_tableall has 2 attribute , table_id and table_name that we insert the data manually depends on list of schema and we put the table id increment tableid table_name 1 A 2 B 3 C 4 D 5 E 6 F 7 G 8 H so what i want is to make a dependent select box (dropdown list) the first dropdown has a list of table_name(which i already finish it) when i choose for example 'E' the second dropdown will show the POLLS_TableAll , Django_Adminuser , etc models.py import datetime from django.db import models from django.utils import timezone from django import forms class TableAll(models.Model): table_name = models.CharField(max_length=250) views.py from django.http import Http404 from django.shortcuts import get_object_or_404, render, redirect from django.template import loader from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views import generic from django.utils import timezone from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib import messages … -
Return AJAX message after view has been performed
I have a Django project on which I am uploading files to a sql server. I would want to show only a text message when the operation has been succeded, without refreshing the page I did not succeed to corelate the view with the AJAX and HTML form. views.py: def upload(request): if request.method == "POST": try: form = UploadFileForm(request.GET, request.FILES["excel_file"]) file = request.FILES['excel_file'] Import_Resource = resources.modelresource_factory(model=item)() dataset = tablib.Dataset() if not file.name.endswith('.xlsx'): messages.error(request, 'This is not a excel file!') if filename1 in file.name: imported_data = dataset.load(file.read(), format='xlsx') item.objects.filter(input_type = 'traitement').delete() for row in dataset: ITEM2 = item() ITEM2.input_type = 'traitement' ITEM2.no_incident = row[1] ITEM2.action = row[2] ITEM2.week = row[4] ITEM2.status = row[5] ITEM2.assigned_by_group = row[6] ITEM2.description = row[0] ITEM2.previous_group = row[7] if isinstance(row[3], float): ITEM2.date_action = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(row[3]) - 2) else: ITEM2.date_action = row[3] if isinstance(row[8], float): ITEM2.date_end = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(row[8]) - 2) else: ITEM2.date_end = row[8] ITEM2.save() data = { 'file': file.name } return JsonResponse(data) urls.py: url(r'^input/$', views.inputprocess, name='inputprocess'), html file: <form action="{% url "upload" %}" method="POST" enctype="multipart/form-data" class="form-inline" style="margin-left: 50px"> <div class="form-group mb-2"> {% csrf_token %} <input type="file" name="excel_file" id="excel_file" required="True"> </div> <div class="form-group mb-2"> <button class="btn btn-primary" id="likebutton2"> <span class="glyphicon glyphicon-upload"></span>Upload</button> … -
How to get the content type model name using the slug field
I would like to get the model name using the slug field. This is a module table. Each module having different tables. So I would like to create a global function for inline grid editing . But for that I need a modal name according to the modules. So I can pass the slug name through java script. But I need to filter the content type models using the slug field Here is my code class Module(BaseModel, SoftDeletionModel): id = models.AutoField(primary_key=True) name = models.CharField( _("Module Name"), max_length=50, default=False, unique=True) slug = models.SlugField(unique=True) display_name = models.CharField( _("Display Name"), max_length=50, default=False) content_type = models.ForeignKey(ContentType, blank=True, null=True, on_delete=models.CASCADE) parent_module_id = models.ForeignKey("Module", blank=True, null=True, on_delete=models.CASCADE) order = models.IntegerField(_("Order"), default=0, blank=True, null=True) class Meta: db_table = 'modules' def __str__(self): return "{0}".format(self.display_name) -
Get instance of a model to be used as foreign key to add data to other model in Django
I have a relationship model that maps two models that is my user and its position as mentioned. Here Emp_position is that relationship model. class Position(models.Model): position_name = models.CharField(max_length=20, unique=True) def __str__(self): return self.position_name class Emp_position(models.Model): emp_uname = models.OneToOneField(User, related_name='emp_name', to_field='username', on_delete=models.CASCADE) position_name = models.ForeignKey(Position, related_name='position', to_field='position_name', on_delete=models.CASCADE) def __str__(self): return str(self.emp_uname) + " " + str(self.position_name) Now to insert data to Emp_position I need instance of user and Position. I was able to get the user model instance easily using the user.username field but how do I get instance of position. The position instance, I am deriving using some logic by using the filter function. How do I get the instance which function helps me in getting the instance using some condition. Here is what I have tried : emp_pos = Emp_position(emp_uname = user, position_name = Position.objects.filter(position_name="COMES FROM LOGIC").first() emp_pos.save() But this is not saving the model. -
How to exclude a foreign's key field from a form
Having my models Yacht and Offer, I created an intermediate table OfferHasYacht in order to connect a yacht with an offer. I have already created instances for both models. I want to exclude in my form the field date_created from the Offer model because when I am trying to included it in my form it gives an error of : TypeError: __str__ returned non-string (type datetime.datetime) In order to avoid this, I want to exclude only this field and not the notes field from my offer model. How can I do that? models.py class Yacht(models.Model): name = models.CharField(max_length=50, verbose_name="Name") price_per_day=models.DecimalField("Price(€) / Day", max_digits=8, decimal_places=2, default=0,blank=True) passengers = models.IntegerField("Passengers",blank=True,null=True) def __str__(self): return self.name class Offer(models.Model): date_created = models.DateTimeField("Date of Offer", null=True,blank=True, default=datetime.datetime.now) notes=models.CharField("Notes",max_length=100, blank=True) def __str__(self): return self.date_created class OfferHasYacht(models.Model): offer=models.ForeignKey(Offer,null=True,verbose_name="Offer",on_delete = models.CASCADE) yacht=models.ForeignKey(Yacht,null=True,verbose_name="Yacht",on_delete = models.CASCADE) def __str__(self): return self.yacht.name forms.py class OfferHasYachtForm(ModelForm): class Meta: model = OfferHasYacht #exclude=('',) fields = ('yacht','offer',) With this solution it raises the error :TypeError: str returned non-string (type datetime.datetime) How can I exclude the date_created field of Offer model? -
Retrieving information from a POST without forms in Django
I'm developing something like an API (more like a communications server? Idk what to call it!) to receive data from a POST message from an external app. Basically this other app will encounter an error, then it sends an error ID in a post message to my API, then I send off an email to the affected account. My question is how do I handle this in Django without any form of UI or forms? I want this to pretty much be done quietly in the background. At most a confirmation screen that the email is sent. I'm using a LAMP stack with Python/Django instead of PHP. -
django form with dynamic queryset ModelMultipleChoiceField
I'm trying to pass a queryset to a forms ModelMultipleChoiceField as an initial value. I want to send a filtered queryset as all the choices and an initial selection. It seems to fail is_valid. Can anyone tell me what I'm doing wrong? forms.py class sendListForm(forms.Form): recipients = forms.ModelMultipleChoiceField(queryset = CustomUser.objects.all()) title = forms.CharField(max_length=100,required=True) description = forms.CharField(max_length=500,required=False,widget=forms.Textarea(attrs={'cols': 20, 'rows': 4})) extraInfo = forms.CharField(max_length=500,required=False, help_text='Add a message to send',widget=forms.Textarea(attrs={"rows":4, "cols":20}),label='Extra Message') startDate = forms.DateField(required=False,widget=forms.HiddenInput()) startTime = forms.TimeField(required=False,widget=forms.HiddenInput()) endDate = forms.DateField(required=False,widget=forms.HiddenInput()) endTime = forms.TimeField(required=False,widget=forms.HiddenInput()) yearName = forms.CharField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): recipients = kwargs.pop('recipients') super(sendListForm, self).__init__(*args, **kwargs) self.fields['recipients'] = forms.ModelMultipleChoiceField(queryset=recipients) views.py def eventSendList(request, modelPk=None): event = get_object_or_404(Event, pk=modelPk) if request.method == 'POST': form = sendListForm(request.POST,recipients=CustomUser.objects.all()) if form.is_valid(): print('valid') baseInfo = { 'recipients':recipients, 'title':event.title, 'description':event.description, 'startDate':event.startDate, 'startTime':event.startTime, 'endDate':event.endDate, 'endTime':event.endTime, 'yearName':event.yearName.name, } classParents = CustomUser.objects.all() form = sendListForm(initial=baseInfo,recipients=classParents) return render(request, 'page/sendListForm.html',{'form':form}) It never gets past the "if form.is_valid():" in the view. -
contactus() got an unexpected keyword argument 'name'
I have created a contact form and fields are name, email, and dropdown.When I am submitting a form then I a getting error but If I print(name) then it's displaying on the terminal. contactus() got an unexpected keyword argument 'name' Would you help me out with this? contatus.html <form action="/contactus/" method="post"> {% csrf_token %} <div class="input-block"> <input id="name" name="name" type="text" placeholder="your full name" class="form-control"> </div> <div class="input-block"> <select name="year" id="year" class="form-control"> <option selected disabled>no of Year</option> <option value="1">1 Year</option> <option value="2">2 Year</option> </select> </div> <div id="reachEmail" class="input-block"> <input id="email" name="email" type="email" class="form-control" placeholder="email"> </div> <input type="submit" name="Send" value="SEND"> </form> view.py def contactus(request): if request.method=="POST": name=request.POST.get('name','') year=request.POST.get('year','') email=request.POST.get('email','') contact=contactus(name=name,year=year,email=email) contact.save(); return render(request,'demo1/contactus.html') Model.py class contactus(models.Model): id=models.AutoField(primary_key=True) name = models.CharField(max_length=30) year = models.CharField(max_length=30) email = models.CharField(max_length=30) admin.py from .models import contactus admin.site.register(contactus) -
Guidance on the best up-to-date tutorial for integrating Django + Webpack + VueJS + Vue-Cli
I would like to have guidance on which is the best up-to-date tutorial for integrating Django + Webpack + VueJS + Vue-Cli. I have successfully gone through the following tutorials. Just wanted to know, which of these are recommended or is there any other latest tutorial/method that I need to keep in mind before proceeding. https://github.com/michaelbukachi/django-vuejs-tutorial/wiki/Django-Vue.js-Integration-Tutorial https://medium.com/@rodrigosmaniotto/integrating-django-and-vuejs-with-vue-cli-3-and-webpack-loader-145c3b98501a https://www.jamesbaltar.com/django-webpack https://ariera.github.io/2017/09/26/django-webpack-vue-js-setting-up-a-new-project-that-s-easy-to-develop-and-deploy-part-1.html Your guidance would be appreciated. -
Django query to Postgres returning wrong column
I'm facing a strange problem maybe related with some cache that I cannot find. I have the following Models: class Incubadores(models.Model): incubador = models.CharField(max_length=10, primary_key=True) posicion = models.CharField(max_length=10) class Tareas(TimeStampedModel): priority = models.CharField(max_length=20, choices=PRIORITIES, default='normal') incubador = models.ForeignKey(Incubadores, on_delete=models.CASCADE, null=True, db_column='incubador') info = JSONField(null=True) datos = JSONField(null=True) class Meta: ordering = ('priority','modified','created') I previously didn't have the argument db_column, so the Postgres column for that field was incubador_id I used the argument db_column to change the name of the column, and then I run python manage.py makemgrations and python manage.py migrate, but I'm still getting the column as incubadores_id whenever I perform a query such as: >>> tareas = Tareas.objects.all().values() >>> print(tareas) <QuerySet [{'info': None, 'modified': datetime.datetime(2019, 11, 1, 15, 24, 58, 743803, tzinfo=<UTC>), 'created': datetime.datetime(2019, 11, 1, 15, 24, 58, 743803, tzinfo=<UTC>), 'datos': None, 'priority': 'normal', 'incubador_id': 'I1.1', 'id': 24}, {'info': None, 'modified': datetime.datetime(2019, 11, 1, 15, 25, 25, 49950, tzinfo=<UTC>), 'created': datetime.datetime(2019, 11, 1, 15, 25, 25, 49950, tzinfo=<UTC>), 'datos': None, 'priority': 'normal', 'incubador_id': 'I1.1', 'id': 25}]> I need to modify this column name because I'm having other issues with Serializers. So the change is necessary. If I perform the same query in other Models where I've also … -
Django 2.1 : Render JSONresponse to template, byte string doesn't work with javascript
In view: response = JsonResponse(available_lessons, safe=False) In template: var available_lessons_json = {{available_lessons_json.content|safe}} In my source js file I see: var available_lessons_json = b'{"courses": {"courseName": "Everyday English", "lessons": ["Phrasal Verbs I", "Phrasal Verbs II", "Phrasal Verbs III"]}}' which is giving me the error "Uncaught SyntaxError: Unexpected string" -
set value of new field depending on other field
i want setting value of new field depending on other field . First Try: my model.py: class Post(Model): title = models.CharField( max_length=100) like_count = models.IntegerField(default=0) and now i want adding new field to Post's model that shown me is post liked yet or not: class Post(Model): title = models.CharField( max_length=100) like_count = models.IntegerField(default=0) like_status = models.BooleanField(default=False if str(F('like_count')) == 0 else True) after running migration ,all value of like_status is True while exist some Post's object with like_count=0 second try: adding like_status with False default value: class Post(Model): title = models.CharField( max_length=100) like_count = models.IntegerField(default=0) like_status = models.BooleanField(default=False) then trying updating like_status field : Post.objects.all().update(like_status=True if F('like_count')>0 else False) the error: '>' not supported between instances of 'F' and 'int' and trying : Post.objects.all().update(like_status=True if int(F('like_count'))>0 else False) error: int() argument must be a string, a bytes-like object or a number, not 'F' i can achieve my goal by running script but i want know the way of doing this process without scripting.thank you for your time -
Django: How to ignore parts of code in a function when testing
I don't care what some_other_functipn_2 and some_other_function does. I just need to assert that test_target is called. This is a simplified version of my code. I know this can be done by patching but my code just has too many parts to patch. Is there anyway to ignore everything else except the target? def abc(): a = some_other_function() b = some_other_functipn_2(a) test_target(b) -
Django Angular Social Medial authentication
I am working on app where user can log-in using your Facebook or any social media account in angular side. I am comfortable with the django framework and AngularJS. But in my application user can only login r signing with social media account. so how do I manage authentication mechanism with facebook. I am expecting some direction so that I can go forward with the app. -
Form data not saving in databse in Django
I have a test from which needs to be save in database. When I submit the form it does not save anything in database. If anyone can review my code and check what's wrong inside the code that's stopping the form to save in database. **Model** class test(models.Model): testname = models.CharField('Name', max_length=50, help_text='Co-worker name.', default='') testPicture = models.ImageField('Co-Worker Picture', upload_to='../media/images/co-woker-pictures' , help_text='Co-worker Picture.', default='', null=True, blank=True) joiningDate = models.DateField('Joining Date', help_text='Joining Date of Co-worker', default=datetime.date.today, ) **form** class testForm(forms.ModelForm): testname = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control formInput', })) testPicture = forms.ImageField(widget=forms.FileInput(attrs={ 'class': 'form-control formInput', })) joiningDate = forms.DateField(widget=forms.DateInput(attrs={ 'class': 'form-control formInput', 'id': 'datePicker', })) class Meta: model = test fields = ['testname', 'testPicture', 'joiningDate'] **view** def test(request): if request.method == 'POST': form = testForm(request.POST, request.FILES) if form.is_valid(): u = form.save() messages.success(request, 'test successful.') return redirect('test', ) else: form = testForm() c = context = ({ 'form': form, }) return render(request, 'test.html', c) -
when to use BaseFilterBackend in django?
I am new to Django and was trying to understand the use of BaseFilterBackend. Why and when to use? class test(APIView): class SimpleFilterBackend(BaseFilterBackend): def get_schema_fields(self, view): return [coreapi.Field(name='Area', location='query', required=False, type='string'), coreapi.Field(name='Quarter', location='query', required=False, type='string'), coreapi.Field(name='Role', location='query', required=False, type='string')] filter_backends = (SimpleFilterBackend) -
Error (AppRegistryNotReady) running test cases with Django inside a Docker container using PyCharm
I read a similar solution posted here: https://intellij-support.jetbrains.com/hc/en-us/community/posts/360002753800-Django-console-not-working-properly-on-docker And I have implemented the above solution. The strange thing is I can open a Django Console in PyCharm without error. And I've confirmed that the Django Console is running inside my Docker container by executing the following: >>> import socket >>> socket.gethostname() 'f6f418ce5d14' I have an entry point script (bash script), which executes the following inside the Docker container without error: python manage.py migrate python manage.py loaddata --format json /srv/app/api/opp/management/fixtures/dev.json But, when PyCharm attempts to execute the test cases, using PyCharm's own nose test runner, that's when the error appear. The following is an excerpt from PyCharm's output when running the Django test cases using a Docker container: app_1 | Installed 127 object(s) from 1 fixture(s) app_1 | app_1 | Launching Nosetest with arguments /opt/.pycharm_helpers/pycharm/_jb_nosetest_runner.py /srv/app/api/opp/tests in /srv/app/api app_1 | app_1 | app_1 | app_1 | app_1 | app_1 | app_1 | app_1 | app_1 | error in setup context Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/nose/suite.py", line 210, in run self.setUp() File "/usr/local/lib/python3.8/site-packages/nose/suite.py", line 293, in setUp self.setupContext(ancestor) File "/usr/local/lib/python3.8/site-packages/nose/suite.py", line 316, in setupContext try_run(context, names) File "/usr/local/lib/python3.8/site-packages/nose/util.py", line 471, in try_run return func() File "/usr/local/lib/python3.8/site-packages/django/test/testcases.py", line 1131, in setUpClass … -
How can you manage content on a website built with Angular and django REST API as the backend?
I'm working on a web application that is powered by Angular and django REST framework on the back-end, everything works fine for the dynamic data but my website has content that needs to be updated regularly, i have been using django-cms to manage content previously but i'm not sure how to manage the content on SPA's.