Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Posting access_token to Django backend to retrieve a DRF token for API usage results to Your credentials aren't allowed in social_django
What I am doing : I am trying to use google sign in button so that I can get a tokenId and send it to the django rest api where it can verify with Google api and create a new user from the email retrieved (if the user is not registered by the email ID) and respond with a default Token (Django Rest Frameworks's) to the Android Client so that it can further be used to do some CRUD operations for the DRF How I am doing : I created two credentials, one for the Android App and the other for the web app Added the SHA-1 fingerprint in the Android credential by copying it from Android studio's gradle signingReport (Without providing SHA-1 to the credential one will not get the desired idToken ) Then I am manually getting the tokenId private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); // Signed in successfully, show authenticated UI. updateUI(account); } catch (ApiException e) { // The ApiException status code indicates the detailed failure reason. // Please refer to the GoogleSignInStatusCodes class reference for more information. Log.w(this.getLocalClassName(), "signInResult:failed code=" + e.getStatusCode()); updateUI(null); } } private void updateUI(GoogleSignInAccount account){ Toast.makeText(this,"SUCCESS",Toast.LENGTH_SHORT).show(); Log.w(this.getLocalClassName(), … -
Running Django server via Dockerfile on GAE Custom runtime
I am trying to deploy my Docker container with Django server on Google APP Engine Custom environment, although it gets deployed but it doesn't start working the way it should work i.e it seems django runserver is not working . App.yaml runtime: custom env: flex service: jobs resources: cpu: 4 memory_gb: 8 disk_size_gb: 30 DOckerfile: FROM hsingh1993/jobs:fourth EXPOSE 8000/tcp RUN id USER jovyan WORKDIR /home/jovyan/trustdjobs CMD ["python","./manage.py","runserver","0.0.0.0:8000"] -
Why does random in django rest serializer always return the same field?
I have a simple serializer class Serializer(serializers.Serializer): name = serializers.CharField(required=False, default='someName') id = serializers.IntegerField(required=False, default=random.randrange(100, 200)) And when I create multiple instances of the serializer it always returns the same field a = Serializer(data={}) a.is_valid(data={}) data = a.data data['id'] // return for example 150 b = Serializer(data={}) b.is_valid(data={}) b_data = b.data b_data['id'] // return also 150 Why it happens? How to get rid of this? -
Getting undefined from .val()
So when I call: var productId = $(this).find('#productnumber').val(); I get undefined as a result. However, when I use var productId = $('#productnumber').val(); I get the id value. But in HTML I have a for loop which makes multiple similar items with different id's. and without (this) I see the id only of the first element -
how to make an object for multiple users , similar to facebook page django
i try to make an app for real estates , some of real estates profile have several employees , the owner of the real estate make an object from RealEstate class , and generates a unique uuid key , then if the Real estate agency had several employees , each employee make a profile ,and the owner should provide the key to access to the RealEstate object , in order to be one the RealEstate employees accounts : class Profile(models.Model): user = models.OneToOneField(User , on_delete=models.CASCADE) image = models.ImageField(upload_to='profiles' , default='pyart.png') phone = models.CharField(max_length=11 , default='',blank=True) bio = models.CharField(max_length=100 , default='',blank=True) date = models.DateTimeField(default=datetime.now) active = models.BooleanField(default=False) def __str__(self): return f'{self.user}' and each RealEstate can have several admins with one super admin , who added other admins depend on the code field class RealEstate(models.Model): admins = models.ManyToManyField(User,on_delete=models.CASCADE) code = models.UUIDField(unique=True,default=uuid.uuid4,editable=False) real_estate_name = models.CharField(max_length=40,unique=True) image = models.ImageField(upload_to='realestate',default='realestates.png') phone = models.CharField(max_length=11) bio = models.CharField(max_length=200) city = models.ForeignKey(City,on_delete=models.CASCADE) address = models.ForeignKey(Address,on_delete=models.CASCADE) nearest_place = models.CharField(max_length=40) date = models.DateTimeField(default=auto_now_add=True) status = models.BooleanField(default=True) and the listings table class Listing(models.Model): objects = ListingManager() company = models.ForeignKey(settings.AUTH_USER_MODEL , on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(unique=True , default=radnom_generating(),blank=True) #others how to make it happen , only by accessing the RealEstate … -
Line chart by dates with django models
I’m trying to build a line chart using Chart.js and Django. This chart will shows the account of class “anomalies” per month. The class anomalie has date_report attribute. This date will repeat because there are many anomalies that could happen in the same month. So I need to group them per month and count the amount of anomalies in this month, then I need to show this in a graph, in order to see the historic progress: In X the month and In Y the amount of anomalies To achieve that in my view.py I have trunked by month months and count by id count_per_month like this: @login_required(login_url='login') def home_screen_view(request): context = {} user_aisles = request.user.aisle.all() list_anomalies_user = [] anomalies = Anomalie.objects.all() anomalies_per_aisle = anomalies.filter(aisle__in=user_aisles) # line chart months = anomalies_per_aisle.annotate( month=TruncMonth('date_report')).values('month').annotate(c=Count('id')).values('month') count_per_month = anomalies_per_aisle.annotate( month=TruncMonth('date_report')).values('month').annotate(c=Count('id')).values('c') print('months', months) print('count_per_moth', count_per_month) context = {'list_anomalies_user': list_anomalies_user, 'anomalies_per_aisle': anomalies_per_aisle,'count_per_month': count_per_month, 'months': months} return render(request, "personal/home.html", context) Then I’m passing this data to "labels" and "data" into the scripts using “safe” like this: <script> var ctx = document.getElementById("myAreaChart"); //"myAreaChart" var myLineChart = new Chart(ctx, { type: 'line', data: { labels: [{{ months| safe}}], datasets: [{ label: "Sessions", lineTension: 0.3, backgroundColor: "rgba(2,117,216,0.2)", borderColor: "rgba(2,117,216,1)", pointRadius: … -
Calling a Django function inside an AWS Lambda
I want to defer some processing load from my Django app to an AWS Lambda. I'm calling my code from the Lambda like this: lambda.py: @bc_lambda(level=logging.INFO, service=LAMBDA_SERVICE) def task_handler(event, context): message = event["Records"][0]["body"] renderer = get_renderer_for(message) result = renderer.render() return result get_renderer_for is a factory method that returns an instance of the class Renderer: from myproject.apps.engine.documents import ( DocumentsLoader, SourceNotFound, source_from_version, ) from myproject.apps.engine.environment import Environment class Renderer: def __init__(self, message): self.message = message def render(self): ENVIRONMENT = Environment(DocumentsLoader()) version_id = self.message.get("version_id") try: source = source_from_version(version_id) except SourceNotFound: source = None template = ENVIRONMENT.from_string(source) if template: return template.render(self.message) return None def get_renderer_for(message): """ Factory method that returns an instance of the Renderer class """ return Renderer(message) In CloudWatch, I see I'm getting this error: module initialization error. Apps aren't loaded yet. I understand that Django is not available for the Lambda function, right? How can I fix this? How can I make the rest of the project available to the lambda function? -
Email verification is not enforced. Disregarding ACCOUNT_EMAIL_VERIFICATION setting
I'm using two packages to assist me with authentication. One is js_rest_auth and the other one is allauth. The latter has a setting to require users to validate their email addresses before a login is possible. I'm setting ACCOUNT_EMAIL_VERIFICATION = "mandatory" but it has no effect. My relevant settings look as follows: INSTALLED_APPS = [ ... "django.contrib.sites", "rest_framework.authtoken", "allauth.account", "allauth.account", "allauth.socialaccount", "dj_rest_auth", .... ] ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 90 ACCOUNT_USER_MODEL_EMAIL_FIELD = "email" ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED=True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED=False ACCOUNT_USER_MODEL_USERNAME_FIELD = "email" ACCOUNT_PRESERVE_USERNAME_CASING = False ACCOUNT_ADAPTER = "users.accountadapter.CustomAccountAdapter" AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] REST_FRAMEWORK = { .... "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ] } The users I create aren't verified (verified attribute an Email Address Model) but are created with is_active=True. When I send a login request for a non-verified user, a valid token is issued. -
How to run python script as daemon/cronjob in Django?
I have developped a Django app and try to solve what should be simple... but more I read about this and more it seems to be complicated. I want an email to be send to new user each time new user account is created in auth_user. I first thought about signals and it works but not when I execute a sql script to create user account. So, I thought about using trigger and Postgresql LISTEN/NOTIFY. I have created a trigger on auth_user insert and a function executed with this trigger that NOTIFY this event using perform pg_notify('new_user', NEW.username); Then, I have a python script that LISTEN new_user signal and send email. #!/usr/bin/env python # -*- coding: utf-8 -*- # https://www.depesz.com/2012/06/13/how-to-send-mail-from-database/ # https://www.psycopg.org/docs/connection.html # https://www.psycopg.org/docs/advanced.html#async-notify import select import psycopg2 import psycopg2.extensions from django.core.mail import send_mail import random, string from django.contrib.auth.hashers import make_password dbc = psycopg2.connect(database='db', host='localhost', port=5433, user='user', password='user') dbc.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) cur = dbc.cursor() cur.execute('LISTEN new_user_handle') while 1: if not select.select([dbc], [], [], 5) == ([], [], []): dbc.poll() while dbc.notifies: notify = dbc.notifies.pop() user_email = [] password = generer_mot_de_passe(8) user_email.append('user@domain.fr') email = email_compte(user_email,notify.payload,password.get("plaintext")) def generer_mot_de_passe(length): """Générer une chaîne aléatoire de longueur fixe""" motDePasse = {} str = string.hexdigits password_plaintext = ''.join(random.choice(str) … -
Failed to establish a new connection: [Errno -3] Temporary failure in name resolution in requests python
I am getting name resolution error with requests occasionally, it's happening approx once in 20 requests. I have checked with request domain service provider, they say it works fine with their other clients. I am not sure if this is because of DNS resolution on the system level. I am running an ubuntu instance on digital ocean. Let me know if anyone else has faced this problem as I am facing(on an occasional basis). Please find the stack trace gaierror: [Errno -3] Temporary failure in name resolution File "urllib3/connection.py", line 159, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw) File "urllib3/util/connection.py", line 57, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "python3.7/socket.py", line 752, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x7f53b0d24790>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution File "urllib3/connectionpool.py", line 600, in urlopen chunked=chunked) File "urllib3/connectionpool.py", line 343, in _make_request self._validate_conn(conn) File "urllib3/connectionpool.py", line 839, in _validate_conn conn.connect() File "urllib3/connection.py", line 301, in connect conn = self._new_conn() File "urllib3/connection.py", line 168, in _new_conn self, "Failed to establish a new connection: %s" % e) MaxRetryError: HTTPSConnectionPool(host='demo.api.afex.com', port=7890): Max retries exceeded with url: /api/bank/find (Caused by … -
Update Form Instances when marked for Deletion
I am trying to update an instance of a form model with 'deleted' values for auditing, and not actually delete the records. Currently I have the following views.py for del_form in formset.deleted_forms: del_form.save(commit=False) del_form.cleaned_data['id_trn'].deleted_trn = True del_form.cleaned_data['id_trn'].date_deleted_trn = datetime.datetime.now() del_form.cleaned_data['id_trn'].deleted_usr_trn = request.session.get('user') del_form.save() However, it's not updating the DB record. TIA! -
Django form ChoiceField not selected when editing existing instance
I'd like to design a modelform that has a choicefield field with values that depend on the value of another field of the same form. For the sake of example, here is the modelform. The course day can be selected for each full-day course. For example, if the user has chosen MATH101, the course_day choicefield should give them a different set of days than if the user has chosen a CMPT101 course: class CourseFeeForm(ModelForm): class Meta: model = Course fields = ['course_name', 'course_day',...] def __init__(self, *args, **kwargs): super(CourseFeeForm, self).__init__(*args, **kwargs) if self.instance and self.instance.course_name == 'CMPT101': self.fields['course_day'] = forms.ChoiceField( choices= ( ('monday', 'Monday'), ('tuesday', 'Tuesday') ) elif self.instance and self.instance.course_name == 'MATH101': self.fields['course_day'] = forms.ChoiceField( choices = ( ('monday', 'Monday'), ('wednesday', 'Wednesday'),('friday', 'Friday')) ... The problem is that in the template for the edit view, I'd like the form to display what the user already selected, but if the user has selected Monday as the course_day, the <option value="monday">Monday</option> is missing the selected="selected" presumably because in __init__, we have changed the choicefield based on the course_name and so the default behavior of attaching the selected="selected" to the already selected option is overriden. Then, the question is how to bring the … -
how can we slove this path error of psycopg2 in linux?
I am using conda package and while trying to install psycopg2 i got this error. I want this for postgis and i am running on ubuntu. ERROR: Command errored out with exit status 1: command: /home/srijan/anaconda3/envs/django/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-s5yimrpg/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-s5yimrpg/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-cop18avg cwd: /tmp/pip-install-s5yimrpg/psycopg2/ Complete output (14 lines): running egg_info creating /tmp/pip-pip-egg-info-cop18avg/psycopg2.egg-info writing /tmp/pip-pip-egg-info-cop18avg/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-cop18avg/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-cop18avg/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-cop18avg/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Django how to get admin full name
I have a model named Post, and want to save the full name of the admin automatically who created(or edited) that post. I read about get_full_name() in django documentation, but I cannot understand how to call this method. Here is my Post model class Post(models.Model): post_id = models.AutoField postname = models.CharField(max_length=50) description = models.CharField(max_length=1000) location = models.CharField(max_length=30) user = // I want to store the logged in admin full name here -
Unable to create the django_migrations table (ORA-00907: missing right parenthesis)
I have used oracle database with django. I am new with integrating oracle with django. This is my models.py: models.py : from django.db import models # Create your models here. class Users(models.Model): id = models.AutoField(primary_key=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) name = models.CharField(max_length=100) email = models.CharField(max_length=100) contact_no = models.CharField(max_length=100) class feed(models.Model): id = models.AutoField(primary_key=True) userid = models.CharField(max_length=2000) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) img = models.CharField(max_length=100) desc = models.CharField(max_length=500) class feed(models.Model): id = models.AutoField(primary_key=True) userid = models.IntegerField(default=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) img = models.CharField(max_length=100) desc = models.CharField(max_length=500) class feed_likes(models.Model): id = models.AutoField(primary_key=True) userid = models.IntegerField(default=True) feedid = models.IntegerField(default=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) class feed_comments(models.Model): id = models.AutoField(primary_key=True) userid = models.IntegerField(default=True) feedid = models.IntegerField(default=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) comment = models.CharField(max_length=500) I have also migrated the models py manage.py makemigrations api py manage.py sqlmigrate api 0001 But when executing this command py manage.py migrate It give this error django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-00907: missing right parenthesis) Please help me to solve this problem -
Django - Display success messages for 10 or 20 seconds in Django Admin Panel
I was working in Django admin. So while saving a modal there is an automatic success message that appears after saving. I was wondering if it is possible to set the time limit for the message to appear. So that after few seconds it deletes automatically!! In the picture below after creating a project and saving it there is a success message which says "The project 'xyzproject' was added successfully". But this message remains on the page until I refresh the page. so can anyone tell me if its possible to add a time limit for the message to appear and disappear without refreshing the page. -
decoding a list from a channels.http.AsgiRequest
I have a docker container which sends data_dict, a dictionary {'dome_temp": 15.5C, 'humidity":71%} using the requests library https://requests.readthedocs.io/en/latest/user/quickstart/ with the following code response = requests.post(dome_control_target, data=data_dict) It is received in another container running django via a daphne server. It is received in a channels consumer with this code: def receive_temperhum_data(request): logger.info(f"message received from temperhum {request.data}") return HttpResponse("temperhum data received") request.data returns the error 'AsgiRequest' object has no attribute 'data' So does request.message Request is type: 'channels.http.AsgiRequest' and has the plain text of <AsgiRequest: GET '/dome_control/temperhum/?dome_temp=15.5C&humidity=71%25'> I want to process this data in the consumer. I suppose I could just parse the text, but does anyone know how I can extract the data as a dictionary ? Thank you -
Context not showing Context variable in Template
Hellooo, I am trying to add a feature to my admin where I can download order details from a PDF file, which has gone successful so far except that only one Model is showing which is Order.Model while there is another one called OrderItems which are the items inside the Model not showing. I am not sure how to add another context for the OrderItem to appear in the PDF.html Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted {% for order_item in order.items.all %} {{ order_item.item.title }} <----------Not Showing {% endfor %} -
RuntimeError: Never call result.get() within a task
My task (check payment status in Sberbank. If no capture - retry check): from ....celeryconf import app from . import client as sberbank from ...models import Payment, Transaction @app.task(bind=True, default_retry_delay=60, time_limit=1200) def check_status_sberbank_task(self, order_id, connection_params): sberbank_client = sberbank.Client(auth=(connection_params['login'], connection_params['password']), sandbox=connection_params['sandbox_mode']) response = sberbank_client.payment.get_status(order_id=order_id) txn = Transaction.objects.get(token=order_id) if response['actionCode'] == 0: txn.is_success = True txn.save() payment = Payment.objects.get(pk=txn.payment_id) payment.charge_status = 'fully-charged' payment.captured_amount = payment.total payment.save() return 'Success pay on Sberbank for ' + str(order_id) else: self.retry(countdown=60) in log file I have: ERROR celery.app.trace Task saleor.payment.gateways.sberbank.tasks.check_status_sberbank_task[bb384815-4a5b-49d7-bc29-114707f072b1] raised unexpected: RuntimeError('Never call result.get() within a task!\nSee http://docs.celeryq.org/en/latest/userguide/tasks.html#task-synchronous-subtasks\n',) [PID:26869:Thread-825] Traceback (most recent call last): File "/home/korolev/saleor/lib/python3.6/site-packages/celery/app/trace.py", line 385, in trace_task R = retval = fun(*args, **kwargs) File "/home/korolev/saleor/saleor/payment/gateways/sberbank/tasks.py", line 26, in check_status_sberbank_task self.retry(countdown=60) File "/home/korolev/saleor/lib/python3.6/site-packages/celery/app/task.py", line 715, in retry S.apply().get() File "/home/korolev/saleor/lib/python3.6/site-packages/celery/result.py", line 1015, in get assert_will_not_block() File "/home/korolev/saleor/lib/python3.6/site-packages/celery/result.py", line 41, in assert_will_not_block raise RuntimeError(E_WOULDBLOCK) RuntimeError: Never call result.get() within a task! See http://docs.celeryq.org/en/latest/userguide/tasks.html#task-synchronous-subtasks How do I fix this error? -
add permission to model
I have two models, abstract user and admin, linked onetoonefield. I want to add permissions for admin. I registered in meta permissions, but they are not saved or created in the database. What do I need to do? When I call admin.has_perm ('MoveOnApp.register_partner') I get the error 'Admin' object has no attribute 'has_perm' class AbstractUser(AbstractBaseUser, PermissionsMixin): """Создал абстрактоного юзера от которого будут унаследованны остальные юзеры""" phone_number = models.CharField( _('phone number'), max_length=14, unique=True, help_text='Enter your phone number', ) email = models.EmailField(_('email address'), blank=True, unique=True) created = models.DateTimeField(_('date joined'), default=datetime.datetime.now()) USERNAME_FIELD = 'phone_number' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email'] objects = BaseManager() is_superuser = None class Meta: verbose_name = _('user') verbose_name_plural = _('users') class Admin(models.Model): """Создаю модель администратора, наследованную от AbstractUser""" user = models.OneToOneField(AbstractUser, on_delete=models.CASCADE, primary_key=True) company_name = models.CharField( _('company name'), max_length=150, ) logo_url = models.ImageField( upload_to='img/logo' ) first_name = models.CharField( _('first name'), max_length=50 ) last_name = models.CharField( _('last name'), max_length=50, ) # Флажок, такие права доступа рекомендует делать документация. Есть еще варианты но этот мне кажется самым удобным is_admin = models.BooleanField( _('admin status'), default=True ) objects = BaseManager() class Meta: permissions = ( ("register_partner", "Can register partner"), ) -
AJAX request and csrf token
So from my cart page I want to rend an AJAX request to Django server. It is made to update the number of items in my cart and the checkout price. Here is my AJAX request $('.plus').click(function() { var productId = $(this).find('#productId').val(); req = $.ajax({ headers: { "X-CSRFToken": csrftoken }, url: 'updateit/', type: 'post', data: {'productId' : productId, 'action' : 'plus'} }); req.done(function(data) { $('#total').text(data.total); $('#total_with_delivey').text(data.total_with_delivery); $('#summary').text(data.subtotal); }); }); Here is django view: @require_http_methods(["POST"]) def updateit(request): product = Product.objects.get(id = request.POST['productId']) action = request.POST['action'] if action == 'plus': try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart ) cart_item.save() elif action == 'minus': if cart_item.quantity > 1: cart_item.quantity -= 1 cart_item.save() else: cart_item.delete() item_count = 0 total = 0 cart = Cart.objects.filter(cart_id=_cart_id(request)) cart_items = CartItem.objects.all().filter(cart=cart[:1]) cart_item = CartItem.objects.get(id=request.POST['productId']) subtotal = cart_item.quantity*cart_item.price for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) item_count += cart_item.quantity total_with_delivery = total + 50 return JsonResponse({'result' : 'success', 'item_count' : item_count, 'total' : total, 'total_with_delivery' : total_with_delivery, 'subtotal' : subtotal}) Every time I press … -
Django Python: How to store python code in a textinput form
I have a requirement where user can save some python code in the form which will be run later when needed. How best we can do this using django and save in database. The user will be shown a form and the he can type the code. and save it in the database. -
How to deploy django project on heroku?
I want to deploy django project on heroku i need list of things that i should take care about project and what are the basic requirements. -
ModuleNotFoundError: No module named 'post_project' Heroku and Django
I was going through a tutorial about creation of user accounts and by its end I tried to deploy my website, but I got this error ModuleNotFoundError: No module named 'post_project' My working directory looks like this And this is settings.py INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' Most of the time I've adhered to the tutorial section about accounts in "Django For Beginners" by W.Vincent. Yet still I do get this particular error every time I try to deploy. I attempted to change django version, it didnt help either. Help will be much appreciated -
Why am I seeing localhost:8000 empty path does not match Django?
I keep running into 'Page not found' when trying to load http://localhost:8000/ . I have an empty path set to direct the page to my project_index page, but this is all I get: I have checked and re-checked all of my urlpatters, but cannot figure out where the problem is. Here are all my urls.py scripts that correspond to this project: personal_portfolio/: projects/: blog/: