Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MultiValueDictKeyError hen adding lines with inlineformset
I am trying to add more lines on the inline formset factory using the same methodology that I used before on a formset factory but is getting an error: MultiValueDictKeyError form-TOTAL_FORMS' models.py: class ttransactions(models.Model): transaction_type = models.CharField(max_length=10, choices=tx_choices) description = models.CharField(max_length=50, null=False, blank=False, default='Description') transaction_date = models.DateField(default=datetime.today, db_index=True) company = models.ForeignKey(tcompany, on_delete=models.PROTECT, db_index=True) def __str__(self): return self.description class ttransaction_lines(models.Model): transaction = models.ForeignKey(ttransactions, on_delete=models.PROTECT, db_index=True) sequence = models.IntegerField() transaction_type = models.CharField(max_length=6, choices=debit_credit) ledger_account = models.ForeignKey(tledger_account, on_delete=models.PROTECT, db_index=True) amount = models.DecimalField(max_digits=14, decimal_places=2, default=0.0) vat_amount = models.DecimalField(max_digits=14, decimal_places=2, default=0.0) vat_code = models.ForeignKey(tvat, on_delete=models.PROTECT, blank=True, null=True) quantity = models.IntegerField(blank=True, null=True) posted = models.BooleanField(default=True) forms.py: class TransactionsForm(forms.ModelForm): transaction_date = forms.DateField(widget=forms.SelectDateWidget(years=year_range), initial=datetime.today) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(TransactionsForm, self).__init__(*args, **kwargs) class Meta: model = ttransactions fields = ['description', 'transaction_date'] class TransactionLinesForm(forms.ModelForm): class Meta: model = ttransaction_lines fields = ['transaction_type', 'ledger_account', 'amount'] class BaseTransactionLinesFormSet(BaseModelFormSet): def clean(self): super(BaseTransactionLinesFormSet, self).clean() # Check errors dictionary first, if there are any error, no point in validating further if any(self.errors): return balance = 0 for form in self.forms: if form.cleaned_data['DELETE'] == True or form.cleaned_data['DELETE'] == '': continue if form.cleaned_data['transaction_type']=='Debit': balance = balance + form.cleaned_data['amount'] else: balance = balance - form.cleaned_data['amount'] if balance != 0: message = 'Transactions not balanced (excluding … -
MySQL root user not able to create new database and perform other operations
I created a user named 'root', by setting a password for it by using: create user 'root'@'localhost' identified by 'some_password'; It successfully created a user and I assigned all the privileges to it against a particular database that I created, and was able to connect successfully to that database. But when I logged in using: mysql -u root -p with the password I set in first step and tried performing operations like Create New Database, Select user from mysql.user, and all other operations not related to that particular database against which the permissions are assigned , it is throwing mysql> SELECT user,authentication_string,plugin,host FROM mysql.user; ERROR 1142 (42000): SELECT command denied to user 'root'@'localhost' for table 'user' mysql> mysql> grant usage on *.* to 'root'@'localhost'; ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) mysql> GRANT ALL PRIVILEGES ON * . * TO 'root'@'localhost'; ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) mysql> SHOW GRANTS FOR 'root'@'localhost'; +-------------------------------------------------------------+ | Grants for root@localhost | +-------------------------------------------------------------+ | GRANT USAGE ON *.* TO 'root'@'localhost' | | GRANT ALL PRIVILEGES ON `navi`.`navi` TO 'root'@'localhost' | +-------------------------------------------------------------+ 2 rows in set (0.00 sec) mysql> create user 'django'@'localhost' identified by 'django-user-password'; ERROR … -
Getting profile picture of blogposter in Django
When I display a blog post in HTML using a for loop {% for post in posts %} <div class="blogpost"> <h3><strong>{{post.title}}</strong></h3> <img class="thumbnail" src="{{author.imageURL}}"> <h7>{{post.date}} - {{post.author}}</h7> <br> <hr> <br> {{post.context|linebreaks}}<br><br> </div> <br> {% endfor %} it works perfectly fine, except the authors profile picture does NOT get displayed. I get the posts by getting all posts in my views.py from my models.py. The thing is that the profile picture of the user posting the blog isn't stored in the "post" model in the database. It is stored in the "Customers". Everybody should be able to read and post blogs. The admin (me) can later delete unwanted posts. I have tried making a for loop using an array key:value in JavaScript. That is not very secure, because everybody just gets all users and all profilepictures through the whole database. That might not be a good idea. This is my models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank = True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) about = models.CharField(max_length=100, null=True) image = models.ImageField(null=True, blank=True) @property def imageURL(self): try: url = self.image.url except: url = 'placeholder.png' return url def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=200, null=True) context … -
Django Profile model not showing first_name and last_name fields in sign up form
I created a Profile model with Django. The profile inherits from a CustomUser class which I wrote by inheriting AbstractBaseUser. However, when I go to the sign up page, even though first_name and last_name are required in the Custom User class, it doesn't show. It only shows the fields of the profile model, and email and password. I am using Django all auth. How do I make the required fields of the custom user (and other fields I want e.g middle_name) and the fields of the profile all show up in the same form, and still save both the custom user model, and the profile model in the database all at the same time? models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) USER_TYPE_CHOICES = ( (1, 'student'), (2, 'department'), (3, 'admin'), ) first_name = models.CharField(max_length=70, blank=False, default="") middle_name = models.CharField(max_length=70, blank=False, default="") last_name = models.CharField(max_length=70, blank=False, default="") is_active = models.BooleanField(default=True) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) is_staff = models.BooleanField(default=False) # a admin user; non super-user is_superuser = models.BooleanField(default=False) # a superuser last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] # Email & Password are required by default. objects = UserManager() … -
I have created a system which generates the image for user, and now i want to upload that on S3 and GCP in backgroud using Django
How can I achieve this, suggest any python library if you know that? -
django update portion of a template dynamically post a model save without re rendering
I have a side bar in my template with three event columns (All, Active, Inactive). The activity of the items in the side bar is controlled in backend. I want to dynamically update the list of events shown under (Active, Inactive), when ever their status changes and saved into the database. I can do this by constantly making an Ajax Request and update the template based on the response from view. But I was wondering if django signals can be used and post_save trigger and update the items on the template. Please let me know if u need more details. Code snippets: <!-- sidebar --> <div class="container"> <div class="sidebar"> <div class="side-filter-header"> <a class="selected">All Events</a> <a class="" >Active Events</a> <a class="" >Inactive Events</a> </div> <div class="side-filter-list"> <a href="#" class="list-group-item active-event"> <ul> <li>Event 1</li> </ul> </a> <a href="#" class="list-group-item inactive-event"> <ul> <li>Event 2 </li> </ul> </a> <a href="#" class="list-group-item inactive-event"> <ul> <li>Event 3</li> </ul> </a> </div> </div> </div> Django models.py class EventStatus(Enum): ACTIVE = "ACTIVE" INACTIVE = "INACTIVE" class Event(models.model): eventNo = models.IntegerField() eventStatus = models.CharField(max_length=255, default=EventStatus.INACTIVE, choices=[(tag,tag.value) for tag in EventStatus]) Django views.py def update_sidebar(): event = Event.objects.filter().last() # example # some condition event.eventStatus = "ACTIVE" event.save() # I want to … -
Adding addition field in Django rest framework modelserializer (write_only && read_write) in mixin
I want to create a mixin for additional fields in Modelserializer. Please refer the code below class AdditionalFieldsMixin(object): additional_fields = dict() def __init__(self, *args, **kwargs): super(AdditionalFieldsMixin, self).__init__(*args, **kwargs) for field_name, field_instance in self.additional_fields.items(): self.fields[field_name] = field_instance print(self.fields) def additional_field_before_create(self, additional_field_data): pass def additional_field_after_create(self, additional_field_data, instance): pass def additional_field_before_update(self, additional_field_data): pass def additional_field_after_update(self, additional_field_data, instance): pass def create(self, validated_data): additional_field_data = {} for additional_field in self.additional_fields.keys(): additional_field_data[additional_field] = validated_data.pop(additional_field, None) self.additional_field_before_create(additional_field_data) instance = super(AdditionalFieldsMixin, self).create(validated_data) self.additional_field_after_create(additional_field_data, instance) return instance def update(self, instance, validated_data): additional_field_data = {} for additional_field in self.additional_fields.keys(): additional_field_data[additional_field] = validated_data.pop(additional_field, None) self.additional_field_before_update(additional_field_data) instance = super(AdditionalFieldsMixin, self).update(instance, validated_data) self.additional_field_after_update(additional_field_data, instance) return instance in main class i decleared additional_fields = dict( reference=CharField(write_only=True, allow_blank=True, allow_null=True, default=None), ) but when retrieving the data in list mode the it gives me an error AssertionError: It is redundant to specify `source='reference'` on field 'CharField' in serializer 'MySerializer', because it is the same as the field name. Remove the `source` keyword argument. why this is happening ? also i noted that after starting runserver first time it doesn't give that error but if I query again it gives error second time and so on. and another general question what is the proper way to add … -
How do i create working search bar on ListView
I search in youtube and google for creating a working search bar on ListView but no one use on class allPostList(ListView): could you explain to me how to make it? here is my code table.html {% block container_content %} <form class="d-none d-sm-inline-block mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search justify-content-end"> <div class="input-group"><input class="bg-light form-control border-0 small" type="text" name="q" placeholder="Search for ..."> <div class="input-group-append"><button class="btn btn-primary py-0" type="button"><i class="fas fa-search"></i></button></div> </div> </form> {% endblock %} on the table.html i didnt show all the code because it is to much and messy but that is the form html code and its created on html not in forms.py my views.py class AdminShowAllPostList(ListView): model = Post template_name = 'admini/table.html' ordering = ['category'] paginate_by = 10 a screenshoot on table.html models.py if needed class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) page_link = models.SlugField(max_length=255, unique=True) body = RichTextField(blank=True, null=True, config_name='special', external_plugin_resources=[ ('youtube', '/static/ckeditor_plugins/youtube/youtube/', 'plugin.js'), ] ) category = models.ForeignKey(Category, default="", on_delete=models.CASCADE) # parent_check = models.CharField(max_length=255) meta_description = models.TextField(null=False, blank=False) meta_keyword = models.TextField(blank=False, null=False) i really hope it if the search bar can use complex Q lookup thanks -
How to subtract dates
Hey thanks for checking the question First, see my code class ConfirmationKey(models.Model): key = models.CharField(max_length=20,blank=True) username = models.CharField(max_length=100) email = models.EmailField() confirmation_key = models.CharField(max_length=10,null=True,blank=True) key_generated_at = models.DateTimeField(blank=True,null=True) key_valid_till = models.DateTimeField(blank=True,null=True) def save(self,*args,**kwargs): if self.key is None or len(self.key)== 0 : self.key = binascii.hexlify(os.urandom(20)).decode() self.confirmation_key = binascii.hexlify(os.urandom(8)).decode() self.key_generated_at = datetime.datetime.now() self.key_valid_till = datetime.datetime.now() + datetime.timedelta(minutes=10) super().save(*args,**kwargs) def is_valid(self): """Returns weather the key is still valid or not""" if datetime.datetime(self.key_valid_till) < datetime.datetime.now(): return True return False Now , in the sceond function, how can I subtract self.key_valid_till from current time — where key_valid_till is stringfied datetime.datetime.now() + datetime.timedelta(minutes=10) -
after deploy django project it showing this error AttributeError: 'str' object has no attribute 'tzinfo'
After move localhost to cpanel it shwoimg me that error AttributeError: 'str' object has no attribute 'tzinfo'. How can I fix it? please suggest to me. -
PHP (WordPress) Website deployment on Python environment
I'm a PHP developer. A new project came which requires me to develop a site on subdomain. That main domain is already covered by a Python website developed in Django CMS. Just wanted to know which kind of complications can come? For example, PHP uses My SQL and in PHP website the version should be same. Kindly, tell me how this can be managed. Thanks. -
Is there a way to link a local file stored on server to a django Model?
I want to create a django model that stores a Video and converts it to different resolutions but i don't know how can i link the converted videos back to the same model or save it another model with foriegn key to the base video. Its just like how youtube saves their videos -
mod_wsgi (pid=145, process='dc_ui', application=''): Loading WSGI script '/app/data_cube_ui/wsgi.py'
I am trying to deploy a django application and i am getting a 500 internal server error. The error.log file shows: [mpm_event:notice] [pid 142:tid 139995416574912] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [core:notice] [pid 142:tid 139995416574912] AH00094: Command line: '/usr/sbin/apache2' [wsgi:info] [pid 145:tid 139995416574912] mod_wsgi (pid=145): Attach interpreter ''. [wsgi:info] [pid 145:tid 139995416574912] mod_wsgi (pid=145): Adding '/app' to path. [wsgi:info] [pid 145:tid 139995298592512] [remote 172.18.0.1:41624] mod_wsgi (pid=145, process='dc_ui', application=''): Loading WSGI script '/app/data_cube_ui/wsgi.py'. mod_wsgi (pid=145): Target WSGI script '/app/data_cube_ui/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=145): Exception occurred processing WSGI script '/app/data_cube_ui/wsgi.py'. Traceback (most recent call last): File "/usr/lib/python3.6/logging/config.py", line 565, in configure handler = self.configure_handler(handlers[name]) File "/usr/lib/python3.6/logging/config.py", line 738, in configure_handler result = factory(**kwargs) File "/usr/lib/python3.6/logging/__init__.py", line 1032, in __init__ StreamHandler.__init__(self, self._open()) File "/usr/lib/python3.6/logging/__init__.py", line 1061, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) PermissionError: [Errno 13] Permission denied: '/app/log/ODC_UI.log' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/data_cube_ui/wsgi.py", line 42, in <module> application = get_wsgi_application() File "/app/datacube_env/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application[Thu Dec 24 17:33:53.891302 2020] [wsgi:error] [pid 145:tid 139995298592512] [remote 172.18.0.1:41624] django.setup(set_prefix=False) File "/app/datacube_env/lib/python3.6/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/app/datacube_env/lib/python3.6/site-packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python3.6/logging/config.py", … -
Why a form having foreign keys in giving field error in django on form submission
I am creating a feedback form. This form has three foreign keys. My views.py is def studentFeedBack(request): if request.method == 'POST': studentid_id = request.POST.get("studentid") studentid = Student.objects.get(id=studentid_id) courseid_id = request.POST.get("courseid") courseid = Course.objects.get(id=courseid_id) teacherid_id = request.POST.get("teacherid") teacherid = SchoolTeacher.objects.get(id=teacherid_id) description = request.POST.get("description") rating = request.POST.get("rating") studentFeedBackModel.objects.create( courseid=courseid, description=description, studentid=studentid, teacherid=teacherid, rating=rating ) return render( request, 'forms/studentFeedBack.html', { 'studentids':Student.objects.all(), 'courseids':Course.objects.all(), 'teacherids':SchoolTeacher.objects.all(), } ) and my model for feedback form is class StudentFeedBack(models.Model): feedbackid = models.AutoField(primary_key=True) courseid = models.ForeignKey('Course', on_delete=models.CASCADE) description = models.CharField(max_length=500) submitdate = models.DateTimeField(auto_now_add=True) teacherid = models.ForeignKey('SchoolTeacher', on_delete=models.CASCADE) studentid = models.ForeignKey('Student', on_delete=models.CASCADE) option = [('Good','Good'),('Average','Average'),('Bad','Bad')] rating = models.CharField(max_length=100, choices=option, default='none') The above model has foreign key from models class Course(models.Model): courseid = models.IntegerField(primary_key=True) coursedescription = models.CharField(max_length=500) coursename = models.CharField(max_length=50) userid = models.IntegerField() code = models.CharField(max_length=50) videolink = models.FileField(default='default_link') # roleid = models.ForeignKey(RoleName, on_delete=models.CASCADE) createddate = models.DateTimeField() imagelink = models.URLField(default='default_link') duration = models.DateTimeField() longdes = models.TextField() coursetype = models.CharField(max_length=50) # classid = models.ForeignKey(TblClass, on_delete=models.CASCADE) assignto = models.CharField(max_length=200) status = models.BinaryField() def _str_(self): return self.coursename class Meta: db_table = "courseids" class SchoolTeacher(models.Model): teacherid = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) address = models.CharField(max_length=200) email = models.EmailField() contact = models.IntegerField() # classid = models.ForeignKey(TblClass, on_delete=models.CASCADE) # schoolid = models.ForeignKey(School, on_delete=models.CASCADE) passowrd = models.CharField(max_length=13) image = … -
How to get object from Django-solo?
I have a Django solo model, and I need to get an object from it class Settings(SingletonModel): start_message = models.TextField(verbose_name='/start', null=True, blank=True) login_message = models.TextField(verbose_name='inst', null=True, blank=True) class Meta: verbose_name = "Settings" verbose_name_plural = 'Settings' def __str__(self): return "Settings" I need to get in one case "start_message", and in another "login_message". I read the documentation, but can't find any answer. The last which I tried was print(Settings.objects.get()) And I get just 'Settings' -
Django Forms: RelatedManager' object has no attribute
I have a model defined like this: class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') text = models.CharField('Question', max_length=255) Question_Img = models.ImageField(upload_to='quizzes/', null=True, blank=True) def __str__(self): return self.text class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') text = models.CharField('Answer', max_length=255) is_correct = models.BooleanField('Correct answer', default=False) Answer_Img = models.ImageField(upload_to='answers/', null=True, blank=True) I try to get the image field in a form, however end up resulting in an "RelatedManager' object has no attribute 'Answer_Img'": class TakeQuizForm(forms.ModelForm): answer = forms.ModelChoiceField( queryset=Answer.objects.none(), widget=forms.RadioSelect(), required=True, empty_label=None) class Meta: model = StudentAnswer fields = ('answer',) def __init__(self, *args, **kwargs): question = kwargs.pop('question') super().__init__(*args, **kwargs) self.fields['answer'].queryset = question.answers.order_by('text') # THIS WORKS self.fields['Answer_Img'].queryset = question.answers.Answer_Img # THIS IS DEFECT I was already able to retrieve the "text" from the Answer-object.. However, it fails to show the "Answer_Img". Goal is to show the image Upload via Form. Does anybody know what the issue is and how to fix it? -
Can we use " RequestContext " in django to update values in div?
I want to update some values in view. temparature.html <table id="test"><tbody> <tr> {% for label, value in temperature.items %} <td >{{ label }}</td> <td>{{ value }}</td> {% endfor %} </tr> </tbody></table> Can I use the RequestContext method in Django to update the values of the temperature variable in the Django HTML template? -
Assertion Error cannot filter a query once a slice has been taken
I have two class in my models.py class Icd(models.Model): code = models.CharField(primary_key=True, max_length=6) class Icd10(models.Model): officialorder = models.IntegerField(blank=True, null=True) And also there are two viewsets for above models class IcdViewSet(viewsets.ModelViewSet): queryset = Icd.objects.all()[:10] serializer_class = IcdSerializer class Icd10ViewSet(viewsets.ModelViewSet): queryset = Icd10.objects.all()[:10] serializer_class = Icd10Serializer Below is my serializer class IcdSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Icd fields = ['code'] class Icd10Serializer(serializers.HyperlinkedModelSerializer): class Meta: model = Icd10 fields = ['officialorder'] And my app/urls.py router = routers.DefaultRouter() router.register(r'', views.IcdViewSet) router.register(r'icd10', views.Icd10ViewSet) urlpatterns = [ path('', include(router.urls)) ] main urls.py urlpatterns = [ path('icd/', include('app.urls')), ] When i call localhost:8000/icd, i am getting correct response. When i call localhost:8000/icd/icd10, am getting below error AssertionError at /icd/icd10/ Cannot filter a query once a slice has been taken. Request Method: GET Request URL: http://localhost:8000/icd/icd10/ Django Version: 3.1.4 Exception Type: AssertionError Exception Value: Cannot filter a query once a slice has been taken. what needs to be changed to retrieve records from Icd10 models? -
ProgrammingError at /db/ (snowflake.connector.errors.ProgrammingError) 252004:: Binding data in type (engine) is not supported
ProgrammingError at /db/ (snowflake.connector.errors.ProgrammingError) 252004: Failed processing pyformat-parameters; 255001: Binding data in type (engine) is not supported. [SQL: SELECT * FROM INGESTDB_DEV] [parameters: (Engine(snowflake://etladmin_dev:@xeroxcdp.east-us-2.azure/cpn_ingestdb_qa/ingest_admin?cache_column_metadata=True&warehouse=etl_nonprod_xs),)] (Background on this error at: http://sqlalche.me/e/f405) Request Method: GET Request URL: http://127.0.0.1:8000/db/ Django Version: 3.0.5 Exception Type: ProgrammingError Exception Value: (snowflake.connector.errors.ProgrammingError) 252004: Failed processing pyformat-parameters; 255001: Binding data in type (engine) is not supported. [SQL: SELECT * FROM INGESTDB_DEV] [parameters: (Engine(snowflake://etladmin_dev:@xeroxcdp.east-us-2.azure/cpn_ingestdb_qa/ingest_admin?cache_column_metadata=True&warehouse=etl_nonprod_xs),)] (Background on this error at: http://sqlalche.me/e/f405) Exception Location: C:\ProgramData\Anaconda3\lib\site-packages\snowflake\connector\errors.py in default_errorhandler, line 89 Python Executable: C:\ProgramData\Anaconda3\python.exe Python Version: 3.7.6 Python Path: ['C:\Users\Priyanka\Desktop\Cogni_demo\Department', 'C:\ProgramData\Anaconda3\python37.zip', 'C:\ProgramData\Anaconda3\DLLs', 'C:\ProgramData\Anaconda3\lib', 'C:\ProgramData\Anaconda3', 'C:\ProgramData\Anaconda3\lib\site-packages', 'C:\ProgramData\Anaconda3\lib\site-packages\win32', 'C:\ProgramData\Anaconda3\lib\site-packages\win32\lib', 'C:\ProgramData\Anaconda3\lib\site-packages\Pythonwin'] Server time: Mon, 28 Dec 2020 08:14:14 +0000 my views.py def snowconn(request): registry.register('snowflake','snowflake.sqlalchemy','dialect') engine = create_engine(URL( account = 'xxxx', user = 'xxxx', password = 'xxxx', database = 'xxxx', warehouse = 'etl_nonprod_xs', schema = 'ingest_admin', cache_column_metadata=True )) connection = engine.connect() ds= connection.execute("SELECT * FROM INGESTDB_DEV", engine).fetchone() df = pd.read_sql_query("SELECT TOP 10 * FROM INGESTDB_DEV.CDDS_DATA.FB_HFSI_HIST", engine) cs = df.to_sql('test_table1',con=engine,schema='CPN_CNSLD_SEC_CORE',if_exists='replace',index=False) return df Trying to connect snowflake database with django. -
how do i send the form data to excel in Django | python
I want the Django forms data to be sent to an excel file I wold like to know how would i render it in the views.py and other files required -
Ajax pass data into table Django
I'm having a trouble on how can I pass data from ajax success to tables.Is there any way how to display list in tables? Ajax success success: function(response){ for(i = 0; i<response.list_reports.length;i++){ console.log(response.list_reports[i]) } $("#rports").modal('show'); $("#rports").val(null).trigger("change"); } My tables <table class="table table-striped table-bordered base-style"> <thead> <tr> <th>samplee</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> <tfoot> <tr> <th>Name</th> </tr> </tfoot> </table> -
Django DRF get request query param in custom decorator applied on a function in viewsets.ViewSet
In django rest framework when create a custom viewsets.ViewSet can we apply a custom decorator on a specific function in that ViewSet? class UserViewSet(viewsets.ViewSet): """ Example empty viewset demonstrating the standard actions that will be handled by a router class. If you're using format suffixes, make sure to also include the `format=None` keyword argument for each action. """ @permission_classes([IsAuthenticated]) @custom_decorator_1() def list(self, request): pass @custom_decorator_2() def create(self, request): pass @custom_decorator_3() def retrieve(self, request, pk=None): pass def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): pass If yes then how can we get query parameters inside that custom decorator applied on a ViewSet? Or is there any alternate solution to achieve this where I can apply multiple decorators on a ViewSet action? Right now I am trying to do it in this way: def custom_decorator(): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): role = request.query_params['role'] return view_func(request, *args, **kwargs) return wrapper return decorator Error received: AttributeError: 'UserViewSet' … -
Razorpay integration in django
I want to change razorpay data-amount dynamically according to amount that i set in input tag of html index.html {% extends 'base.html' %} {% block content %} <form action="/success/" method="POST"> {% csrf_token %} <input type="name" name="name" id="name" required class="form-control mb-4" placeholder="Name"> ------------------------------------------------------------------------------------------------------------ | <input type="number" name="amount" id="amount" required class="form-control mb-4" placeholder="amount"> | ------------------------------------------------------------------------------------------------------------ <input type="submit" class="btn btn-success" value="Submit"> </form> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="rzp_test_USdeDvKmBCAmHz" data-amount="{{payment.amount}}" data-currency="INR" data-order_id="{{payment.id}}" data-buttontext="pay with razorpay" data-name="abc corp" data-description="Test transaction" data-image="https://example.com/your_logo.jpg" data-prefill.name="Gaurav Kumar" data-prefill.email="gaurav.kumar@example.com" data-prefill.contact="9999999999" data-theme.color="#F37254" ></script> <input type="hidden" custon="Hidden Element" name="hidden"> {% endblock %} I'm taking input from input tag that I marked above in the box with name="amount". then in my views.py I'm receiving that as views def home(request): if request.method == "POST": name = request.POST.get("name") amount = request.POST.get("amount") client = razorpay.Client(auth=("rzp_test_USdeDvKmBCAmHz","KaE4ygFQcjE9y9X2YySqNcFn")) payment = client.order.create({'amount':amount , 'currency':'INR' , 'payment_capture':'1'}) print(name , amount) return render(request,'index.html',{'payment':payment}) then I'm assigning that amount in payment dictionary as payment = client.order.create({'amount':amount , 'currency':'INR' , 'payment_capture':'1'}) and accessing that in script tag of my index.html data-amount="{{payment.amount}}" to dynamically change the amount but razorpay gives an error. but when I'm assigning data-amount manually . data-amount="50000" then its working. i also did the csrf_exempt in my views.py -
ModelForm validating data for new instance even after passing instance in form
I am creating view for edit data. I am using same model form and html script to create and edit data. In create view I am passing instance in form but form.is_valid is validating data fro new instance. models.py class Van(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='vans') slug = models.SlugField(max_length=200) number_plate = models.CharField(max_length=15, unique=True) commercial_name = models.CharField(max_length=100) forms.py class VanForm(forms.ModelForm): class Meta: model = Van fields = ('commercial_name', 'number_plate', ) def clean_number_plate(self): number_plate = self.cleaned_data['number_plate'] van = Van.objects.filter(number_plate=number_plate).exists() if van: raise forms.ValidationError("A van with this number plate has been registered.") return number_plate views.py def edit_van_detail(request, slug): van = get_object_or_404(Van, slug=slug) van_form = VanForm(instance=van) if request.method == 'POST': van_form = VanForm(request.POST, request.FILES, instance=van) if van_form.is_valid(): return HttpResponseRedirect(reverse('edit_van_detail', args=(van.slug,))) context = { 'van_form': van_form, } return render(request, 'van/add_van.html', context) Create is working fine. But on Edit page, when I submit form, it gives unique validation error ("A van with this number plate has been registered.") which I wrote in modelForm. I have done this before without any issue but this time I dont whats wrong. -
django transaction can not rollback in millisecond
I'm using django-rest-framework for my website and I control users points and permission for selecting a new reward, but I have some problem users can choose two rewards with millisecond difference but because they don't have enough point our system shows them negative point because (if user select reward, user total point should subtract by reward_point) and now I have problem with this activity of my system, I controlling transactions with raising exceptions to rollback if the user doesn't have enough points. this is my code @atomic def grant_cycle_reward_to_outlet(self, user, reward_id, count): # TODO outlet = self.get_outlet_by_user(user) current_cycle = self.cycle_dao.get_current_cycle() reward = self.reward_dao.get_reward(reward_id) if not reward: raise NotFoundObjectException(GeneralConfigConstants.reward) viewable_rewards = self.get_current_outlet_viewable_rewards(user) if reward not in viewable_rewards: raise NotViewableException(GeneralConfigConstants.reward) reward_total_point = int(reward.point * count) if outlet.point < reward_total_point: raise NotEnoughPointException() if int(outlet.point) >= reward_total_point: outlet_cycle_rewards, outlet_cycle_reward = self.outlet_cycle_logic.add_reward_to_outlet(outlet, current_cycle, reward, count) if outlet.point >= reward_total_point: OutletNonAppPointEvent.objects.create( outlet=outlet, point=-1 * reward_total_point, type=OutletPointEventType.grant_reward.value, ) else: raise NotEnoughPointException() self.outlet_point_logic.add_point_diff_to_outlet_points(outlet, -1 * reward_total_point) self.warehouse_logic.consuming(outlet, reward, count, user, outlet_cycle_reward) return outlet_cycle_rewards else: raise NotEnoughPointException() Users can't log in to their client app (mobile) at the same time Thank you