Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save image to server with javascript and python
I am working on a Django application, where the user can click a button to start the webcam. Once the webcam is started, the user can save the image onto the Django server. Right now my code can snap a picture with javascript. But I am stuck trying to save the image onto the django server. This is my code so far html template <center> <button type="button" name="button" class='btn btn-outline-dark btn-lg' id='start'>Start Video Capture</button> <div class="container-fluid mt-2"> <video id="video" width="640" height="480" autoplay></video><br> <button type="button" data-toggle="modal" data-target="#image_model" class="btn btn-lg btn-dark" id="snap">Snap Photo</button> </div> </center> <form action="{% url 'img_submit' %}" method="post" class="image_submit_form"> {% csrf_token %} <input type="submit" value="Use Image" class="btn btn-primary" id="use_image"> </form> javascript // Grab elements, create settings, etc. var video = document.getElementById('video'); // Elements for taking the snapshot var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); document.getElementById('start').addEventListener("click", function() { // Get access to the camera! if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) { //video.src = window.URL.createObjectURL(stream); video.srcObject = stream; video.play(); }); } $('#snap').fadeIn(); // Trigger photo take document.getElementById("snap").addEventListener("click", function() { context.drawImage(video, 0, 0, 640, 480); var url = canvas.toDataURL(); $("#use_image").click(function() { let $form = $(".image_submit_form"); let form_data = new FormData($form[0]); $.ajax({ url: $form.attr('action'), type: $form.attr('method'), dataType: "json", data: … -
Flutter: Parse a JSON with an array of names, display in Futurebuilder and Listview
I have a a Flutter Project and an Array of Strings in an Api. I want to take out the usernames and display them in a listview.builder. How do I do that? My system is set up like this: I have a Futurebuilder and Listview that displays: 'Title', 'Description' & 'Deadline' - All this inside a card! These cards are scrollable. These are projects, like project management, and I need another Listview.builder inside them that can display the names of the people included in the project. This is my JSON, and I want to display the usernames in a Listview.builder inside another Listview! - I do this by putting it inside a container inside every Card! { "id": 81, "users": [ { "username": "hugo", "fullname": "Hugo Johnsson" }, { "username": "studentone", "fullname": "Student One" } ], "title": "test med teacher chat", "description": "This project does not have a description.", "subject": "No subject", "deadline": "2019-01-06", "days_left": "107 days ago", "overview_requests": [ { "id": 28, "user": { "username": "hugo", "fullname": "Hugo Johnsson" }, "group": 81 } ] } Going into Flutter! - This is the Future Function for taking out the Strings, but how do I create an object for taking out … -
Transform Django Annotate Output
In my application, I have the following annotation statement: TestQuestion.objects.filter(test__owner=self.user, test__complete=True).values('question__concept__name', 'chosen_answer__is_correct').annotate(dcount=Count('question__concept__name')) Which returns a JSON output like follows: "concept_questions_completed": [ { "question__concept__name": "Math", "chosen_answer__is_correct": false, "dcount": 8 }, { "question__concept__name": "Math", "chosen_answer__is_correct": true, "dcount": 9 }, ..... ] However, wonder if there is any way to transform the output to make it easier to work with later. Such that it would look something like this: "concept_questions_completed": [ "Math": { true: { "dcount": 9 }, false: { "dcount": 8 } }, ... ] -
Django object not count
when user adds items, number of items should appear in the dashboard but my code does not count however it is only showing zero here what i have tried so far. views.py class ItemListView(LoginRequiredMixin, ListView): model = Item template_name = 'item/items.html' context_object_name = 'items' ordering = ['-created_at', '-updated_at'] def get_queryset(self): return super(ItemListView, self).get_queryset().filter(author=self.request.user) class ItemCountView(LoginRequiredMixin, ListView): model = Item template_name = 'dashboard/dash.html' context_object_name = 'items' def get_queryset(self): return Item.objects.filter(author=self.request.user) in templates dash.html when it is {{ items.count }} it does not count but if {{ items|length }} it shows zero. Please show me where i am making mistake. Thanks -
Django2.1 + Heroku + Postgres app crashing in Production
The web app I have deployed is crashing in Production as soon as I try to log in after submitting credentials. normally, i have to run: heroku run python manage.py migrate to update the change in Heroku database but when I do, please find below what happen. Here is what the terminal return. Running python manage.py migrate on ⬢ friendsbook-demo... up, run.1779 (Hobby) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 79, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) … -
How to retrieve all usernames alongside a boolean flag for each user to indicate their membership to a group?
I am trying to build a page which allows the admin user to toggle membership to a particular group for each user. I aim to do this with AJAX functionality. I have implemented an AJAX call which returns all users in the system - this data populates a data table. The next step is to have a checkbox next to each user, indicating their membership to a group. I am using the code below in my view to retrieve users. users = list(GeminiUser.objects.filter(is_active=1).values('email')) I want the users query result to contain a boolean field for each user indicating their membership to a particular group. How can I achieve this? Appreciate any guidance. -
Django changing pdf font's xhtml2pdf
So i am rendering an object to pdf and i want to change my pdf font. My project myproject/ |-- myproject |-- static/ |-- admin/ |-- fonts/ |-- GothamPro-Medium.eot |-- GothamPro-Medium.ttf |-- GothamPro-Medium.woff |-- GothamPro-Medium.woff2 my page.html <style type="text/css"> @page { size: A4; } @font-face { font-family: 'GothamPro-Medium'; src: url('static/admin/fonts/GothamPro-Medium.woff') format('woff'), url('static/admin/fonts/GothamPro-Medium.woff2') format('woff2'), url('static/admin/fonts/GothamPro-Medium.eot?') format('eot'), url('static/admin/fonts/GothamPro-Medium.ttf') format('truetype'); font-weight: normal; font-style: normal; } body { font-family: 'GothamPro-Medium'; } </style> <body> TESTE </body> My font is not working , i already try it with another font's and nothing -
Multiple Views from a single form
I have a django app in which there are forms which allow user to enter their data. When I run the app it shows the entry fields vertically like this: here is the Forms.py class SupplierTruckForm(forms.ModelForm): supplier_type = forms.CheckboxSelectMultiple() subject = forms.CheckboxSelectMultiple() supplier_address = forms.CharField(widget=forms.TextInput(attrs={'id': 'pac-input','class': 'controls'})) class Meta: model = Supplier fields = ( 'supplier_name','supplier_address', 'supplier_company_name', 'supplier_email', 'supplier_gst', 'supplier_origin_city', 'supplier_pan', 'supplier_service','subject', 'supplier_type') widgets = {'subject': forms.CheckboxSelectMultiple,'supplier_type':forms.CheckboxSelectMultiple} Can I convert my page into something like this(below) without splitting my form into smaller forms ? I believe two forms are used here in a template. -
Django Admin cannot find data that exists: 'Perhaps it was deleted?'
I have a similar problem to this question: Tablename with ID "Some_ID" doesn't exist. Perhaps it was deleted? Django Sqlite The issue only occurs with one particular model which is: class Kinterms(models.Model): kin_category = models.TextField(blank=True, null=True) # This field type is a guess. parameter = models.TextField(blank=True, null=True) # This field type is a guess. term = models.TextField(blank=True, null=True) # This field type is a guess. ipa_term = models.TextField(blank=True, null=True) # This field type is a guess. alternative_address = models.TextField(blank=True, null=True) # This field type is a guess. comment = models.TextField(blank=True, null=True) # This field type is a guess. sourceid = models.TextField(db_column='sourceID', blank=True, null=True) # Field name made lowercase. This field type is a guess. coder = models.TextField(blank=True, null=True) # This field type is a guess. speaking = models.TextField(blank=True, null=True) # This field type is a guess. kinbank_id = models.TextField(blank=True, null=True) # This field type is a guess. glottocode = models.TextField(blank=True, null=True) # This field type is a guess. row_id = models.TextField(unique=True, blank=True, primary_key = True) # This field type is a guess. class Meta: managed = False db_table = 'kinterms' def __str__(self): return self.row_id Which is displayed in the admin file as from django.contrib import admin from .models import Kinterms, … -
Add past date to auto_add_now
I have a model in which I have field like this createdDate = models.DateTimeField(auto_now_add=True,blank=True, null=True) Now I have to populate records with past date lets say like 1990-01-01 but it is coming as current date and time how can I add past dated datetime to this field? -
AttributeError: 'dict' object has no attribute 'template'
Getting below error while launching the application, AttributeError: 'dict' object has no attribute 'template' ERROR Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 164, in get_response response = response.render() File "/usr/local/lib/python2.7/dist-packages/django/template/response.py", line 158, in render self.content = self.rendered_content File "/usr/local/lib/python2.7/dist-packages/django/template/response.py", line 135, in rendered_content content = template.render(context, self._request) File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py", line 74, in render return self.template.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 210, in render return self._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 202, in _render return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 905, in render bit = self.render_node(node, context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 919, in render_node return node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 135, in render return compiled_parent._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 202, in _render return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 905, in render bit = self.render_node(node, context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 919, in render_node return node.render(context) File "/usr/local/lib/python2.7/dist-packages/classytags/core.py", line 106, in render return self.render_tag(context, **kwargs) File "/usr/local/lib/python2.7/dist-packages/sekizai/templatetags/sekizai_tags.py", line 89, in render_tag rendered_contents = nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 905, in render bit = self.render_node(node, context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 919, in render_node return node.render(context) File "/usr/local/lib/python2.7/dist-packages/classytags/core.py", line 106, in render return self.render_tag(context, **kwargs) File "/usr/local/lib/python2.7/dist-packages/sekizai/templatetags/sekizai_tags.py", line 89, in render_tag rendered_contents = nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 905, in render bit = self.render_node(node, context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 919, in render_node return node.render(context) … -
How to render multiple choices field from model
I need to render Product model as follows: 1 - there are 2 check boxes for gender men/women when user checks men only men products appear when user check women only women products appear when check both or uncheck both all products appear so I used choices for gender field but how to render that in my template as mentioned above? thanks in advance... GENDER_CHOISES=( ('men', "Men"), ('women', "Women"),) class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to='products', null=True, blank=False) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) gender = models.CharField(max_length=120,default="women" ,choices=GENDER_CHOISES) timestamp= models.DateTimeField(auto_now_add=True) -
create and download zip files with django/jquery
If this is a duplicate question please feel free to mark it. I have some data that I need to send it to my client (his personal data on my website). So I created a link: export in html file: <a href="#" class="export-data">export<i class="ft-download"></i></a> this is my jquery function: $(document).on('click', '.export-data', function(){ // get selected data and send list to backend var data= [] $('.group-check-data').each(function(){ var checked = $(this).is(':checked'); if (checked == true){ data.push($(this).attr("data-id")); } }); console.log(data); var json_data = {'csrfmiddlewaretoken' : $('.url-csrf').attr('data-csrf'), 'list-data': data}; $.ajax({ type:'POST', url : $('.url-export-selected-data').attr('data-url-export-selected-data'), data : json_data, success : function(response){ $('.result').attr('href', response); console.log(response); } }); }); this is my view: def export_data(request): user = get_object_or_404(User, username=request.session['username']) # TODO: generate json of selected data for key in request.POST.keys(): if key == "list-data[]": list = request.POST.getlist(key) for item in list: path = os.path.join(EXPORT_FOLDER, 'user_{}', 'data_{}').format(user.id, int(item)) try: shutil.rmtree(os.path.join(EXPORT_FOLDER, 'user_{}', 'data_{}').format(user.id, int(item))) except: print("directory does not exist") if not os.path.exists(path): os.makedirs(path) generate_data(user.id, int(item)) # TODO: create zip file and export it to user archive = shutil.make_archive(os.path.join(EXPORT_FOLDER, 'user_{}', 'compressed').format(user.id), 'zip', os.path.join(EXPORT_FOLDER, 'user_{}').format(user.id)) response = HttpResponse(archive, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=foobar.zip' return response I can't show to user the download window, I tried to add this link <a href="#" … -
How to correctly serialize a List of Lists
I am writing a django API where I need to return a list of lists. I attempted to do this as a model serializer, but I received the following error when I began building up a list of lists response: AttributeError: Got AttributeError when attempting to get a value for field `contract_number` on serializer `ContractsSignUpListSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `list` instance. I began building a response due to the fact that I needed to pull in attributes from 3 different tables, and each time I used their respective model serializer it gave me attribute errors for one of the other models. These are the attributes I needed coming from 3 different tables: query = SignUpTable.objects.filter(empid_id__empid=int(input)) for q in query: print q.empid.first_name, print q.empid.last_name, print q.signedup, print q.contract_number.contract_number, I've tried returning the Query variable which works, but it only provides me with the foreign key in the current table, when I need one or two attributes from the other table's and not necessarily the foreign key on the current table. I've also tried returning list of lists with a list serializer, but receive an error that no child has … -
i want to create a website where users can login , and upload their profile , images , stories etc, like facebook ,
i have already create a model to extent users fields, now i want create another model to store user all upload. e.g how Facebook stores users data and make that available for all users and even a user can edit anything in his profile, can you tell me how i make models to store date all data. enter code here my current models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) upload_date = models.DateTimeField(auto_now_add=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True, default='users/download.png') def __str__(self):enter code here return 'Profile for user {}'.format(self.user.username) -
pipenv install django==2.1 not working on google collab
I have already installed pipenv using, pip install pipenv on the directory which was installed successfully. But pipenv install Django==2.1 does not seem to work. In fact, no command is getting executed using pipenv. pip install pipenv Collecting pipenv Downloading https://files.pythonhosted.org/packages/13/b4/3ffa55f77161cff9a5220f162670f7c5eb00df52e00939e203f601b0f579/pipenv-2018.11.26-py3-none-any.whl (5.2MB) 100% |████████████████████████████████| 5.2MB 5.5MB/s Requirement already satisfied: setuptools>=36.2.1 in /usr/local/lib/python3.6/dist-packages (from pipenv) (40.9.0) Collecting virtualenv-clone>=0.2.5 (from pipenv) Downloading https://files.pythonhosted.org/packages/ba/f8/50c2b7dbc99e05fce5e5b9d9a31f37c988c99acd4e8dedd720b7b8d4011d/virtualenv_clone-0.5.3-py2.py3-none-any.whl Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from pipenv) (2019.3.9) Requirement already satisfied: pip>=9.0.1 in /usr/local/lib/python3.6/dist-packages (from pipenv) (19.0.3) Collecting virtualenv (from pipenv) Downloading https://files.pythonhosted.org/packages/33/5d/314c760d4204f64e4a968275182b7751bd5c3249094757b39ba987dcfb5a/virtualenv-16.4.3-py2.py3-none-any.whl (2.0MB) 100% |████████████████████████████████| 2.0MB 17.1MB/s Installing collected packages: virtualenv-clone, virtualenv, pipenv Successfully installed pipenv-2018.11.26 virtualenv-16.4.3 virtualenv-clone-0.5.3 pipenv install Django==2.1 File "", line 1 pipenv install Django==2.1 ^ SyntaxError: invalid syntax * Anything on Google Colab suggestions would be very helpful! * -
Problems with receiving data from celery task django?
I am learning how to implement celery task in django. I have created a task which basically does some file validation and the writes the record to a model. Then I am returning the result in the return value. Now, when i see my celery logs, I can see that the function is returning correct data as expected but when i make a request from my ajax to get the results of my task using task id, I am getting nothing. What could be the issue. from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Pay2School.settings') app = Celery('pay2school') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings.py BROKER_HOST = "localhost" BROKER_PORT = 5672 BROKER_USER = "guest" CELERY_RESULT_BACKEND = "amqp" CELERY_RESULT_SERIALIZER = 'json' tasks.py @app.task() def process_upload_file(file_id): try: logger.debug('Files:process_upload_file - called.') try: _file = FileUpload.objects.get(id=int(file_id)) except FileUpload.DoesNotExist: return None if not _file: logger.error('Files:process_upload_file - Could not locate upload file with ID={}'.format(file_id)) return elif not _file.type: logger.debug('Files:process_upload_file - identify.') elif _file.status == FileUpload.STATUS_NEW: print('Files:process_upload_file - … -
(Django)send data to View from javascript(ajax)
I want to send data(survey data) from the template to the server via ajax and store this data as csv on the server. (I don't know jquery.) Currently, an error appears everywhere in url, view, and ajax. Help me with this. I can't understand how the request and response work, if this is right... javascript function sendToServer(data){ var req = new XMLHttpRequest(); req.open("POST", "/polls/upload_csv/", true); req.send(data); } urls.py app_name = 'polls' urlpatterns = [ path('', views.index, name = 'index'), path('survey/', views.survey, name = 'survey'), path('finish/', views.finish, name = 'finish'), path('upload_csv/', views.upload_csv, name = 'upload_csv'), ] views.py @csrf_exempt def upload_csv(request): output_file = open('/media/result/resultList.csv', 'wb') writer = csv.writer(output_file) if request.method == 'POST' and request.is_ajax(): writer.writerow(request.body) return 0 (I did not know what to write in return, so I left it blank.) current error: Internal Server Error: /polls/upload_csv/ output_file = open('/media/result/resultList.csv', 'wb') FileNotFoundError: [Errno 2] No such file or directory: '/media/result/resultList.csv' "POST /polls/upload_csv/ HTTP/1.1" 500 75545 code 400, message Bad request syntax -
error while saving the .pkl models of linear regression
I am coding a web application using the framworks django ,the problem is when saving my learning model of linear regresion as .pkl. Is it necessary to create the empty .pkl file or does it generate automatically? and how can I read the contents of such a .pkl file? # Libraries # Importing Dataset data = pd.read_csv('ml_code/ml_process/test.csv') data.fillna(0, inplace=True) def handle_non_numerical_data(df): columns = df.columns.values for column in columns: text_digit_vals = {} def convert_to_int(val): return text_digit_vals[val] if df[column].dtype != np.int64 and df[column].dtype != np.float64: column_contents = df[column].values.tolist() unique_elements = set(column_contents) x = 0 for unique in unique_elements: if unique not in text_digit_vals: text_digit_vals[unique] = x x = x + 1 df[column] = list(map(convert_to_int, df[column])) return df data = handle_non_numerical_data(data) data = data.as_matrix() #X matrice des var. explicatives X = data[:,0:9] #y vecteur de la var. à prédire y = data[:,9] X2_train, X2_test, y2_train, y2_test = train_test_split(X, y, test_size=0.3, random_state=0) lreg = LinearRegression() lreg.fit(X2_train, y2_train) print('Accuracy of linear regression on training set: {:.2f}'.format(lreg.score(X2_train, y2_train))) print('Accuracy of linear regression on test set: {:.2f}'.format(lreg.score(X2_test, y2_test))) y_pred2 = lreg.predict(X2_test) print("Predicted Sales: %.3f" % (y_pred2[0])) ``` Saving the Logistic Regression Model linear_regression_model = pickle.dumps(lreg) Saving the model to a file joblib.dump(linear_regression_model,'ml_code/linear_regression_model.pkl') I get this error when … -
How to owerwrite ListView?
I wrote some code using ListView but I think that exist more professional way to write the same by using get_queryset() method? class CityListView(ListView): model = Place template_name = 'places/city-objects-list.html' def get_context_data(self, *, object_list=None, **kwargs): context = super(CityListView, self).get_context_data(**kwargs) city_paginator_page = Place.objects.all().order_by('name') paginator = Paginator(city_paginator_page, CITIES_ITEMS_PER_PAGE) page_number = self.request.GET.get('page', 1) page = paginator.get_page(page_number) context['city_paginator_page'] = page context['alphabet'] = Place.objects.get_alphabetitc_list() return context -
How to auto-populate a form from database in Django?
I have two forms, and I want to auto fill the second form depending on one field of the first form. How can I do that ? Do I have to override some methods ? Tournament Form class MyModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.name class TournamentCreationForm(forms.ModelForm): name = forms.CharField(label='Name', widget=forms.TextInput(attrs={ 'class':'form-control', 'placeholder': 'Enter the name of the tournament'})) dateStart = forms.DateField(label='Beginning', widget=forms.DateInput(attrs={ 'class':'form-control', 'placeholder': 'Enter the date of the beginning'})) dateEnd = forms.DateField(label='Ending', widget=forms.DateInput(attrs={ 'class':'form-control', 'placeholder': 'Enter the date of the end'})) nbMaxTeam = forms.IntegerField(label='Number max of team', widget=forms.NumberInput(attrs={ 'class':'form-control', 'placeholder':'Max 24'})) nameGymnasium = forms.CharField(label='Name of the gymnasium', widget=forms.TextInput(attrs={ 'class':'form-control', 'placeholder': 'Enter the name of the gymnasium'})) addressGymnasium = forms.CharField(label='Address of the gymnasium', widget=forms.TextInput(attrs={ 'class':'form-control', 'placeholder': 'Enter the address of the gymnasium'})) sport = MyModelChoiceField(queryset=Sport.objects.all(), widget=forms.Select(attrs={ 'class':'form-control'})) class Meta: model = Tournament fields = [ 'name', 'dateStart', 'dateEnd', 'nbMaxTeam', 'nameGymnasium', 'addressGymnasium', 'sport' ] Sport Form class SportEditForm(forms.ModelForm): timeMatch = forms.DecimalField(label='Time for one match', widget=forms.NumberInput(attrs={ 'class':'form-control', 'placeholder':'Enter the the time for one match', 'step': 0.1})) nbpointpervictory = forms.IntegerField(label='Points per Victory', widget=forms.NumberInput(attrs={ 'class':'form-control', 'placeholder':'Enter the points for a victory'})) nbpointperdefeat = forms.IntegerField(label='Points per Defeat', widget=forms.NumberInput(attrs={ 'class':'form-control', 'placeholder':'Enter the points for a defeat'})) nbpointperdraw = forms.IntegerField(label='Points per Draw', widget=forms.NumberInput(attrs={ 'class':'form-control', 'placeholder':'Enter the points … -
Integrate django with google docs,sheet and slides
I created a web application with django, but what I have left is to integrate tools like word, excel in my application and I would like to use google docs is it possible? if that's not the case could you help me find another solution. Thank you in advance for your answers -
Writable nested serializers update function throwing an attribute error
I'm trying to create an update function for an object in Django Rest Framework using writable nested serializers but when I try to do a PUTrequest using postman I'm having this error: AttributeError at /api/kbds/1/ 'collections.OrderedDict' object has no attribute 'rationale' I have two objects interracting KBDand ValueAnswer which you can see the implementation below class KBD(models.Model): company = models.ForeignKey(Company, related_name='kbds', null=False, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='admin_kbd', null=True, on_delete=models.SET_NULL) ended_on = models.DateTimeField(blank=True, null=True) user_group = models.ForeignKey(UserGroup, related_name='kbds', null=True, on_delete=models.SET_NULL) category = models.ForeignKey(Category, related_name='kbds', null=True, on_delete=models.SET_NULL) values = models.ManyToManyField(Value, related_name='kbd_value') class ValueAnswer(models.Model): value = models.ForeignKey(Value, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) rationale = models.CharField(max_length=512) score = models.IntegerField() kbd = models.ForeignKey(KBD, related_name='user_answers', on_delete=models.CASCADE) i'm following the documentation about writable nested serializers but they are not detailing the update function. After googling a while i managed to write this piece of code which is not working (I'm getting the error shown before) #KBD RELATED SERIALIZERS class ValueAnswerSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) rationale = serializers.CharField(required=True) user = ShortUserSerializer(many=False, read_only=True) score = serializers.IntegerField(required=True) class Meta: model = ValueAnswer fields = ('id', 'rationale', 'user', 'score') class KBDSerializer(serializers.ModelSerializer): #company = CompanySerializer(many=False, read_only=True) user_answers = ValueAnswerSerializer(many=True, read_only=False) #user_group = UserGroupSerializer(many=False, read_only=True) class Meta: model = KBD … -
Django Formset - This field is required error
I'm sending multiple instances of QRCode model objects using ModelFormSet, but when form is submitted 'id': ['This field is required.'] error appears in the views.py (formset.errors) Initially, I did include all the form fields one by one, but trying to fix the form I've just pasted whole {{ form }} in the template, in order to put there all the hidden fields. template.html {% extends 'base.html' %} {% load staticfiles %} {% block content %} <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.formset/1.2.2/jquery.formset.js"></script> <div id="app"> <div class="container"> <h3 class="">Создание заданий</h3> <form method="post" > {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row"> <div class="input-field col s6"> {{ form }} </div> </div> {% endfor %} <input type="submit" class="waves-effect waves-light btn"> </form> </div> </div> {# <script src="{% static 'js/quest_qrs.js' %}"></script>#} {% endblock %} models.py class QRCode(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) body = models.TextField() nextStep = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True ) views.py class QRCreateView(LoginRequired, View): def get(self, request, pk): data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '', } formset = QRFormSet(data) context = {'formset': formset} return render(request, 'qrs_create.html', context) def post(self, request, pk): formset = QRFormSet(request.POST) print(formset.__dict__) print(formset.errors) if formset.is_valid(): starting_quest = Quest.objects.get(pk=pk) starting_quest.startQr = formset[0] starting_quest.save() formset_len = … -
Django file upload (get file DATA, not just filepath)
I want to upload an admin Django form to gcloud. My gcloud part works, but requires a filepath. I would like to access the raw data of the file from a form upload and provide that to gcloud's blob upload. I have a model that looks like this from django.db import models from gcloud import storage from oauth2client.service_account import ServiceAccountCredentials # Create your models here. class TestFile(models.Model): name = models.CharField(max_length=64, # NOT NULL, UNIQUE, no default. null=False, default=None, blank=False, unique=True ) data = models.FileField() img_src = models.CharField(max_length=255, null=True, default=None, blank=True ) def save(self, *args, **kwargs): super(TestFile, self).save(*args, **kwargs) filename = self.data.url print("FILENAME: " + filename) # How do I get the file DATA I also have an admin table like so. from django.contrib import admin from django.utils.safestring import mark_safe from .models import TestFile class TestFileAdmin(admin.ModelAdmin): list_display = ( "data", "name", "_img_src", ) def _img_src(self, obj): return mark_safe(u'<img style="height: 75px;width: 75px;object-fit: cover;" src="%s"/>' % obj.img_src) admin.site.register(TestFile, TestFileAdmin) Using whatever storage back-end I want, I have some example code like this: from gcloud import storage from oauth2client.service_account import ServiceAccountCredentials import os credentials_dict = { "type": "service_account", "client_id": os.environ["BACKUP_CLIENT_ID"], "client_email": os.environ["BACKUP_CLIENT_EMAIL"], "private_key_id": os.environ["BACKUP_PRIVATE_KEY_ID"], "private_key": os.environ["BACKUP_PRIVATE_KEY"], } credentials = ServiceAccountCredentials.from_json_keyfile_dict( credentials_dict ) client = …