Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Replace text entry for datetime to calendar date picker icon in Django form
I've this template in my Django application for adding a training session: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>New session</h1> <form action="" method="post">{% csrf_token %} {{ form|crispy }} <input class="btn btn-success" type="submit" value="Save" /> </form> <p /> {% endblock content %} The form contains a datetime field which appears as follows: Is it possible to change this so instead of entering the datetime as text it can be selected from a calendar type icon? If so, how is this done? This is my view: class SessionCreateView(CreateView): model = ClubSession template_name = 'session_new.html' fields = ['location', 'coach', 'date', 'details'] This is my model: class ClubSession(models.Model): location = models.CharField(max_length=200) coach = models.ForeignKey(CustomUser, on_delete=models.CASCADE) date = models.DateTimeField(default=now) details = models.TextField() def __str__(self): return self.location def get_absolute_url(self): return reverse('session_detail', args=[str(self.id)]) -
'List' object has no attribute 'startswith' - difficulty solving
Upon reviewing existing cases regarding this topic I have yet to find a solution. I am trying to run my python server and keep running into this traceback: > G:\inetpub\FaulknerandSonsLTD2\Website\Website>manage.py runserver > Watching for file changes with StatReloader > Exception in thread django-main-thread: > Traceback (most recent call last): > File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\threading.py", line 926, in > _bootstrap_inner > self.run() > File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\threading.py", line 870, in run > self._target(*self._args, **self._kwargs) > File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\utils\autoreload.py", > line 53, in wrapper > fn(*args, **kwargs) > File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\commands\runserver.py", > line 109, in inner_run > autoreload.raise_last_exception() > File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\utils\autoreload.py", > line 76, in raise_last_exception > raise _exception[1] > File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\__init__.py", > line 357, in execute > autoreload.check_errors(django.setup)() > File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\utils\autoreload.py", > line 53, in wrapper > fn(*args, **kwargs) > File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\__init__.py", > line 24, in setup > apps.populate(settings.INSTALLED_APPS) > File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\apps\registry.py", > line 91, in populate > app_config = AppConfig.create(entry) > File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\apps\config.py", > line 90, in create > module = import_module(entry) > File "G:\Program Files … -
How do I Query a child value of an object in a CharField of a model?
I have a model: class OAuthCredentials(BaseModel): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="credentials_author") temp_id = models.UUIDField(default=uuid.uuid4, editable=True) credentials = models.CharField(max_length=255, blank=True) The "credentials" CharField is an object with a token and some other info inside of it. I'm trying to authenticate the token like so: def authenticate(request, username=None, password=None, token=None, **kwargs): if token: if request.session['credentials']['token'] == token: user = OAuthCredentials.objects.get(credentials__token=token) I thought I could look inside of it to query like so: user = OAuthCredentials.objects.get(credentials__token=token) But I'm getting the error: Unsupported lookup 'token' for CharField or join on the field not permitted. How do I check my token against the token inside of the credentials object in that model? -
problems creating a modelform that validates unique_together with a foreignkey that is excluded from the modelform
So i've been stuck on this problem for a couple of days. I am trying to create a form that validates unique together with a foreignkey that is excluded from the modelform(since i dont want user to choose the user) and a "title" field which is included. What i tried to do is to define a init that takes a user object passed in through the view, to set the user field and validate inside the form. However when i save the form i get an error saying: init() got multiple values for argument 'user' My modelform looks like this class NewGoalForm(ModelForm): class Meta: model = Goal exclude = ['slug', 'date_created', 'user', 'parent'] def __init__(self, user, *args, **kwargs): self.user = user object = Goal.objects.get(user=self.user, parent=None) self.parent = object super(NewGoalForm, self).__init__(*args, **kwargs) And my view looks like this def goals(request, username): #def get(node_id): return Category.objects.get(pk=node_id) if username == request.user.username: if request.method == 'POST': userobject = User.objects.get(pk=request.user.pk) form = NewGoalForm(request.POST, user=userobject) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) else: userobject = User.objects.get(pk=request.user.pk) form = NewGoalForm(user=userobject) user = User.objects.get(username=username) object = Goal.objects.get(parent=None, user=user).get_descendants(include_self=False) return render(request, 'goals/goals.html', {'genres': object, 'form': form, }) else: return render(request, 'goals/private.html') Any help is highly appreciated! -
EMAIL IS NOT SENDING IN DJANGO AFTER HOSTED IN CPANEL
I hosted website (django) on cpanel, But the email is not sending , its working fine with local server , SMTP im using -
How to access setting error of django using scrapy
I am new to scrapy and Django, I am using django for creating models and display data from the database and scrapy to scrape and dump the data to database, I am unable to get what is the below error is about. ''' % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. ''' I am trying to scrape data and then dump it to database I am following this linkhttps://blog.theodo.com/2019/01/data-scraping-scrapy-django-integration/ structure scrapy_structure Can anyone please let me know how to save the items(with item.save()or other methods) into the data base(postgresql). I can save the data into db with insert command(with %s) in scrapy but I am trying to use .save() as the link provided but I am getting the above error. Thank you in advance. -
remote rejected master -> master (pre-receive hook declined) while pushing to heroku
i want push my django API to heroku to host using git but i am getting error while pushing "git push heroku master". i tried buildpacks but still getting this error. -
DJANGO form submission via AJAX: TypeError: $.ajax is not a function
I'm creating a chat app and trying to submit a simple form in django via Ajax but I keep getting this error. chat.html <textarea class="form-control" id="msg-text" name="text" placeholder="Message {{ receiver }}.."></textarea> <input type="hidden" id="msg-receiver" name="receiver" value='{{ receiver }}'/> <input type="hidden" id="msg-sender" name="sender" value='{{ sender }}'/> <button id="submit-button" class="btn btn-primary submitbutton" type="submit" style="margin: 10px;">Send</button> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script type="text/javascript"> $('.submitbutton').click(function(){ var text = document.getElementById('msg-text').value var sender = document.getElementById('msg-sender').value var receiver = document.getElementById('msg-receiver').value $.ajax({ type:"GET", url: "/message", data:{ text:text, sender:sender, receiver:receiver }, }); }); </script> views.py def send_message(request): if request.method == 'GET': text = request.GET['text'] sender = request.GET['sender'] receiver = request.GET['receiver'] print('ceva') if text: new_message = Message(sender=sender,receiver=receiver,text=text) new_message.save() return HttpResponseRedirect(self.request.path_info) return HttpResponseRedirect(self.request.path_info) urls.py url(r'^message/$', views.send_message, name='message'), Somebody please help I'm stuck here for days. -
Django Forn Not Saving Extra Information
I extended the Django AbstratUser so that users can use email to sign in and signup, these work perfectly. The problem I am facing, however, is that the extra information on the extended model is not storing the information in the database, even though the user gets created. Once I hit the submit button, the user and extended model get created, and while the user model stores the information, the extended model is always empty. I have tried using both signals and @transaction_atomic, yet, I have not been able to figure it out. Maybe I am missing out something, I do not know. Models.py class Company(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) name= models.CharField(_('Company name'), max_length=250) ... #more information ... class Meta: verbose_name = _('Company') verbose_name_plural = _('Companies') def __str__(self): return self.name forms.py class CompanySignUpForm(CustomUserCreationForm): name = forms.CharField(widget=TextInput(attrs={'placeholder': 'Company name'})) ... #more fields ... class Meta(CustomUserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_company = True user.save() company = Company.objects.create(user=user) company.name = self.cleaned_data.get('name') ... #more information ... return user Views.py def company_signup(request): if request.method == 'POST': form = CompanySignUpForm(request.POST) if form.is_valid(): form.save() return render(request, 'accounts/templates/company_success.html') else: form = CompanySignUpForm() return render(request, 'accounts/templates/company_signup.html', context={ 'title': _('Create a Company Account'), 'form': … -
quickly access models attributes via foreign key relationship in django template
I have a model where one field is a ForeignKey so that each child object is linked to a parent object. In my (jinja2) templates, I list some attributes from a subset of objects from the child model, including one of the parents' attributes. The page loads very slowly, so I am wondering if there is a faster way to do the following: views.py class TransactionView(LoginRequiredMixin, ListView): model = Transactions context_object_name = 'transaction_list' template_name = 'bank/transactions.html' def get_queryset(self): return Transactions.objects.filter(owner_id=self.request.user) template.html <tbody> {% for transaction in transaction_list %} <tr> <td>{{transaction.source_document.service_provider}}</td> <td>{{transaction.account}}</td> <td>{{transaction.tnsx_date}}</td> <td>{{transaction.end_bal}}</td> <td>{{transaction.amount}}</td> <td>{{transaction.category}}</td> </tr> {% endfor %} </tbody> models.py class Transactions(models.Model): def __str__(self): return str(self.tnsx_uuid) owner = models.ForeignKey( User, on_delete=models.CASCADE, db_index=True, editable=True, ) source_document = models.ForeignKey( Document, on_delete=models.CASCADE, editable=True, ) tnsx_uuid = models.UUIDField(default=uuid.uuid4, unique=True) account = IBANField(enforce_database_constraint=True) currency = models.CharField(max_length=4, blank=False, null=False) currency_assumed = models.BooleanField(null=False) <etc> -
How to get list of all nse stocks and real time price
I m working on this project where I need all NSE stocks and their real-time price also. What I have done till now: I m able to get a list of all stocks listed in NSE. from nsetools import Nse nse = Nse() stocks = nse.get_stock_codes() What I need to show their real-time price also I m using a python package nsetools. you can suggest any other package also. please help. -
After Changing to Customer User Model: AttributeError: 'NoneType' object has no attribute '_meta'
I had to switch to a custom user model to assign additional fields to the model. I am currently working on debugging the code. Finally the code is now running. But when I try to log in the user, I get the following error message: AttributeError: 'NoneType' object has no attribute '_meta' I work with the django rest api. Internal Server Error: /api/auth/login Traceback (most recent call last): File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\user\Dropbox\Dev_Projects\project\Backend\project\user\api.py", line 38, in post "user": UserSerializer(user, context=self.get_serializer_context()).data, File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\rest_framework\serializers.py", line 562, in data ret = super().data File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\rest_framework\serializers.py", line 260, in data self._data = self.to_representation(self.instance) File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\rest_framework\serializers.py", line 514, in to_representation for field in fields: File "C:\Users\user\Desktop\Development\project\project_env\lib\site-packages\rest_framework\serializers.py", line 375, in _readable_fields for field in self.fields.values(): File … -
Error: Line number: 1 - 'C' Django import export
i'm trying to import csv by import export but its showing this error. Errors Line number: 1 - 'C' MGT502, 1, muhammad ibrahim, Male, 0, No attempts have been made on this lesson. , No attempts have been made on this lesson. , Grade: - , Grade: - , Grade: - Traceback (most recent call last): File "C:\Users\hafiz\PycharmProjects\DotsPrototype\ven\lib\site-packages\import_export\resources.py", line 522, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\hafiz\PycharmProjects\DotsPrototype\ven\lib\site-packages\import_export\resources.py", line 292, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\hafiz\PycharmProjects\DotsPrototype\ven\lib\site-packages\import_export\resources.py", line 281, in get_instance self.fields[f] for f in self.get_import_id_fields() File "C:\Users\hafiz\PycharmProjects\DotsPrototype\ven\lib\site-packages\import_export\resources.py", line 281, in self.fields[f] for f in self.get_import_id_fields() KeyError: 'C' this error is for all the rows. can anyone help me with this?? -
Recieving IDENTITY_INSERT is set to OFF. (544) , how to check what is wrong?
I want to make input into database. But it is screaming FactClaimCases' when IDENTITY_INSERT is set to OFF. (544).I have identity_insert set on in database and I am not inserting primary key with from. Other field looks fine. I have tried different combinations. If I set parameter form.save(commit=False) form pass through. I learning django and I just do not know what to look for now. is this error connected somehow with polybase services? models.py class Factclaimcases(models.Model): idfactclaimcase = models.IntegerField(db_column='IdFactClaimCase', primary_key=True) # Field name made lowercase. idtechnican = models.ForeignKey(Dimtechnican, models.DO_NOTHING, db_column='IdTechnican') # Field name made lowercase. thedate = models.ForeignKey(Dimdate, models.DO_NOTHING, db_column='TheDate') # Field name made lowercase. description = models.CharField(db_column='Description', max_length=50) # Field name made lowercase. manufacturedef = models.BooleanField(db_column='ManufactureDef', blank=True, null=True, default=False) # Field name made lowercase. This field type is a guess. doc = models.BinaryField(db_column='Doc', blank=True, null=True) # Field name made lowercase. class Meta: managed = True db_table = 'FactClaimCases' def __str__(self): return self.name forms.py class Factclaimcases_input(forms.ModelForm): class Meta: model = Factclaimcases fields = ("idtechnican", 'thedate', 'description') views.py def send(request): pks=request.POST.getlist('check') selected_objects = Factclaim.objects.filter(pk__in=pks) table = tab_recent_claims(selected_objects) form = Factclaimcases_input(request.POST) if request.method == "POST": if form.is_valid(): form.save() return redirect('claim_cases') print(form) else: form = Factclaimcases_input() return render(request, 'test.html', {'table': table, 'pks': pks, … -
Django on Windows Server using mod_wsgi. No module named 'lxml.etree'
I am deploying a new Django project to a local Windows server via Apache with two preexisting Django projects. The site works when running locally on the server, but not via WSGI. I am using the mailmerge package to manipulate some docx templates, and when the site loads, it fails on the line "from lxml.etree import Element". I have tried modifying the import command in the mailmerge.py file to no avail. I have installed the lxml and mailmerge packages in and outside of my virtualenv. I've googled and searched this and other sites, but the search results either don't apply or didn't solve the issue when I tried the various fix actions. Here is a snippet from my Apache error log for the project: Apache Error Log Here is my wsgi_windows.py file: # execfile(activate_this, dict(__file__=activate_this)) exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('D:/QR/qr_env/Lib/site-packages') # Add the app's directory to the PYTHONPATH sys.path.insert(0,'D:/QR') sys.path.insert(1,'D:/QR/quality_review') os.environ['DJANGO_SETTINGS_MODULE'] = 'quality_review.settings' #os.environ.setdefault("DJANGO_SETTINGS_MODULE", "quality_review.settings") os.environ["DJANGO_SETTINGS_MODULE"] = "quality_review.settings" from django.core.wsgi import get_wsgi_application application = get_wsgi_application This is the project's entry in the vhosts.conf file: <VirtualHost *:8082> ServerName ********** WSGIPassAuthorization On ErrorLog "logs/quality_review.error.log" CustomLog "logs/quality_review.access.log" combined WSGIScriptAlias … -
How to give user wise numbers to uploaded videos which is to be displayed on Django admin
Model from django.contrib.auth.models import User from django.db import models # Create your models here. class VideoUploads(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) video = models.FileField(null=True) def __str__(self): return f'{self.user.username} Videos' I am getting Output as shown in the image attached I want something like this bbbb Videos 2 aaaa Videos 2 bbbb Videos 1 aaaa Videos 1 As I keep adding videos the number of the videos uploaded should be displayed next to it. I used repr() method also but as we know it displays only Object name but not the content. Please help me out with this -
What thing need to Deploy a Django Website
I'm trying to figure out the hosting requirements for the website. Any guidance to this would be much appreciated! I don't know anything about deploying I need to know how many / which kind of instances I'll need so I can start planning this in my head. Info: - I am having a Django website which is linked with Postgres database having images video basically it is an educational website which has mainly had 3 function 1st is blog page 2nd is courses 3rd is books download page I am new to this I don't know what is instance what I need to deploy a Django website I never used hosting I am thinking to deploy the project on google cloud platform hosting kindly tell me what I need. I am a student that why I need everything to happen with as much as less money I appreciate any suggestions. Thank you! -
how to use prefix in inlineformset
Whenever I save my inlineformset, it only saves the last form, if count=3 then my front end generates 3 fields to add books, but it only the save the last one. i know i should use prefix keyword but i dont know where and how to add prefix in my template and the script code my models.py class Book(models.Model): book = models.CharField(max_length=20,unique=True) author = models.ForeignKey(Author,on_delete=models.CASCADE) class Author(models.Model): author = models.CharField(max_length=30,unique=True) count = models.IntegerField() this is my forms.py class AuthorForm(ModelForm): class Meta: model = Author fields = ['author','count'] class BookForm(ModelForm): class Meta: model = Book fields = ['book'] InlineFormset_Author = inlineformset_factory(Author,Book,form=BookForm,extra=1) and also this is my views.py class CreateBookView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Author form_class = AuthorForm def get_context_data(self,*args,**kwargs): context = super(CreateBookView,self).get_context_data(*args,**kwargs) if self.request.POST: context['book'] = InlineFormset_Author(self.request.POST) context['book'] = InlineFormset_Author() return context def form_valid(self,form): context = self.get_context_data() context = context['book'] with transaction.atomic(): self.object = form.save() if context.is_valid(): context.instance = self.object context.save() return super(CreateBookView,self).form_valid(form) and this is my template <form method="POST">{% csrf_token %} {{book.management_form}} {{form.author | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.count | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:count'}} <button class="col-4 mx-auto shadow-lg border-right border-left">insert</button> <div id="BOOK" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="my-modal-title">BOOK</h5> <p class="close" … -
populate FOREIGN KEY with a django fomrs
am trying to give the user the ability to enter data here is my models named cv : class Experience_Pro(models.Model): annee_debut = models.IntegerField() annee_fin = models.IntegerField() description_exp_pro = models.TextField(null=True,blank=True) class Ecole(models.Model): nom_ecole = models.CharField(max_length=50) classement = models.IntegerField() class Academic(models.Model): annee_debut = models.IntegerField() annee_fin = models.IntegerField() type_diplome = models.CharField(max_length=10) description_academic = models.TextField(null=True,blank=True) ecole = models.ForeignKey('Ecole' , on_delete=models.DO_NOTHING) class Cv(models.Model): experience_Pro = models.ForeignKey('Experience_Pro' ,on_delete=models.CASCADE) academic = models.ForeignKey('Academic',on_delete=models.CASCADE) and here is my forms class CvForm(forms.ModelForm): class Meta: model = Cv fields = "__all__" but instead of getting inputs for the user to enter data i get a dropdownlist of already existed records in my database . -
Django- how to incorporate forms into ListView
Using Django, I am trying to create a view displaying a list of objects. each list will contain some details about participants in a study (name, age, etc.). That part is easy enough however for one of the fields, for each participant in this list, a drop-down menu that will display the current state of the field and then allow the viewer to select a different value for this field, and then either automatically or through hitting a 'submit' button, update that field value. Currently I am using a ListView to enable this view but I cannot make this work. I am currently trying this. : ''' class ReviewStateForm(forms.ModelForm): class Meta: model = Participant fields = ['review_state'] widgets = {'review_state': forms.Select(Participant.REVIEW_STATE_CHOICES)} def get_context_data(self, **kwargs): context = super(ParticipantListView, self).get_context_data(**kwargs) for p in context['object_list']: p.form = ReviewStateForm(instance=p) return context ''' This gives me an error when I go to the associated url due to an exception in processing 'item.form' in the template. How can I address this? I am open to using a different approach completely and not using ListView -
Why does this django query return a tuple instead of the object?
I'm working on a project and found a bug which makes no sense to me. In these lines: customer = Customer.objects.get_or_create(phone=from_number) store = Store.objects.get(phone=to_number) logging.info("CUSTOMER TYPE: {}".format(type(customer))) logging.info("STORE TYPE: {}".format(type(customer))) In the logs, the customer type says CUSTOMER TYPE: <class 'tuple'>, but the store type says STORE TYPE: <class 'orders.models.Store'>. Both classes are in the same project and app, both are included in the same way (from orders.models import Customer, Store) If it's of any help, the classes are these: class Customer(models.Model): name = models.CharField(max_length=200, verbose_name="Nombre") phone = models.CharField(max_length=13, verbose_name="Teléfono") last_location = models.CharField(max_length=200, verbose_name="Ultima ubicación") def __str__(self): return self.name class Store(models.Model): service_hours = models.ForeignKey(ServiceHours, related_name="stores", on_delete=models.PROTECT) name = models.CharField(max_length=100, verbose_name="Nombre") phone = models.CharField(max_length=13, verbose_name="Celular") enabled = models.CharField(max_length=200) address = models.CharField(max_length=200, verbose_name="Dirección") dialogflow_id_project = models.CharField(max_length=30, blank=False, null=False, default='pedidoswhatsapp-hcujca') file_settings_name = models.CharField(max_length=30, blank=False, null=False, default='pedidos_dialogflow.json') def __str__(self): return self.name I don't get how the code would be taking the customer as a tuple. Any help would be very helpful. -
Django/Python : Best practices for video storage / processing
I am building an app that allows users to upload video submissions for specific events. The video file is handled with django-videokit which uses ffmpeg and mediainfo to get the dimensions, length, mimetype, and create a thumbnail. It then sends the video to a celery task to create an mp4. I am using a digitalocean droplet, nginx, and gunicorn to serve the website. Originally, I was storing, serving and processing all the videos from the droplet. I recently moved my static and media files to a Spaces bucket and use django-storages. It seems like a sacrificed a lot of speed on the uploads for what I think is the "greater good". Can anyone provide feedback? Did I make the right decision to use the CDN? After moving to the CDN, when the file upload reaches 100% the page sits idle with the loading wheel while I assume it sends the file to the CDN? I am still relatively new and this is my first experience with video processing and a CDN -
How to handle multiple elements with the same ID in HTML/AJAX/DJANGO?
I have created the functionality to like/dislike posts in my blog but currently it is that the users can only give a like on the post_detail page. Now I wanted to improve my page so users do not have to open the post_detail view but instead can like posts on the main feed. With my current code I am facing the issue that multiple html elements share the same ID.. I know that IDs are unique, so I need to somehow create unique IDs but I do not know how I can accomplish that. Within the post_detail page I am having a div to include my html template for likes: <div id="like-section"> {% include 'feed/like_section.html' %} </div> Within the like_section file I have the two buttons for liking/disliking a post: <form action="{% url 'post-likes' %}" method="POST"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-secondary btn-danger">Unlike</button> {% else %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-secondary">Like</button> {% endif %} </form> <p class="">{{ post.likes.count }} people liked this post</p> If this form is submitted, the following jQuery code calls my django view: $(document).on('click', '#like', function(event){ event.preventDefault(); // Primary Key from form is … -
Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000002523CE84E48>>": "Balance.user" must be a "User" instance
I'm working on the Wallet Balance ASPECT of my django website. I want a situation where as soon as new user registers on the website his wallet balance is set to '0', But my code is throwing the above error. Kindly assist. VIEW @unauthenticated_user def registration(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='customer') user.groups.add(group) Customer.objects.create( user=user, name=user.username, ) instance = Balance(user=request.user, balance=10) instance.save() messages.success(request, 'Account was created for ' + username) return redirect('loginuser') context = {'form': form} return render(request, 'account/registration.html', context) MODEL class Balance(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) balance = models.IntegerField() def __str__(self): return str(self.user) if self.user else '' TRACEBACK Traceback (most recent call last): File "C:\Users\ienovo\Domination\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ienovo\Domination\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\ienovo\Domination\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ienovo\Domination\accounts\decorators.py", line 12, in wrapper_func return view_func(request, *args, **kwargs) File "C:\Users\ienovo\Domination\accounts\views.py", line 64, in registration instance = Balance(user=request.user, balance=10) File "C:\Users\ienovo\Domination\venv\lib\site-packages\django\db\models\base.py", line 482, in __init__ _setattr(self, field.name, rel_obj) File "C:\Users\ienovo\Domination\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 219, in __set__ self.field.remote_field.model._meta.object_name, Exception Type: ValueError at /registration/ Exception Value: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000002523CE84E48>>": … -
How to extract charts of xlsx to save on database using django
I want to know how can I extract the charts which exist in an excel file (xlsx) and save them on a database (as an image/pdf/excel chart). I am working with django and reading the other data on spreadsheet using openpyxl. I have found this question and answer but it works using win32 which clearly I can't work with on Linux cPanel. The excel file is received from a user and its certain cells are saved to database at the time of uploading. Any help is appreciated