Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
long running task manager project
I have to implement a project in which the user can stop the long-running task at any given point in time, and can choose to resume or terminate it. This will ensure that the resources like compute/memory/storage/time are used efficiently at our end, and do not go into processing tasks that have already been stopped (and then to roll back the work done post the stop-action). I also have to create Rest API endpoints. Can anyone help with intuition? -
Adding your own language for translation in Django
We need to make a translation into the Bashkir language on the site. This does not seem to exist in the locale django file. I'm trying to do this. In the settings.py file added. import django.conf.locale EXTRA_LANG_INFO = { 'ba': { 'bidi': False, 'code': 'ba', 'name': 'Bashkir', 'name_local': 'башкирский' }, } d = django.conf.locale.LANG_INFO.copy() d.update(EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = d LANGUAGE_CODE = 'ru' LANGUAGES = ( ('ru', 'Russian'), ('en','English'), ('ba', 'Bashkir'), ) Now, when following the link, it writes that it cannot find the / ba page. I display links on the page as follows.(When switching to ru and en, the translation goes without problems). {% for language in languages %} <a href="/{{ language.code }}/"}>{{ language.code }} </a> {% endfor %} in urls + = i18n_patterns added. Maybe there is some other way? Or how to finish the given one? -
Using App name with Django.contrib.auth views
I am new to Django and I am creating a user change password page. However, I keep encountering a NoReverseMatch error which I suspect is due to my app name but I am not able to resolve it even after spending hours googling for a solution. My urls.py file: from os import name from django.urls import path from account import views from django.contrib.auth import views as auth_views # Import Django built-in authentication views app_name = 'account' urlpatterns = [ path('test/', views.test_login, name='test'), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), ] My settings.py: # Login Logic LOGIN_REDIRECT_URL = 'account:test' # Tells Django which URL to redirect user to after a successful login if no next parameter is present in the request LOGIN_URL = 'account:login' # The URL to redirect the user to log in - based on the name in the urls.py LOGOUT_URL = 'account:logout' # The URL to redirect the user to log out - based on the name in the urls.py Much help is appreciated. -
How to get only content from JSON using Regex
How to get JobTitle from following json which item have "Country":"CN" {"Data":[{"JobTitle":"Asset Management Analyst","Country":"CN","City":"Shenzhen","DisplayJobId":"349356BR","UrlJobTitle":"Asset-Management-Analyst","JobId":1041047,"Latitude":22.54286,"Longitude":114.059563},{"JobTitle":"Package Consultant: SAP C/4 HANA C4C","Country":"CN","City":"Bangalore","DisplayJobId":"349128BR","UrlJobTitle":"Package-Consultant-SAP-C-4-HANA-C4C","JobId":1041046,"Latitude":12.976746,"Longitude":77.57528},{"JobTitle":"Package Specialist: SAP HANA Security","Country":"IN","City":"Pune","DisplayJobId":"348219BR","UrlJobTitle":"Package-Specialist-SAP-HANA-Security","JobId":1041045,"Latitude":18.528904,"Longitude":73.87435},{"JobTitle":"Cloud Developer (Go Lang)","Country":"CN","City":"Bangalore","DisplayJobId":"349318BR","UrlJobTitle":"Cloud-Developer-(Go-Lang)","JobId":1041026,"Latitude":12.976746,"Longitude":77.57528},{"JobTitle":"Watson AI Site Reliability Engineering Team Manager","Country":"IN","City":"Bangalore","DisplayJobId":"348769BR","UrlJobTitle":"Watson-AI-Site-Reliability-Engineering-Team-Manager","JobId":1041025,"Latitude":12.976746,"Longitude":77.57528},{"JobTitle":"Site Reliability Engineering (SRE)","Country":"IN","City":"Bangalore","DisplayJobId":"348768BR","UrlJobTitle":"Site-Reliability-Engineering-(SRE)","JobId":1041024,"Latitude":12.976746,"Longitude":77.57528},{"JobTitle":"Site Reliability Engineering (SRE)","Country":"IN","City":"Bangalore","DisplayJobId":"348765BR","UrlJobTitle":"Site-Reliability-Engineering-(SRE)","JobId":1041023,"Latitude":12.976746,"Longitude":77.57528} -
Trying to use multiple listviews on one HTML file?
I'm trying to create a website where I can display my projects, and for each project I can include programming languages used that are also a model. I created a couple of different programming languages, then tried making a project and selected some programming languages I used, but when I run the server, the languages used don't show up like I intended (refer to HTML code in the {%for language in languages%}) My models page is like this: from django.contrib.auth.models import User from django.utils import timezone class Language(models.Model): name = models.CharField(max_length=12) icon = models.ImageField(upload_to="languages/", null=True) def __str__(self): return self.name class Project(models.Model): name = models.TextField(max_length = 75) description = models.TextField(max_length=300) gitlink = models.CharField(max_length=100) image = models.ImageField(null=True) languages = models.ManyToManyField(Language) author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.name My HTML file is like this: {% block content %} <div class="projects"> {% for project in projects %} <div class="project"> <h2>{{ project.name }}</h2> <p> {{ project.description }}</p> <img src="{{ project.image.url }}" style="width: 800px; height: 600px;"> <p>GitHub: {{ project.gitlink }}</p> {% for language in languages %} <p>{{ language.name }}</p> <img src="{{ language.icon.url }}" style="width: 60px; height: 60px;"> {% endfor %} </div> {% endfor %} </div> {% endblock %} And my views page … -
Cannot access form.first_name and form.email from django default authentication form
I am using the default Django AuthenticationForm() for the user login feature. Now when I see inside the user model in Django admin it has fields like username, email address, first name last name and active status. But in my sign-in.html page I can only access form.username and form.password, but cant access to form.email and form.first_name?? My views: def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() authlog(request, user) return redirect('home') else: messages.error(request, 'Invalid username or password') # back_page = request.META.get('HTTP_REFERER') return redirect('login') # messages.error(request, student_form.errors, 'Incorrect') # return HttpResponse(back_page) else: content = { 'form': AuthenticationForm() } return render(request, 'sign-in.html', content) <div class="input-group"> <span class="input-group-text" id="basic-addon1"><span class="fas fa-envelope"></span></span> {{form.emailaddress}} </div> <div class="input-group"> <span class="input-group-text" id="basic-addon2"><span class="fas fa-unlock-alt"></span></span> {{form.password}} </div> Here I can access form.password and form.username but cant login with email address. But we know we should be able to login with email address as well. I have the picture here of the html page. Sign-In Page -
Having Problem in adding redirect URL on Faliure of payment razorpay python?
I am using Django Web Framework for my E-commerce Website, and Using Razor-pay as my payment gateway. The Problem is that I cannot make a track of users with failed payments, So I need to make a redirect URL for every failure payments, So that I can Save the order and redirect it to any URL for the Customers. I am using razorpay python library. Python version = 3.6.8 Django version = 2.2.3 Thank You -
Get constant incoming post requests from multiple devices with Django Rest Framework or listen TCP Server Socket
I have IoT devices which are rfıd readers. This devices send stream data with HTTP Post message. I use Django to get data from these devices. While receiving this data, I can write a function to get data from post requests coming directly with Django and receive the data from the request in this function with Django REST Framework or I can listen with a TCP Server socket. Which of these two approaches is more suitable for retrieving data? Because when I use a TCP Server socket, Django REST Framework does not work for HTTP requests, only the TCP socket works. -
How to add a property to a model which will be calculated based on input?
class TransactionHistory(models.Model): from_account = models.ForeignKey( 'Account', on_delete=models.CASCADE, related_name='from_account' ) to_account = models.ForeignKey( 'Account', on_delete=models.CASCADE, related_name='to_account' ) amount = models.DecimalField( max_digits=12, decimal_places=2 ) created_at = models.DateTimeField(default=timezone.now) @property def way(self): # Here I need to access a list of user's accounts # (request.user.accounts) to mark the transaction # as going out or in. return def get_own_transaction_history(me_user): my_accounts = me_user.accounts.all() # TODO: mark transactions with way as in and out own_transactions = TransactionHistory.objects.filter( Q(from_account__in=my_accounts) | Q(to_account__in=my_accounts) ) return own_transactions I want to add a "way" property for the model so when I return the queryset via serializer, the user could understand if the transaction is for going out from his account or in. But if I just add property, it can not be calculated with me_user user in mind, AFAIK the property can only access the local model fields like "from_account" or "to_account". -
Using Bootstrap Modal as Register and Login Form. On error the full page is served
I am using jquery.bootstrap.modal.forms.js to load Login and Register form from their url as Modals using the code below: <script> $(function ($, undefined) { // log in & sign up buttons $(".register-btn").modalForm({ modalID: "#registerModal", formURL: "/register-modal/", }); }); $(function ($, undefined) { // log in & sign up buttons $(".login-btn").modalForm({ modalID: "#registerModal", formURL: "/login-modal/", }); }); $(function ($, undefined) { // log in & sign up buttons $(".forgot-password").modalForm({ modalID: "#registerModal", formURL: "/recover-modal/", }); }); </script> HTML code for the modal <div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="registerModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document" style="width:400px;"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="registerModalLabel">Register</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> Modal Code : {% extends 'base.html' %} {% load static %} {% block title %} Login {% endblock %} {% block style %} {% endblock %} {% block content %} <div class="container-fluid "> <div class="row "> <div class="col-sm-12 col-xs-12 col-md-12"> <form class="account-register form-narrow p-3 mb-4 bg-white" id="login_form" method="POST" action="" autocomplete="off"> {% if messages %} <div id="messages"> {% for message in messages %} <div class="alert alert-dismissible alert-info" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span … -
ON deployment to heroku: RelatedObjectDoesNotExist at /admin/login/ User has no profile
I have no problem with regards to the development stage. The problem is when I deploy my web thru heroku. i got an error everytime I log in or go to my admin.. RelatedObjectDoesNotExist at /admin/login/ User has no profile. Request Method: POST Request URL: https://azheafaith.herokuapp.com/admin/login/?next=/admin/ Django Version: 3.1.4 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no profile. Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py, line 424, in get Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.12 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Mon, 28 Dec 2020 06:18:42 +0000 --any help is highly appreciated.. Thank you -
save uploaded file to aws s3 and path to database in django using boto3
models.py def document_file_name(instance, filename): char_set = string.ascii_uppercase + string.digits dat = "".join(random.sample(char_set * 6, 12)) return 'documents/' + str(instance.created_by_id) + '/' + dat + '_' + re.sub(r'[^a-zA-Z0-9-_.]', r'_', filename); class UploadDocument(models.Model): document = models.FileField(upload_to=document_file_name, blank=True, null=True) other_doc = models.ForeignKey("doc.OtherDocuments") views.py def opportunity_document_add(request, opportunity_id): c = setup_context(request) other_documents = get_object_or_404(OtherDocuments, pk=opportunity_id) c["other_documents "] = other_documents c["other_documents_id"] = other_documents document = UploadDocument(other_doc=other_documents) errors = {} if request.method == "POST": document.type = request.POST.get("type") if "document" in request.FILES: document.document = request.FILES["document"] document.created_by = request.user document.save() cloudFilename = '<someDirectory>/' + document.document.name session = boto3.session.Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) s3 = session.resource('s3') s3.Bucket(AWS_STORAGE_BUCKET_NAME).upload_file(Key=cloudFilename, Body=document.document) else: errors['document'] = "There is no document specified" c['errors'] = errors c['document'] = document return render_to_response( 'documents/document_form.django.html', c, context_instance=RequestContext(request)) Here my file is getting saved to AWS S3 folder but the path is not getting saved to my database