Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python django access live logs while view still running
how to access a list generated by another function while it still running def index(request): return render(request,"index.html") def assigntoken(request): #I got list of users from post request to assign token to each of them I call a class called AssignToken v = AssignToken() #AssignToken class has attribute called log_lst I want to be able to access this log_lst from result view while assigntoken view and class AssignToken still running v.start(users) #this will start loop in users list to assign tokens return redirect('/result') def result(request): #while assigntoken function still running I should be able to access /result to see live logs generated in v.log_lst (AssignToken class object), how to do this?, is it safe to make it global variable, will it be unique for each user access the webapp at same time? context = {'logs':v.log_lst} return render(request,"results.html",context) -
Response From Django Rest Api Framework
I have created lots of API's list this using Django Rest Framework and it is working perfectly fine. But the issue i am facing is that when these API's are executed succesfully, then i am not getting Response like status=true or any response which says it executed successfully. Is there in-built function in rest framework or how can i do it to get success message. # Add Trusty class TrustyAddAPIView(generics.CreateAPIView): queryset = TrustyRequest.objects.all() serializer_class = serializers.TrustyAddSerialzer permission_classes = [IsAuthenticated] # User Trusty Profile Update class TrustyUserProfileUpdateAPIView(generics.RetrieveUpdateAPIView): queryset = User.objects.all() serializer_class = serializers.UserDetailSerialzer permission_classes = [IsAuthenticated] -
Django: The value of the id field is coming None
I want to create a unique id for all my groups in my django project which will help us to easily detect the user action. I have tried the following: Models: class Group1(models.Model): urlhash = models.CharField(max_length=6, null=True, blank=True, unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) group_name = models.CharField(max_length=32) This is the functionality I have given: def save(self): if not self.urlhash: if self.user.profile.user_type == 'Bussiness User': self.urlhash = 'B' + str(self.User.id) + ('00') + str(self.id) else: self.urlhash = 'P' + str(self.User.id) + ('00') + str(self.id) super(Group1, self).save() But str(self.id) is coming None. Can anyone plz explain me why this error is happening? Thank you -
Django crontab not workong in backgroung
I am using django-crontab to run some cron jobs as part of my project. I have a virtual environment setup for this particular project. So after activating the environment, I add the jobs by using the following command : python manage.py crontab add I see that my jobs are succcessfully added to the OS crontab, however when I see the logs, I found that it was not able to find certain modules(read all) that were installed in virtual environment. However if I run those crons manually by passing the hash to the run command it runs successfully. On further inspection I found when the crons are added to the crontab, the python binaries are pointed to the global(system level binaries) instead of the virtual level binaries. The only soulution I can think of is to run pip instal at a system levwl but that will mess up the sanbox environment I intend to create. Any ideas? -
How to filter DataTime field by hour in Django?
I have Django 1.8 and Python 2.7, I need to get orders made per hour the field is DateTimeField close_date = models.DateTimeField(null=True, blank=True) I do the simple loop: for hour in xrange(0, 24): Order.objects.filter(close_date__hour=hour) but it does not filter. -
Is it possible to convert web app to mobile app? [duplicate]
This question is an exact duplicate of: Develop a mobile application based on an existing Django website/app 1 answer I have made full responsive website with DJango as the backend and HTML, CSS and JS as the fronted, but know I want to change my website to an app that can be accessed on Google Play and App Store as well as other platforms. my question is Is it possible to change my web to an app? If YES how??? -
showing entries based on selection type in django
my question is i want to show only particular titles under music_track (musicmodel)field when type = track(title model) in my django admin site class album(models.Model): def get_autogenerated_code(): last_id = album.objects.values('id').order_by('id').last() if not last_id: return "AL-"+str(0) return "AL-"+str(last_id['id']) album_name = models.CharField( max_length=150, blank=False ) music_track = models.ManyToManyField("title") def __str__(self): return (self.album_name) class Meta: verbose_name = "Album" verbose_name_plural = "Albums" class title(models.Model): def get_autogenerated_code(): last_id = title.objects.values('id').order_by('id').last() if not last_id: return "TT-"+str(0) return "TT-"+str(last_id['id']) upc_code = models.CharField(max_length=15, default="N/A", blank=False) display_name = models.CharField(max_length=150, blank=False) type = models.ForeignKey(Asset_Type, on_delete=models.CASCADE, null=True) def __str__(self): return (self.display_name+ " " +self.code) admin.site.register( [album, title] ) -
Django: is_valid for AuthenticationForm doens't work as expected
The problem I'm facing is like this class CustomLoginView(LoginView): form_class = CustomLoginForm template_name = ... This view works. The users can log in when inputting the correct username and password. And I want to use this form other than usual login view. def a_view(request): if not request.user.is_authenticated: if request.method == 'POST': form = CustomLoginForm(request.POST) if form.is_valid(): return HttpResponse("Success") else: form = CustomLoginForm() But for this view, the validation doesn't work even though I input the correct information. forms.py class CustomLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(CustomLoginForm, self).__init__(*args, **kargs) self.fields['username'].label = "Custom Name" self.fields['password'].label = "Custom Name" What am I wrong with this? Also I want to know the way to output the error on console if the form is not valid. -
Django user permissions, chosen groups not showing in custom admin site
I extend my user from AbstractBaseUser and customize my admin site but could not see the chosen user permission, Chosen groups, and available groups models.py from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin, UserManager, ) from django.conf import settings from Django.utils import timezone class User(AbstractBaseUser, PermissionsMixin): """ User model is created """ ball = models.IntegerField(unique=True,db_index=True,default=0) username = models.CharField( max_length=30, unique=True, verbose_name=('username'), help_text=('Required. 3-30 characters. Letters, numbers and _ characters'), ) email = models.EmailField( verbose_name=('email address'), max_length=75, blank=True, null=False, ) is_staff = models.BooleanField( verbose_name=('staff status'), default=False, help_text=('Designates whether the user can log into this admin site.'), db_index=True ) is_active = models.BooleanField( verbose_name=('active'), default=True, help_text=('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.') ) date_joined = models.DateTimeField(('date joined'), default=timezone.now, db_index=True) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = ('user') verbose_name_plural = ('users') description = models.CharField(max_length=40, null=True,default="") first_name=models.CharField(max_length=20,default="") last_name=models.CharField(max_length=20,default="") class Events(models.Model): name=models.CharField(max_length=20) And my admin.py looks like this class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = … -
Python 2 to 3 migration: AttributeError: 'int' object has no attribute 'replace'
We are having two python apps with same database, one is running on python 2 and the other on python 3. We are accessing python 2 app models in python 3 app. While all other models work fine. One model is throwing error when queried : Traceback: File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/contextlib.py" in inner 52. return func(*args, **kwds) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 551. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner 224. return view(request, *args, **kwargs) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func 63. return func.get(self, type(self))(*args2, **kwargs2) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/contrib/admin/options.py" in changelist_view 1662. selection_note=_('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)}, File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/db/models/query.py" in len 232. self._fetch_all() File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/db/models/query.py" in _fetch_all 1118. self._result_cache = list(self._iterable_class(self)) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/db/models/query.py" in iter 62. for row in compiler.results_iter(results): File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in results_iter 847. row = self.apply_converters(row, converters) File "/home/pulkit/.local/share/virtualenvs/morpheus-NvWJB9pm/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in apply_converters 832. value = converter(value, expression, self.connection, … -
Problem using djongo for django 2.1.5 and mongodb 4
I followed the tutorials of installing both mongodb and django. I also installed djongo using pip and updated my settings.py file in my project. But, when I ran python manage.py runserver I get there are no users authenticated error.I need to get it working in a short time so somebody help me. Did I miss something? Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by .wrapper at 0x7fc412ba6400> Traceback (most recent call last): File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/django/core/management/base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in init self.build_graph() File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 61, in applied_migrations if self.has_table(): File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 56, in table_names return get_names(cursor) File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 51, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/djongo/introspection.py", line 46, in get_table_list for c in cursor.db_conn.collection_names(False) File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/pymongo/database.py", line 715, in collection_names nameOnly=True, **kws)] File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/pymongo/database.py", line 677, in list_collections **kwargs) File "/home/habib/.local/share/virtualenvs/habib-HN5dLoHi/lib/python3.6/site-packages/pymongo/database.py", line 631, in _list_collections session=tmp_session)["cursor"] File … -
Is Django using any front end framework or library and which front end framework is best for Django?
Is Django Admin validated their data to client side or server side ? And when we using Django Forms then is still need to use front end framework for data validations ? I red Stackoverflow post Best Ajax library for Django this Question is closed and they recommend Jquery but now we have multiple options. Front end frameworks or libraries React AngularJs Vue backbone ember Jquery Ionic many more I want these things in framework. AJAX Calls Reusable Components Form Validations Structure code Animations No Performance issue Which is best front end framework or library for Django ? -
how to use background url to div with static with s3 in dajngo
i have <div class="p-5 back-image corner-radius" >{{obj.app_name}}</div> for this i need to add css like this .back-image { background: url("/static/boss/slider-2.jpg") 50% fixed; } this is working fine when local host but now i am using s3 bucket to to server static files for this background: url("/static/boss/slider-2.jpg") 50% fixed; // not working still picking localhost background: url("'{{static}}'/boss/slider-2.jpg") 50% fixed; // not working background: url("'{{STATIC_URL}}'/boss/slider-2.jpg") 50% fixed; // not working how to fix this , is this possible ? -
How to access foreign key in a django template? (ListView)
I want to display education data in a Profile ListView template. In my project Profile has one to many education instance, Profile model class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True) full_name = models.CharField(max_length=30, null=True, blank=True) education = models.ForeignKey(Education, on_delete=models.SET_NULL, null=True, blank=True, related_name="education") Education model class Education(models.Model): degree = models.CharField(max_length=100, null=True, blank=True) school = models.CharField(max_length=100, null=True, blank=True) edu_start_date = models.DateField(null=True, blank=True) edu_end_date = models.DateField(null=True, blank=True) def __str__(self): return str(self.degree) CreateView class EducationView(CreateView): form_class = EducationForm pk_url_kwarg = 'pk' template_name = "profile_settings.html" ListView class EducationList(ListView): model = Profile queryset = Profile.objects.all() context_object_name = 'object' pk_url_kwarg = 'pk' template_name = "profile_settings.html" Template {% for obj in profile.education.all %} <div class="col-lg-12"> <h2>{{ obj.degree }}</h2> <br> <div> {{ obj.school }} </div> </div> <br> {% endfor %} Education form saves data to the database but I couldn't fetch it using the template code. Note: I'm using single template for CreateView and ListView. -
How do I make Apache 2.4 use Python 3.7?
I set a VPS (Ubuntu 18.04 LTS) and it has Python 3.6.7 pre-installed. My project was writen in Python 3.7 with django. I run the server and get a 500 error when loading the page. Error log: ModuleNotFoundError: No module named 'django' My guess is that its trying to use python 3.6.7 which doesn't have the correct modules. So my question is how do I make apache2.4 use python 3.7 and its modules? -
How to get Instagram Ads Using Access token
I was able authenticate the user and generate access token using Instagram Auth Api. Is there any way to access the instagram ads using this access token? -
Not able to change is_active status od a user in Django
I am working on webapp where the admin of a domain has the task to register other users of the same domain as his. When I click on "Authorize Users" button on my template is shows an error: "KeyError at /authorize/ 'user' Here is my forms.py: class AuthUserCheckbox(forms.Form): choice = forms.MultipleChoiceField(choices=[], widget=forms.CheckboxSelectMultiple, required=True) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.user_email = self.user.email.split('@')[1] super(AuthUserCheckbox, self).__init__(*args, **kwargs) self.fields['choice'] = forms.MultipleChoiceField(choices=[(i.id, i.email) for i in User.objects.all() if not i.is_active and self.user_email in i.email ]) Here is my views.py: @login_required def auth_users(request): form = AuthUserCheckbox(request.POST, user=request.user) return render(request, 'todoapp/auth_users.html', context={'form': form}) @login_required def authorize(request): if request.method == 'POST': authorize_users = AuthUserCheckbox(data=request.POST, user=request.user) if authorize_users.is_valid(): email_list = request.POST.getlist('choice[]') for i in email_list: if not i.is_active: i.is_active = True return redirect('authorize') else: return render(request, 'todoapp/auth_users.html', {'errors': authorize_users.errors}) return render(request, 'todoapp/auth_users.html', {'form': AuthUserCheckbox()}) -
Having Trouble Running Locust With Django
I tested the locust locally and it runs perfectly . But when I run the Locust on server in a django app it won't run . Whenever I add from locust import runners it gives me following error :- Traceback (most recent call last): File "/usr/lib/python3.5/socketserver.py", line 625, in process_request_thread, self.finish_request(request, client_address) File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.5/socketserver.py", line 681, in __init__ self.handle() File "/var/www/html/kk/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 169, in handle self.handle_one_request() File "/var/www/html/kk/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.5/socket.py", line 575, in readinto return self._sock.recv_into(b) File "/var/www/html/kk/lib/python3.5/site-packages/gevent/_socket3.py", line 433, in recv_into self._wait(self._read_event) File "src/gevent/_hub_primitives.py", line 284, in gevent.__hub_primitives.wait_on_socket File "src/gevent/_hub_primitives.py", line 289, in gevent.__hub_primitives.wait_on_socket File "src/gevent/_hub_primitives.py", line 271, in gevent.__hub_primitives._primitive_wait File "src/gevent/_hub_primitives.py", line 46, in gevent.__hub_primitives.WaitOperationsGreenlet.wait File "src/gevent/_hub_primitives.py", line 46, in gevent.__hub_primitives.WaitOperationsGreenlet.wait File "src/gevent/_hub_primitives.py", line 55, in gevent.__hub_primitives.WaitOperationsGreenlet.wait File "src/gevent/_waiter.py", line 151, in gevent.__waiter.Waiter.get File "src/gevent/_greenlet_primitives.py", line 60, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch File "src/gevent/_greenlet_primitives.py", line 60, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch File "src/gevent/_greenlet_primitives.py", line 64, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch File "src/gevent/__greenlet_primitives.pxd", line 35, in gevent.__greenlet_primitives._greenlet_switch greenlet.error: cannot switch to a different thread` Can you Please tell me how to solve this error . kk is my environment. -
Django Template not rendering
I am trying to load a list of objects from a MySQL database using Django templates. I can load the objects from the database using Product.objects.values() and convert it into a dict, then pass that dict as a context to the render function. But when I load my page, it does not iterate the dictionary. Has anyone any ideas? for entry in d: name = entry.pop('name') newdict[name] = entry print(newdict) return render(request, 'product.html', newdict)` <div class="col-12 col-lg-6 add_to_cart_block"> {% for item in newdict.items %} {{newdict|length}} <div class="card bg-light mb-3"> <div class="card-body"> <p class="price">{{item}}</p> <p class="price_discounted">149.90 $</p> <form method="get" action="cart.html"> <div class="form-group"> <label for="colors">Color</label> <select class="custom-select" id="colors"> <option selected>Select</option> <option value="1">Blue</option> <option value="2">Red</option> <option value="3">Green</option> </select> </div> <div class="form-group"> <label>Quantity :</label> <div class="input-group mb-3"> <div class="input-group-prepend"> <button type="button" class="quantity-left-minus btn btn-danger btn-number" data-type="minus" data-field=""> <i class="fa fa-minus"></i> </button> </div> <input type="text" class="form-control" id="quantity" name="quantity" min="1" max="100" value="1"> <div class="input-group-append"> <button type="button" class="quantity-right-plus btn btn-success btn-number" data-type="plus" data-field=""> <i class="fa fa-plus"></i> </button> </div> </div> </div> <a href="cart.html" class="btn btn-success btn-lg btn-block text-uppercase"> <i class="fa fa-shopping-cart"></i> Add To Cart </a> </form> <div class="product_rassurance"> <ul class="list-inline"> <li class="list-inline-item"><i class="fa fa-truck fa-2x"></i><br/>Fast delivery</li> <li class="list-inline-item"><i class="fa fa-credit-card fa-2x"></i><br/>Secure payment</li> <li class="list-inline-item"><i class="fa fa-phone fa-2x"></i><br/>+33 1 … -
How to access attribute elements from a JSON file on a Django Template?
From views.py, I am parsing a JSON file from the web. keywords = 'speakers' kw = urllib.parse.urlencode({ 'keywords' : keywords }) url = 'http:/svcs.someservice.com=findItemsByKeywords&' + kw r = requests.get(url).json() context = {'items' : r['findItemsByKeywordsResponse'][0] ['searchResult'][0]['item']} template='home.html' return render(request, template, context)` The JSON file would look like below. I have to say that it is more complex and larger, but I am only interested in extracting a few elements { "findItemsByKeywordsResponse": [ { "version": [ "1.13.0" ], "timestamp": [ "2019-02-27T16:15:48.159Z" ], "searchResult": [ { "@count": "5", "item": [ { "itemId": [ "232972578507" ], "title": [ "Bluetooth Wireless Speaker" ], "primaryCategory": [ { "categoryId": [ "111694" ], "categoryName": [ "Audio Docks & Mini Speakers" ] } ], "galleryURL": [ "http:\/\/thumbs4.greatstorestatic.com\/pict\/232972578507404000000001_1.jpg" ], "viewItemURL": [ "http:\/\/greatstore.com\/rover\/1\/711-53200-19255-0\/1?ff3=2&toolid=10041&campid=123456789&customid=lifeisgreat&item=123456789" ], "autoPay": [ "true" ], "postalCode": [ "11220" ], "location": [ "Dresden, Germany" ], "country": [ "GE" ], "shippingInfo": [ { "shippingServiceCost": [ { "@currencyId": "DM", "__value__": "0.0" } ], "shippingType": [ "Free" ], "shipToLocations": [ "Worldwide" ], "expeditedShipping": [ "true" ], "oneDayShippingAvailable": [ "false" ], "handlingTime": [ "1" ] } ], "sellingStatus": [ { "currentPrice": [ { "@currencyId": "DM", "__value__": "8.99" } ], "convertedCurrentPrice": [ { "@currencyId": "DM", "__value__": "8.99" } ], "sellingState": [ "Active" ], "timeLeft": … -
How to view a shopping cart on each page without a context processor?
I have a simple django eCommerce application that has shopping cart functionality. I am trying to extend my application so that I can see the contents of my shopping cart no matter what page of the application I am on. I was following this tutorial, which states I should use a context processor to do this functionality. However, when attempting to do so, I was not having luck getting this to work. I asked a question showing my approach, and someone commented I should not be using a context processor and there is no need as my cart is being returned from the view. OK. My question is, if the tutorial is wrong why is it wrong, and if a context processor is not needed, why am I unable to display data from my shopping cart in each page when just using views? The relevant section of my template where I want to show the total price of my shopping cart: <div class="header-cart-total"> Total: {{ cart.get_total_price }} </div> This works on the page for the actual cart itself, and I believe I am passing the correct views. How can I troubleshoot this? -
How to make a python object json-serialized?
I want to serialize a python object, after saved it into mysql(based on Django ORM) I want to get it and pass this object to a function which need this kind of object as a param. Following two parts are my main logic code: 1 save param part : class Param(object): def __init__(self, name=None, targeting=None, start_time=None, end_time=None): self.name = name self.targeting = targeting self.start_time = start_time self.end_time = end_time #... param = Param() param.name = "name1" param.targeting= "targeting1" task_param = { "task_id":task_id, # string "user_name":user_name, # string "param":param, # Param object "save_param":save_param_dict, # dictionary "access_token":access_token, # string "account_id": account_id, # string "page_id": page_id, # string "task_name":"sync_create_ad" # string } class SyncTaskList(models.Model): task_id = models.CharField(max_length=128, blank=True, null=True) ad_name = models.CharField(max_length=128, blank=True, null=True) user_name = models.CharField(max_length=128, blank=True, null=True) task_status = models.SmallIntegerField(blank=True, null=True) task_fail_reason = models.CharField(max_length=255, blank=True, null=True) task_name = models.CharField(max_length=128, blank=True, null=True) start_time = models.DateTimeField() end_time = models.DateTimeField(blank=True, null=True) task_param = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'sync_task_list' SyncTaskList( task_id=task_id, ad_name=param.name, user_name=user_name, task_status=0, task_param = task_param, ).save() 2 use param part def add_param(param, access_token): pass task_list = SyncTaskList.objects.filter(task_status=0) for task in task_list: task_param = json.loads(task.task_param) add_param(task_param["param"], task_param["access_token"]) # pass param object to function add_param If I directly use Django … -
Why does adding a Django redirect stop database from populating?
So, long story short, I have been having issues implementing Django CreateViews. I am very close to getting this to work, but a new issue has suddenly arisen. Without the redirect in the following code, my database populates new Model instances. However, after adding the redirect to the success page, I cannot see new model instances in my database or in the Django admin page. Apologies in advance if I'm missing something simple. I can post more code if necessary but my guess is that it's going to be something in either views.py or my template views.py class SuccessView(TemplateView): template_name = "success.html" class DeviceChoiceView(CreateView): model = DeviceChoice form_class = DeviceChoiceForm success_url = 'success.html' template_name = 'index.html' ## All the code below this point is what stops the database from populating ## def form_valid(self,form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return ('success') index.html <!DOCTYPE html> <html> <head> <title>Port Reset</title> </head> <body> <h1>Device Database</h1> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" id="deviceSelection" value="Submit"> </form> </body> -
how can i store this created cookie key in a variable in django
request.session.set_test_cookie() ---- this will create a session with cookie id but how can I store this cookie key in a variable in Django id = request.session.set_test_cookie() ----- this expression through error -
I am not getting emails from my contact form
Hey guys I am trying to make my contact form in django 2.1 which will send emails to me from the sender but I don,t know why it,s not sending me the email I was supposed to receive views.py def index(request): queryset = Post.objects.filter(featured = True) if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') subject = 'Message from ubaidparvaiz.com recieved' from_email = settings.DEFAULT_FROM_EMAIL to_email = [settings.DEFAULT_FROM_EMAIL] context = {'user':name, 'email':email, 'message':message, 'subject':subject } contact_message = get_template('app/contact_message.txt').render(context) send_mail(subject,message,from_email,to_email,fail_silently = True) return redirect('index') return render(request,'app/index.html',{'object':queryset}) models.py settings.py SEND_GRID_API_KEY = 'API key' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'ubaidparvaiz' EMAIL_HOST_PASSWORD = '.py/r^admin1' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'ubaidparvez4@gmail.com' ACCOUNT_EMAIL_SUBJECT_PREFIX = 'Contact email received from my blog' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' contact_message.txt You recieved a message,Don,t panic ..Keep it normal The sender,s name : {{user}} They sender,s email : {{email}} The sender,s subject : {{subject}} This is what he states : {{message}} Thank You Regards, You,r bot Xingo