Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying get_context_data in template Django
I am trying to display the get_context_data on the template. I have a method on the model class that I need to call from ProfileView which has two different models. For the Profile View I have Profile Model and for the shippingaddress view I have ShippingAddress Model. And these models are from two different app. I tried the function below and it does not show any error, but when I tried to call it in the Template, It does not show the method. Views.py class ProfileView(LoginRequiredMixin, DetailView): model = Profile template_name = "account/profile.html" success_url = "/" def get_context_data(self, *args, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) context['shipping'] = ShippingAddress.objects.filter(user=self.request.user) return context Template code {{object.get_full_address}} Models.py class ShippingAddress(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone_number = PhoneNumberField(null=True, blank=True) street_address = models.CharField(max_length=300) province = models.CharField(max_length=300) city = models.CharField(max_length=50) country = models.CharField(max_length=50) zip_code = models.CharField(max_length=10) def __str__(self): return str(self.user) def get_phone_number(self): return self.phone_number @property def get_full_address(self): return f"{self.street_address}, {self.province}, {self.city}, {self.country}, {self.zip_code}" -
Cannot assign "<VendorupdateForm bound=True, valid=True, fields=(username;email)>": "VendorImage.vendor" must be a "Vendor" instance
i was trying to upload the multiple images using formset in django while updating the vendor profile but stuck at the above error from few days vendor.py : from django.db import models from .vendorcategory import Vendorcategory from .city import City from django.contrib.auth.models import User from PIL import Image class Vendor(models.Model): name = models.CharField(max_length=150, default="") user = models.OneToOneField(User, on_delete=models.CASCADE, default=1) # city = models.CharField(max_length=50) # vendorcategory= models.CharField(max_length=50) city= models.ForeignKey(City, on_delete=models.CASCADE, default=1) vendorcategory= models.ForeignKey(Vendorcategory, on_delete=models.CASCADE, default=1) state = models.CharField(max_length=50, default="") address = models.CharField(max_length=250, default="") desc= models.CharField(max_length=1150, default='') details= models.CharField(max_length=1150, default="") reviews= models.CharField(max_length=150, default="") phone= models.IntegerField( default="1111111111") pincode = models.IntegerField( default="1111111111") website = models.CharField( max_length=50, default="") email = models.EmailField(max_length=254, default="") facebooklink= models.CharField(max_length=150, default="") instalink = models.CharField(max_length=150, default="") twitterlink = models.CharField(max_length=150, default="") pinterest = models.CharField(max_length=150, default="") images = models.ImageField(upload_to= 'uploads/vendor/', default='uploads/vendor/default.jpg' ) # for uploading multiple images # images = models.FileField(blank=True) location = models.TextField(default='') vendoremail = models.EmailField(default='') vendorpassword = models.CharField(max_length=50, default='') vendorphone = models.CharField(max_length=13, default='') views = models.IntegerField(default=0) @staticmethod def get_all_vendors(): return Vendor.objects.all() @staticmethod def get_all_vendors_by_vendorcategoryid(vendorcategory_id): return Vendor.objects.filter(vendorcategory= vendorcategory_id) def register(self): self.save() def isExists(self): if Vendor.objects.filter(vendoremail = self.vendoremail): return True return False @staticmethod def get_vendor_by_email(vendoremail): try: return Vendor.objects.get(vendoremail=vendoremail) except: return False class VendorImage(models.Model): images1 = models.ImageField(upload_to='uploads/vendor/', default='uploads/vendor/default.jpg') vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, related_name="images1") forms.py : … -
What hosting service should I choose for course website?
I am going to develop the backend for a website that are going to contain videos for our members to watch. We will produce about 50 videos and based on our assessments, we will end up with approximately 5000-10000 members. Does anyone know where and how to host the videos to make it as cheap as possible? (direct link to youtube, and vimeo is not an option). We are using django for backend and postgreSQL database. I tried to use this calculator https://calculator.s3.amazonaws.com/index.html for AWS, but it showed that it will cost us 6000$/month if the videos is 300 MB each. -
Django: How do I allow views and methods with AllowAny permission to bypass authentication with HttpOnly JWT token cookies?
I have applied JWT authentication with HttpOnly cookies using a custom middleware. Now, the middleware checks for the presence of access and refresh tokens as HttpOnly cookies in every request. Everything works well. But, it retuns 'KeyError': 'access' if I request for a page that does not require authentication, say, the homepage or bloglist or blogdetail page. How do I remove this need for access token in these views with permissions set to AllowAny and also in some views where only the GET method permission is set to AllowAny? My view: class TagView(viewsets.ModelViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer def get_permissions(self): if self.request.method == 'PUT': self.permission_classes = [permissions.IsAuthenticated,] elif self.request.method == 'GET': self.permission_classes = [permissions.AllowAny,] elif self.request.method == 'POST': self.permission_classes = [permissions.IsAuthenticated,] return super(TagView, self).get_permissions() If request method is GET, the middleware should pass the request even if no access cookie is found. Now, it checks for the access cookie in every request. I added a line to skip asking for tokens if the request method is GET and if there is no cookie in the request, to mark it as AllowAny view, but I think it is unsafe. My middleware: class AuthorizationHeaderMiddleware: def __init__(self, get_response=None): self.get_response = get_response def … -
Django Generic View (Search and Post Form)
How to Search an athlete and then post a payment in Django Generic View How should I find an athlete in form and then post a payment for the current athlete. Anyone can help me it will be apreciat... I tried this code it finds the athlete but I don't know how to implement the form with it.. views.py class SearchResultsListView(ListView): model = Athlete context_object_name = 'athlete_list' template_name = 'athletes/add-fee.html' def get_queryset(self): # new query = self.request.GET.get('q', None) return Athlete.objects.filter( Q(membership_num__iexact=query) ) code for post the payment ?? This is the template (it is static rightnow) -
Migrate from standard User to Abstract user in Django
I have created a Django Project using the standard User-form. I really need to make use of the email as login (using this guide). The problem is it should be difficult to migrate when I already have used the standard User-form. Since we are only in the testing stage at the moment, I don't mind wiping the entire database to make this migration. Having that in mind, that losing data is not an issue, is there a way to make this migration? -
Post returns 1364, Field 'ADD' doesn't have a default value
THe error upon clicking the POST button on Djangorest Form The serializer: class CreatePolicyBenefitsSerializer(serializers.ModelSerializer): class Meta: model = Policy fields = ('company','name','benefits','price') The views: class CreatePolicyBenefits(CreateAPIView): queryset = Policy.objects.all() serializer_class = CreatePolicyBenefitsSerializer Here the form Is it possible when I hit POST button, the data can be displayed on the form? Thanks -
jQuery not finding class after AJAX response
I have essentially a cart section where a user should be able to remove items from the cart and then the contents are refreshed with AJAX. However, after a cart item is removed the response changes from asynchronous to synchronous and I can't establish why. Sorry new to programming so a lot of things may not be the best way to do something, any help appreciated! Views.py def checkout_detail_api_view(request): customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.cartItems_set.all() '# create lists for items to be put in dictionary' productId_list = [] product_url = [] productName_list = [] location_list = [] img_list = [] checkoutList = {} for item in items: '# append into lists' productId_list.append(item.product_id) productName_list.append(item.product.title) product_url.append(item.product.get_absolute_url()) img_list.append(item.product.image.url) location_list.append(item.product.location) checkoutList["id"] = productId_list checkoutList["title"] = productName_list checkoutList["location"] = location_list checkoutList["image"] = img_list checkoutList["url"] = product_url checkout_data = {"checkoutList": checkoutList} return JsonResponse(checkout_data) def cart_update(request): product_id = request.POST.get('product_id') customer = request.user.customer if product_id is not None: try: product_title = Product.objects.get(id=product_id) except BlogPost.DoesNotExist: print("Show message to user, product is gone?") '# gets or makes product order' order, created = Order.objects.get_or_create(customer=customer, complete=False) '# gets or makes cartItem' cartItem, created = cartItems.objects.get_or_create(order=order, product=product_obj) '# gets all items in cart ' items = order.cartItems_set.all() '# … -
Django model PositiveIntegerField save as 0 if input is blank
How to set django form to assign a field to 0 if input is blank? Here is my model: amount = models.PositiveIntegerField(default = 0, null=False, blank=True) Then on form: self.fields['amount'].required = False Making the amount on template None Required. However, I want this to save as 0 if input field is blank. If possible, I dont want to do this on view. -
django shows error like 'Invalid block tag on line 3: 'else'. Did you forget to register or load this tag?'
following code is from views.py it fetch the profile which is a extension of user module in django also it passes that profile to html as a dictionary. views.py def render_add_req(request): profile = Profile.objects.get(user=request.user) return render(request, 'add_item_request.html', {'profile': profile}) This is the code from html to be rendered and in this I am using is_admin attribute of profile object to determine whether the given user is admin or staff and after that I am determining which bases template to be extend with that html depending on user. add_item_request.html {% if profile.is_admin == 'a' %} {% extends 'admin_base.html' %} {% else %} {% extends 'staff_base.html' %} {% endif %} {% block title %} Item Req : Add {% endblock %} {% block content %} Item Req : Add {% endblock %} -
KeyError "RDS_DB_NAME" when trying to connect PostgresQL with Django with Elastic Beanstalk
I have deployed my Django app (Python 3.7) with AWS Elastic Beanstalk and are trying to connect it with a postgresQL database. Following AWS' tutorial I have three files in my .ebextensions folder: 01_packages.config commands: 01_postgres_activate: command: sudo amazon-linux-extras enable postgresql10 02_postgres_install: command: sudo yum install -y postgresql-devel 03_remove_cmake: command: "yum remove cmake" packages: yum: git: [] amazon-linux-extras: [] libjpeg-turbo-devel: [] cmake3: [] gcc-c++: [] I need cmake3 and gcc-c++ for some python packages I'm running, and I'm removing cmake not to worry about a wrong version of cmake that seems to be installed by default. 02_python.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: mainapp.wsgi:application NumProcesses: 3 NumThreads: 20 aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: mainapp.settings db-migrate.config container_commands: 01_migrate: command: "python manage.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: mainapp.settings I've added a postgresQL DB through EB console. I've also tried first activating the virtual environment in the db-migrate.config file like this: command: "source /var/app/venv/*/bin/activate && python manage.py migrate" But no success. The logs are telling me the 01_migrate command is returning an error. When I eb ssh into the EC2 instance, navigate to my app, activate the venv and then run python manage.py migrate, it gives me a KeyError that os.environ doesn't have a key named 'RDS_DB_NAME'. When … -
how do I avoid getting double array in serializer django?
I am trying to return all of the references for all of the books associated with the author, but however, I am getting an array inside array where I know its because foo in serializer, and ArrayField(models.URLField() , but I want to return as a string instead of an array of arrays. note: the API consume as a read-only so doesn't matter writeable fields class Books(models.Model): id = models.CharField(max_length=255) summary = models.TextField(blank=True, null=True) last_modified = models.DateTimeField(auto_now=True) class References(models.Model): bookid = models.ForeignKey(Vulnerabilities, on_delete=models.SET_NULL, null=True) references = ArrayField(models.URLField(),null=True, blank=True, default=list) serializer class ReferencesSerializer(serializers.ModelSerializer): class Meta: model = References fields = ("references",) class BooksSerializer(serializers.ModelSerializer): foo = serializers.SerializerMethodField() class Meta: model = Books fields = ('id','summary','foo', 'last_modified',) def get_foo(self, value): items = References.objects.filter(bookid=value) serializer = BooksSerializer(instance=items, many=True) return serializer.data viewset class BooksViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Books.objects.all() serializer_class = BooksSerializer def get_queryset(self): search = self.request.query_params.get('search', None) if search is not None: self.queryset = self.queryset.filter( Q(summary__icontains=search) | Q(id__iexact=search) ) return self.queryset response { "count":1, "next":null, "previous":null, "results":[ { "id":"2021-3420", "summary":"", "foo":[ [ "www.google.com", "gksjksjs.com" ] ], "last_modified":"2021-03-06T00:41:00Z" } ] } -
Making form fields - read only or disabled in DJANGO updateView
I have a model which I will update using an updateView generic class based function. How can I make specific fields as read only ? example : Models.py: class Employee(models.Model): emp_no = models.IntegerField( primary_key=True) birth_date = models.DateField() first_name = models.CharField(max_length=14) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) hire_date = models.DateField() class Meta: verbose_name = ('employee') verbose_name_plural = ('employees') # db_table = 'employees' def __str__(self): return "{} {}".format(self.first_name, self.last_name) views.py : lass EmployeeUpdate(UpdateView): model = Employee fields = '__all__' How can I make the first_name readonly inside a UpdateView ? Note: I want to have the model(charfield) the same, But it should be read only inide an UpdateView. -
ApplicantEducation matching query does not exist
This function in views.py views.py def UpdateEducation(request): context = {} user_obj = request.user if not user_obj.is_authenticated: return redirect('login') user_id = Applicant.objects.filter(app_id = user_obj.app_id).first() print(user_id) applicant = ProfileInfo.objects.filter(user=user_id).first() print(applicant) user_info = ApplicantEducation.objects.filter(applicant_info = applicant).get() if request.POST: form = EducationForm(request.POST, instance=user_info) if form.is_valid(): obj = form.save(commit=False) obj.applicant_info = applicant print(obj) obj.save() return redirect('profile') else: form = EducationForm() context['education_form'] = form else: try: form = EducationForm( initial={ 'institute_name': user_info.institute_name, 'marks_percentage' : user_info.marks_percentage, 'affilation_with' : user_info .affilation_with, 'date_completion':user_info.date_completion, 'degree_details' : user_info.degree_details, } ) context['education_form']= form except: form = EducationForm() context['education_form']= form return render(request, 'admission/signup.html', context) This model class i made for views.py models.py class DegreeDetails (models.Model): degree_name = models.CharField(max_length=10) degree_category = models.CharField(max_length= 15) def __str__(self): return '%s %s'%(self.degree_name, self.degree_category) class ApplicantEducation(models.Model): applicant_info = models.ForeignKey(ProfileInfo, on_delete=models.CASCADE) degree_details = models.ForeignKey(DegreeDetails, on_delete= models.CASCADE) marks_percentage = models.FloatField(max_length=5, default=0.0) institute_name = models.CharField(max_length=100) affilation_with = models.CharField(max_length= 50) date_completion = models.DateField(auto_now_add=False, blank=True) This is the form class for the model..... forms.py class EducationForm( forms.ModelForm): class Meta: model = ApplicantEducation fields = [ 'institute_name', 'marks_percentage', 'affilation_with', 'date_completion', 'degree_details', ] def clean(self): if self.is_valid(): institute_name = self.cleaned_data['institute_name'] marks_percentage = self.cleaned_data['marks_percentage'] affilation_with = self.cleaned_data['affilation_with'] date_completion = self.cleaned_data['date_completion'] degree_details = self.cleaned_data['degree_details'] This the error i got Error ApplicantEducation matching query does not exist. Request Method: … -
Text type hints: inspection detects names that should resolve but don't
Django 3.1.7 Pycharm Community 2020.3 ├── images │ ├── models.py │ ├── model_utils.py │ ├── tests.py │ └── views.py In the directory of 'images' application I've organized model_utils. The easiest case of a function in model_utils is for finding upload dir: def raster_img_upload_to(instance: Union["images.models.RasterImage", "images.models.ResponsiveImage"], file_name: str) -> str: responsive_image_cls = apps.get_model("images.ResponsiveImage") raster_image_cls = apps.get_model("images.RasterImage") # //@formatter:off # Assertions { assert isinstance(instance, (responsive_image_cls, raster_image_cls)) # } Assertions # //@formatter:on if isinstance(instance, responsive_image_cls): an_id = instance.raster_image.id else: an_id = instance.id result = get_image_upload_to(an_id=an_id, file_name=file_name, img_dir=general.ImgDirs.RASTER) # //@formatter:off # Assertions { assert isinstance(result, str) # } Assertions # //@formatter:on return result There are several functions of the type. That's why I moved them all in a separate package model_utils.py. The problem is that I have two warnings in PyCharm: "Unresolved reference 'images'". Correct detecting type hints errors is a key point for me. That is why I can't just ignore it. IDE's message: Unresolved reference 'images' Inspection info: This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items. One way suggested by the IDE is … -
Trying to identify the correct Python/Django unit testing solution - unittest vs pytest vs "manage.py test" vs...?
I'm new to Python and Django, as well as writing unit tests for either or both, and am trying to navigate the landscape of testing solutions as well as resolving some runtime errors (namely "Apps aren't loaded yet" when using "python -m unittest tests/tests.py"). I've been reading forum posts and tutorials for several hours and I seem to end up with more questions than answers. What I'm trying to do, as part of Agile methodology training, is implement basic get/display/show functionality on a Django model and write tests showing that the serializers are generating the proper output based on records in the database (or created by a factory and faker, which is another layer of complexity I'm attempting to wrangle). I've been advised to use AssertEquals statements to validate JSON serializer output against what's contained in a given database row, with the latter being generated by a faker, inserted via a factory and stored in a variable to use by AssertEquals when comparing values. I have an idea of the logic and how I would write it, but I'm currently getting tripped up by the errors along with trying to sort out what's the best testing framework to use and … -
Having git problem in React django project
STATEMENT I want to make project with django backend and React frontend. I have created a project using and then create a frontend react folder using create-react-app. Now I want to upload my projectname folder to my github repository. But when I add my files using git add . command from my root folder('projectname' folder). It shows some warnings given below. What should I do? Please help. WARNING hint: You've added another git repository inside your current repository. hint: Clones of the outer repository will not contain the contents of hint: the embedded repository and will not know how to obtain it. hint: If you meant to add a submodule, use: hint: hint: git submodule add <url> frontend hint: hint: If you added this path by mistake, you can remove it from the hint: index with: hint: hint: git rm --cached frontend COMMAND THAT I HAVE USED $ virtualenv env $ source env/bin/activate $ pip install django $ django-admin.py startproject projectname $ cd django-react-demo $ npm install -g create-react-app $ create-react-app frontend MY FOLDER STRUCTURE projectname │ └───frontend │ ├──.node_modules │ ├──public │ ├──src │ ├──gitignore │ ├──README.md │ ├──package.json │ └──package_lock.json │ │projectname │ ├── __init__.py │ ├── settings.py … -
Python queryto get height price user with count
I have two tables like : User: Id | Name | Age | 1 | Pankhuri | 24 2 | Neha | 23 3 | Mona | 25 And another Price log: Id | type | user_id | price | created_at| 1 | credit | 1 | 100 | 2021-03-05 12:39:43.895345 2 | credit | 2 | 50 | 2021-03-05 12:39:43.895345 3 | debit | 1 | 100 | 2021-03-04 12:39:43.895345 4 | credit | 1 | 100 | 2021-03-05 12:39:43.895345 These are my two tables from where i need to get heighst credit price user with their total price count acoording to last week date.. i want a result like : like if i want to get result for user id 1 then result should be like: pankhuri on date 04/03 price 100 and on date 5 pankhuri on date 05/03 price 200 want only heighst price user in retirn with their price total on date basisi. -
No error message, redirect to detailview using slug and get_absolut_url()
** I'm trying to link my detalview to the listview and can't understand how to redirect my title blog to the detailview template. This is my first project. I'm using slug and don't know if the problem is in hear. There's no error message. Just don't work at all. ** models.py class Story(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, blank=True) report = models.TextField() pubdate = models.DateTimeField(auto_now=True, editable=False) author = models.ForeignKey( 'User', on_delete=models.CASCADE, blank=True, null=True ) class Meta: ordering = ['-pubdate'] def __str__(self): return self.title def get_absolute_url(self): return reverse('storiesdetail', kargs={'slug', self.slug}) urls.py urlpatterns = [ path('', views.index, name='index'), path('allauthors/', views.AuthorsList.as_view(), name='all-authors'), path('allstories/', views.StoriesList.as_view(), name='all-stories'), path( 'allstories/<slug:slug>/', views.StoriesDetail.as_view(), name='story-detail', ), ] views.py class StoriesList(ListView): models = Story template_name = 'story_list.html' queryset = Story.objects.all() context_object_name = 'stories' class StoriesDetail(DetailView): models = Story template_name = 'story_detail.html' story_list.html {% extends "base.html" %} {% block content %} <ul> {% for story in stories %} <li><a href="{{ title.get_absolute_url }}">{{ story.title }}</a> - {{ story.pubdate }} - <a href="{{ author.get_absolute_url }}">{{ story.author }}</a></li> {% empty %} <li>Sorry, no story in this list.</li> {% endfor %} </ul> {% endblock %} -
Django ImageField Template Injection
I have checked multiple sources and I can't find any pattern to how the template tags are referenced for ImageFields. Can someone please explain to me every single little part to the template tag call. For instance, {{emp.emp_image.url}} - the first spot before the period has no reference anywhere I look. Not in views, models. No references ever. The second argument is the Field in the model and then urls is a Django argument. What is the first part? {% load static %} <!DOCTYPE html> <html> <body> <h1>Name - {{emp.name}}</h1> <img src="{{emp.emp_image.url}}" alt="Smiley face" width="250" height="250"> <br /> <a href="{% url 'home' %}">Go Back!!!</a> </body> </html> -
Django Timezone Configuration
My django project is correctly enable the timezone in settings. However, the datetime field of Django ORM object is a naive datetime object as shown in Block 3. The expected result should be same as the output of Block 4 without any manually conversion. In [1]: from django.conf import settings ...: settings.USE_TZ, settings.TIME_ZONE Out[1]: (True, 'Asia/Hong_Kong') In [2]: from qms.models import Quota In [3]: q = Quota.objects.get(pk=1) ...: q.create_date, q.write_date Out[3]: (datetime.datetime(2021, 3, 10, 17, 37, 42, 489818), datetime.datetime(2021, 3, 10, 17, 37, 42, 489818)) In [4]: from django.utils import timezone ...: timezone.make_aware(q.create_date,timezone.utc), timezone.make_aware(q.write_date, time ...: zone.utc) Out[4]: (datetime.datetime(2021, 3, 10, 17, 37, 42, 489818, tzinfo=<UTC>), datetime.datetime(2021, 3, 10, 17, 37, 42, 489818, tzinfo=<UTC>)) The database schema and settings, Table "public.qms_quota" Column Type Modifiers id integer not null default nextval('qms_quota_id_seq'::regclass) create_date timestamp with time zone not null write_date timestamp with time zone not null name character varying(255) not null SHOW TIMEZONE; TimeZone ---------- UTC Questions How can I get the timezone-aware datetime object directly without any conversion? Or the manual conversion is expected ? -
Problem is that imgge is not saving . when i am select image and upload all code working propely but image does not save django
Problem is that imgge is not saving . when i am select image and upload all code working propely but image does not save. i chacked all the code line by line i am not understand wwhats the problem. i also see the media file any image is saved or not ,but there no image was saved please help me this is models.py in this file i use image field models.py class Answer (models.Model): question=models.ForeignKey(Question,on_delete=models.CASCADE) user=models.ForeignKey(User,on_delete=models.CASCADE, null=True) img=models.ImageField(null=True,blank=True,upload_to='Answer_Img') detail=RichTextUploadingField() add_time=models.DateTimeField(auto_now_add=True) def __str__(self): return self.detail forms.py class AnswerForm(ModelForm): class Meta: model=Answer fields=('detail','img') labels={'img':'Upload Image'} views.py def answer(request,pk,slug): try: trend=Question.objects.get(pk=pk,slug=slug) except: raise Http404("Post Does Not Exist") tags=trend.tags.split(',') ans=Answer.objects.filter(question=trend) answerform=AnswerForm if request.method=='POST': answerData=AnswerForm(request.POST) if answerData.is_valid(): answer=answerData.save(commit=False) answer.question=trend answer.user=request.user answer.save() p=messages.success(request,'Answer has been submitted.') return HttpResponseRedirect(trend.slug) return render(request,"ask/answer.html" ,{ 'trends':trend, 'tags':tags, 'answer':ans, 'form':answerform, }) answer.html {% if user.is_authenticated %} <div class="container"> <div class="py-5 text-center bg-secondary text-white"> <h1 class="mb-3">Upload Image</h1> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" class="btn btn-danger" value="Upload"> </form> </div> {% else %} <h3><P>Sign In/Sign Up before posting answers</P></h3> <h4><li><a href="{% url 'account_login' %}" class=" text-left text-info">Sign In</a></li><h4> <h4> <li><a href="{% url 'account_signup' %}" class=" text-left text-info">Sign Up</a></li><h4> {% endif %} settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = … -
trying to pass datetime into mysql table (django) but ValueError: unconverted data remains
so the time format in the data is given as: 2018-12-01T00:00:54HKT since "HKT" can't be parsed in a datetime object, i decided to replace all instances of "HKT" with a blank string and to make a naive datetime object aware. however, I kept encountering AttributeError: 'str' object has no attribute 'tzinfo' errors (the .replace(tzinfo=None) parameter doesn't seem to work for me), so i gave up on that approach and I'm just trying to convert "HKT" to GMT+0800 to parse it in as %Z to get an aware datetime object. however, this code: from mysite.models import Member, Driver, Order import json import argparse import django from django.conf import settings from django.utils import timezone import sys import os #from datetime import datetime #from pytz import timezone import pytz import datetime import pymysql pymysql.install_as_MySQLdb() for member in data: data_members = {} if 'memberID' in member: data_members['memberID'] = member['memberID'] if 'createdTime' in member: #createdTime = str(member['createdTime']) createdTime = str(member['createdTime']).replace("HKT", "GMT+0800") # remove so time can be parsed as datetime object #print(createdTime) createdTime = datetime.datetime.strptime(createdTime, "%Y-%m-%dT%H:%M:%S%Z") print(createdTime) #print(type(createdTime)) # type datetime object createdTime = createdTime.strftime(datetime_format) aware_createdTime = timezone.make_aware(createdTime, hkt) #print(type(createdTime)) # type string #print(createdTime) # createdTime = createdTime.replace(tzinfo=hkt) # createdTime = createdTime.astimezone(hkt) # createdTime_aware = … -
My view object has no attribute 'META', why is this happening?
I run into AttributeError: 'ConstanciaInscripcion' object has no attribute 'META' when I try to post my request. I am not sure what happened because it was working perfectly fine until today. Is the error in the view or somewhere else? I says " 'ip': lambda r: ip_mask(r.META['REMOTE_ADDR']), " right before the error so maybe that's related to it? What's wrong with the code? This is the view: from django.shortcuts import render, HttpResponse import requests from django.views.generic import FormView from .forms import MonotributoForm from app.ws_sr_padron import ws_sr_padron13_get_persona from app.captcha import resolve_simple_captcha from app.constancia_email import constancia_email from ratelimit.decorators import ratelimit #selenium from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from time import sleep #screenshot pdf import io from PIL import Image from importlib import reload import sys class ConstanciaInscripcion(FormView): def get(self, request): return render(request, 'app/constancia-inscripcion.html') @ratelimit(key='ip', rate='3/d') def post(self,request): form = MonotributoForm(request.POST) email = request.POST['Email'] #Verificar cuit en padron13 una vez que es ingresado cuit_r = int(request.POST["CUIT"]) response = ws_sr_padron13_get_persona(cuit_r) try: nombre = response["persona"]["nombre"] apellido = response["persona"]["apellido"] cuit = response["persona"]["tipoClave"] except KeyError: nombre, apellido = None, None print("El CUIT ingresado es incorrecto") except TypeError: nombre, apellido = None, None print("El CUIT ingresado … -
why this problem while using Django Rest Framework
module rest_framework unresolved import 'rest_framework'Python(unresolved-import) No quick fixes available