Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CSRF Malfunction after using HTTPS
I know that this problem is occurs many times here. But none of them has working for me right now. I've been struggling in this error since I change the protocol of my app to https using apache2 and LetsEncrypt. I try the configurations in settings but it doesn't solve the problem. # settings.py CSRF_COOKIE_DOMAIN = ".myapp.ml" CSRF_COOKIE_SECURE = True CSRF_USE_SESSIONS = True SESSION_COOKIE_SECURE = True Ofcourse in every forms with POST method required that I have has {% csrf_token %} in there. It also shows in request data. This errors occurs in Log in and Sign Up forms. Inside the app after I add csrf_exempt in login and signup, I use DRF and when I make requests like POST, DELETE, PUT etc... It only shows the error {"detail":"CSRF Failed: Referer checking failed - no Referer."} Here is my apache2 configuration file: <IfModule mod_ssl.c> <VirtualHost *:443> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the … -
Breaking a forloop
I am currently working on my first website. A dna to protein translator. Here's the thing, when you input the codon (group of three letters) tga,tag or taa. The forloop should stop. Here's the code: class TranslatorView(View): template_name = 'main/translated.html' rna_mapper = { "a": "u", "t": "a", "c": "g", "g": "c" } amino_mapper={ "aat": "Asparagine", "aac": "Asparagine", "aaa": "Lysine", "aag": "Lysine", "act": "Threonine", "acc": "Threonine", "aca": "Threonine", "acg": "Threonine", "agt": "Serine", "agc": "Serine", "aga": "Arginine", "agg": "Arginine", "att": "Isoleucine", "atc": "Isoleucine", "ata": "Isoleucine", "atg": "Methionine", "cat": "Histidine", "cac": "Histidine", "caa": "Glutamine", "cag": "Glutamine", "cct": "Proline", "ccc": "Proline", "cca": "Proline", "ccg": "Proline", "cgt": "Arginine", "cgc": "Arginine", "cga": "Arginine", "cgg": "Arginine", "ctt": "Leucine", "ctc": "Leucine", "cta": "Leucine", "ctg": "Leucine", "gat": "Aspartic", "gac": "Aspartic", "gaa": "Glutamic", "gag": "Glutamic", "gct": "Alanine", "gcc": "Alanine", "gca": "Alanine", "gcg": "Alanine", "ggt": "Glycine", "ggc": "Glycine", "gga": "Glycine", "ggg": "Glycine", "gtt": "Valine", "gtc": "Valine", "gta": "Valine", "gtg": "Valine", "tat": "Tyrosine", "tac": "Tyrosine", "taa": "Stop", "tag": "Stop", "tct": "Serine", "tcc": "Serine", "tca": "Serine", "tcg": "Serine", "tgt": "Cysteine", "tgc": "Cysteine", "tga": "Stop", "tgg": "Tryptophan", "ttt": "Phenylalanine", "ttc": "Phenylalanine", "tta": "Leucine", "ttg": "Leucine", "AAT": "Asparagine", "AAC": "Asparagine", "AAA": "Lysine", "AAG": "Lysine", "ACT": "Threonine", "ACC": "Threonine", "ACA": "Threonine", "ACG": "Threonine", "AGT": "Serine", "AGC": … -
Getting rid of duplicates when sorting by 2 related fields in Django
I'm having difficulties sorting data from a stock management database in a Django query. The data has to be ordered by 2 related fields, and this results in duplicates. I understand that this is expected behavior, but I can't seem to find an elegant way to get rid of those duplicates. models.py: class Attribute(models.Model): name = models.CharField(max_length=100) class AttributePossibleValues(models.Model): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) name = models.CharField(max_length=100) sorting_value = models.IntegerField(null=True) class Meta: ordering = ('sorting_value', ) class Product(models.Model): product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE) attributes = models.ManyToManyField(Attribute, through='ProductAttributes') price = models.DecimalField(max_digits=8, decimal_places=2) class ProductAttributes(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) value = models.ForeignKey(AttributePossibleValues, on_delete=models.CASCADE, null=True) The query which is returning duplicates (views.py): product_type = ProductType.objects.get(pk=data['product_type_id']) queryset = Product.objects.filter(product_type=product_type) queryset = queryset.order_by('productattributes__attribute__name','productattributes__value__sorting_value') For example: A specific red sweater made out of wool, is represented by a Product instance. This instance is linked to 2 Attribute instances (color and material) through a many-to-many intermediary table. This intermediary table also links the attributes to the correct values for these attributes (red and wool). Now I want to generate a list with the prices of all sweaters. I want this list to be sorted. I want to see the cotton sweaters first, and then the … -
How to access ForeignKey field object in order to get correct URL in views.py
models.py: class MenuItem(models.Model): main_menu_item = models.CharField(max_length=60) main_menu_slug = models.SlugField(max_length=120, unique=main_menu_item) ... class SubMenuItem(models.Model): main_menu = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name="items", null=True) sub_menu_item = models.CharField(max_length=80) item_page_slug = models.SlugField(max_length=120, unique=sub_menu_item) ... views.py: def menus_detail(request, menu, main_menu): menu = get_object_or_404(SubMenuItem, item_page_slug=menu) main_menu = get_object_or_404(MenuItem, main_menu_slug = main_menu) return render(request, "menus/menus_detail.html", {"menu": menu, "main_menu": main_menu, }) urls.py: urlpatterns = [ path("<slug:main_menu>/<slug:menu>", views.menus_detail, name="menus-detail"), ] MenuItem and SubMenuItem are in one-to-many relationhip, so I am trying to copy that logic to URLs - <slug:main_menu>/<slug:menu>. Currently each combination of MenuItem and SubMenuItem will work (views.py). I did this as a "bad" workaround solution just to see if everything else is working, but obviously it can't stay that way. I understand that I need to access the ForeignKey field of SubMenuField inside of views.py in order to get the desired output. Can someone explain me how to do this? -
i have this problem desc="No web processes running" but when i use this heroku ps:scale web=1
i have this problem 020-11-29T19:04:56.000000+00:00 app[api]: Build succeeded 2020-11-29T19:05:18.831941+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/%20deployed%20to%20Heroku" host=last-test-maybe.herokuapp.com request_id=aa5ae524-db09-4d6d-ac8e-4f4e5ba2cec4 fwd="160.176.89.91" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T19:05:19.181672+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=last-test-maybe.herokuapp.com request_id=c98ffee4-d90f-43a5-b576-da4505c744ad fwd="160.176.89.91" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T19:05:22.298801+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=last-test-maybe.herokuapp.com request_id=a4612daf-8511-44a1-87e0-487b815f661d fwd="160.176.89.91" dyno= connect= service= status=503 bytes= protocol=https2020-11-29T19:05:22.583867+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=last-test-maybe.herokuapp.com request_id=ad721b81-03ae-46dc-bd8f-7cc80ff9ed1b fwd="160.176.89.91" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T19:17:14.000000+00:00 app[api]: Build started by user pro.python.ml@gmail.com 2020-11-29T19:17:48.931929+00:00 app[api]: Deploy e136ea5e by user pro.python.ml@gmail.com 2020-11-29T19:17:48.931929+00:00 app[api]: Release v15 created by user pro.python.ml@gmail.com 2020-11-29T19:18:02.000000+00:00 app[api]: Build succeeded 2020-11-29T19:18:31.000000+00:00 app[api]: Build started by user pro.python.ml@gmail.com 2020-11-29T19:18:42.048061+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=last-test-maybe.herokuapp.com request_id=2f7bbc5b-cb34-4835-902f-11bc809433a1 fwd="160.176.89.91" dyno= connect= service= status=503 bytes= protocol=https2020-11-29T19:18:42.536733+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=last-test-maybe.herokuapp.com request_id=718eb26d-45ec-4bc8-9955-e917fc102fe6 fwd="160.176.89.91" dyno= connect= service= status=503 desc="No web processes running"but i cant use this commande heroku ps:scale web=1 (myvenv) C:\Users\privet01\Desktop\python projects\PRODUCT-hunt\ProductHUNT-project>heroku ps:scale web=1 » Error: Missing required flag: » -a, --app APP app to run command against » See more help with --help help me plz -
How to display image from django rest framework in react application using json
I am having a problem with displaying an image. I've sent it from the react to the django by converting it to base64: {this.renderImageInput, type = "file", processImage) { const { data, errors } = this.state; return ( <Input type={type} name={name} value={undefined} label={label} onChange={this.handleImageChange(processImage)} error={errors[name]} /> ); } } {this.renderImageInput("image", "Image", "file",(input, valueCallback) => { let reader = new FileReader(); reader.readAsDataURL(input.files[0]); reader.onload = () => { valueCallback(reader.result); }; })} the react components which suppose to display it as following: <img src={image} alt="Profile" className="rounded-circle" width="150"/> the image the react receives is the local path to the image. the image is stored correctly in the intended directory. however when trying to display the picture I got none: the model is: image = models.ImageField(upload_to="media/images/", max_length=500, null=True, blank=True) the image serilizer is: class ProfileSerializer(serializers.ModelSerializer): skill_set = SkillSerializer(many=True, required=False) experience = ExperienceSerializer(required=False) image = Base64ImageField() class Meta: model = Profile fields = ('first_name', 'last_name', 'email', 'lab', 'is_looking_for_job', 'git_account', 'facebook_account', 'linkedin_account', 'description', 'image', 'skill_set', 'experience') should I encode the image to base64 and then send it to the frontend and if so how? or is there any other way more convenient? thanks in advance for your help. -
Using previously annotated value in KeyTransform ends up being incorrect SQL query
My intent is to use previously annotated value of object in further KeyTransform. Nor OuterRef, nor F expression are helping. When examining generated SQL, you can see broken SQL query. Example follows: query = Model.objects.annotate( annotated_value=KeyTransform('name_in_json', 'json_field') ).annotate( needed_value=KeyTransform(F('annotated_value'), 'some_relation__jsonfield') ) # if I try to get needed_value, there won't be one query.first().needed_value # returns None SELECT "model"."field", ..., ("model"."json_field" -> name_in_json) AS "annotated_value", ("related_model"."jsonfield" -> F(annotated_value)) AS "needed_value" FROM "wallets_transaction" I tried nested KeyTransform also, no success. Basically, I need to get some value from json field of primary model (get it annotated), and through its relation access some other model json field and by the help of annotated value, get value that will have key that equals to annotated value, so I have to get value of that key. -
Django Rest Framework: Error - "user with this uuid already exists."
I have written a model and made uuid as my primary id. When I use the POST it gives me error - "user with this uuid already exists." This error started showing only when I changed my User's model primary key from 'id' to 'uuid'. These are the relevant models - User Model: class User(models.Model): uuid = models.CharField(default=uuid.uuid4, max_length=50, primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email_id = models.EmailField(max_length=100, default="") Appointment Model: class Appointment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) zorg = models.ForeignKey(Zorg, on_delete=models.CASCADE, null=True) branch = models.ForeignKey(Zorg_Branche, on_delete=models.CASCADE, null=True, related_name='branch') timestamp = models.DateTimeField(auto_now_add=True, blank=True) status = models.ForeignKey(Appointment_Status, on_delete=models.CASCADE, null=True) totaltime = models.PositiveIntegerField(default=0) total_price = models.DecimalField(decimal_places=2, max_digits=10, default=0) Appointment Detail Model: class AppointmentDetail(models.Model): appointment = models.ForeignKey(Appointment, on_delete=models.CASCADE,null=True, related_name='appointment') service = models.ForeignKey(Service, on_delete=models.CASCADE,null=True, related_name='service') -
get() returned more than one Order -- it returned 2
Actually i want to build a virtual payment system but whenever a customer wants to pay his first order it proceed successfully but in the 2nd time i face this error.I dont know why i am getting this error can someone please help me to solve this problem Here is my : Model.py class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100) coin = models.IntegerField(null=True, blank=True, default=0000.00) # user = models.ForeignKey(User, related_name='customer', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.phone_number class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey(Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey(PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True, blank=True) def save(self, *args, **kwargs): self.total = self.price * self.quantity return super().save(self, *args, **kwargs) Here is my views.py: def post(self, request, *args, **kwargs): customer = Customer.objects.get(id=request.session['customer']['id']) print(customer) try: index, created = Order.objects.get_or_create(customer=customer) # print(index.total) except Order.MultipleObjectsReturned: index = Order.objects.get(customer=customer) # index = Order.objects.get(customer=customer) # print(index.total) balance = request.session['customer']['coin'] print(balance) if balance >= index.total: balance = balance - index.total print(balance) # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer = Customer.objects.get_or_create(id = request.session['customer']['id']) customer.coin … -
React and Django REST not fully authenticating?
I built a app with react, django and used DRF, I have a log in page which when successful passed a token, basically, it logs in fine but just noticed that i have a component which gets data from a particular logged in user and i used "IsAuthenticated" as a decorator, I notice it shows in the API, but not in my frontend, I removed "IsAuthenticated" decorator, and check the network then i noticed it shows: 'AnonymousUser' object has no attribute 'follow_user' ... even when im logged in react. Please help I dont understand what is going on. This is the Login.js class LoginForm extends React.Component { state = { username: "", password: "" }; handleChange = e => { this.setState({ [e.target.name]: e.target.value }); }; onFinish = values => { console.log(values); // values.preventDefault(); const { username, password } = this.state; this.props.login(username, password); }; render() { const { error, loading, token } = this.props; const { username, password } = this.state; if (token) { return <Redirect to="/" />; } return ( <Layout> <Layout> <L <Tabs defaultActiveKey="1" onChange={callback}> <TabPane tab="Login" key="1"> <Content> <h2>Log in to your account</h2> <div> {error && <p>{this.props.error.message}</p>} <React.Fragment> <Form {...layout} name="basic" initialValues={{ remember: false }} onFinish={this.onFinish} onFinishFailed={onFinishFailed} // … -
Intellij not able to detect syntax of static assets loaded in django project
Setting up virtual environment $ pip3 install virtualenv virtualenvwrapper $ mkdir Django; cd Django; $ virtualenv django-virtual-env -p python3 $ ls django-virtual-env bin lib pyvenv.cfg $ source django-virtual-env/bin/activate (django-virtual-env) $ (django-virtual-env) $ which python3 $PWD/env_blog/bin/python3 (django-virtual-env) $ deactivate $ pip dependencies required pip install django Setting up intellij for your project Configure Python interpreter File -> Project Structure -> SDKs -> + -> Add Python SDK -> Virtual Environment -> Existing Environment -> (Set the interpretter to absolute path) ./django-virtual-env/bin/python Configure the project to be able to import the python modules Right-click on project_dir -> Mark Directory as -> Sources Root Still the following syntax is not getting detected. The code is correct and working. Not sure what is the issue -
Django: OneToOne self-referencing field form validation error (Model with this field already exists)
Guys, could you please give a hint.. I just made a onetoone field in model that refers to itself. I have a collision problem in form validation when Im trying to edit already created model with already filled onetoone field with the SAME instance as it was assigned from scratch. In case I remain same relation (instance that was assigned before) in field it will return error: "Model (name of my model) with this field (name of my field) already exists" but If I change field value in form to another instance it will eventually validate this form without any problems. So, my solution that came to my mind is to override validate/clean methods in form. Is it a proper way to manage this problem? And if it's true so how to write a proper code to handle this case? For clarity I attach my code below: Models.py db_dr = models.OneToOneField('self', on_delete=models.CASCADE, blank=True, null=True) Part of code in views.py form = DatabaseInfoForm(initial=data) if request.method == 'POST': form = DatabaseInfoForm(request.POST) if form.is_valid(): -
Django image view
I have a Django app and im trying to build up a commerce ,I have all done in my models like to upload the images in my admin panel , My question is after I have display all the images in my store I don't find the solution to view individual in my store.html one witch I desired for ex: to access only a single one on View button ......Do I have to use only javascript? or to enumerate an use a filter for database? Thanks in Advance ! my code is : models.py CATEGORY = ( ('Small Tiles','Small Tiles'), ('Big Tiles','Big Tiles'), ('Adhesive','Adhesive') ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True) image = models.ImageField(null=True, blank=True) view.py from django.shortcuts import render,redirect from . models import * def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/store.html', context) store.html {% extends 'store/base.html' %} {% load static %} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-6"> <img class="thumbnail" src="{{ product.imageURL }}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <div class="card text-white bg-dark mb-4" style="max-width: 25rem;"> <div class="card-header">Porcelain Tiles</div> <div class="card-body"> <h5 class="card-title">Description :</h5> <p class="card-text">{{ product.description }}</p> </div> … -
How to set different permission to edit field on django admin list view depending on a value of this field?
How to set different permission to edit field on django admin list view depending on a value of this field (status)? For example if field status is null this field only for current instance stays readonly on django admin list view, class MyModelAdmin (admin.ModelAdmin): list_display = ['id', 'client', 'status'] list_editable = ('status',) -
Function inside class not executed
I've a method inside a class with (CreateView) that i need to be executed, but i think it's not being executed, in fact 'save' do nothing and the table 'Card_id_user' is empty... Is there a way to solve this problem? Here is the code in my views.py class New_card_creation_view(CreateView): title = "AGGIUNGI CARD" model = Card template_name = "new_card.html" fields = ['card_title', 'description', 'expiration_date', 'column'] def create_card_view(self, request): v = New_card_creation_view(request) v.create_card_view(request) if request.method == 'POST': form = CardCreationForm(request.POST or None) if form.is_valid: form = form.save(commit=False) form.save() nCard=Card_id_user(user_id=request.user.id, card_id= form.id) return render(request, 'board.html'), else: form = CardCreationForm() return render(request, 'new_card.html', {'form': form}) else: form = CardCreationForm() return render(request, 'new_card.html', {'form': form}) def get_context_data(self, **kwargs): context = super(New_card_creation_view, self).get_context_data(**kwargs) context.update({'title': self.title}) return context def get_success_url(self): return reverse('board_view', args=(self.object.column.board.id,)) -
Calling own API endpoints in django command
I'd like to call the endpoint of my own app in a django.core.management.base.BaseCommand pretty much like this with rest_framework.test.APIClient: client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + auth_token.key) url = reverse('myurl-viewset') res = client.post(url, data=payload, format='json') The problem I have with APIClient is that it seems to be using its own testing database and so everything I do within my views to modify the db actually doesn't get inserted into the real database. I need to find a way to call my views/endpoints from a django.core.management.base.BaseCommand class handle function. Any idea how I can solve this? Thanks. -
Django - usage of prefetch_related
no matter how many tutorials/documentation i read i still don't quite understand how exactly i'm supposed to be using prefetch_related. My models.py: class ProfileComment(models.Model): author = models.ForeignKey('Profile', on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=timezone.now, editable=False) body = models.CharField(max_length=180, blank=True) ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') comments = models.ManyToManyField(ProfileComment, related_name='comments', blank=True) avatar = models.FileField(upload_to=avatar_folder, default='user-avatar/default.png') ... My views.py: profile = Profile.objects.prefetch_related('comments').get(user=request.user) And in template: {% for comment in profile.comments.all %} <div> <p>Author: {{ comment.author.user }}</p><img src="{{ comment.author.avatar.url }}"> <p>Message: {{ comment.body }}</p> <p>Date posted: {{ comment.date_posted }}</p> </div> {% endfor %} However, no matter what i put in prefetch_related, amount of queries just go up by like 5 for every record -
Demonizing app in python and django using systemd
i'm trying to demonize app in python in django using systemd. [Unit] Description=sklep.kaczkoland.pl service After=network.target StartLimitIntervalSec=0 [Service] Type=simple Restart=always RestartSec=1 User=root ExecStart=/root/ivshop/manage.py runserver 0.0.0.0:2135 [Install] WantedBy=multi-user.target When I look into logs I see Nov 29 18:12:02 vps12830 systemd[1]: Stopped sklep.kaczkoland.pl service. Nov 29 18:12:02 vps12830 systemd[1]: Started sklep.kaczkoland.pl service. App also not work. What I'm doing wrong? -
Django model query with Foreign key and get logged in user
Hi I am trying to add "fields" to my django projects that would be calculated based on query.. Basically I have 2 models one is a user which is an extension of Abstract user class CustomUser(AbstractUser): pass and my main model is Project class Project(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False) name = models.CharField(max_length=20, editable=False) total = models.DecimalField(max_digits=6, decimal_places=2, editable=False) created = models.DateTimeField(auto_now_add=True, editable=False, null=False, blank=False) this_month = datetime.datetime.now().month allprojectsthismonth = Project.objects.filter(created__month=this_month) def __str__(self): return self.name I create Project objects via a web form using this view: def homepage(request): if request.method == "POST": project = Project() name = request.POST.get('name') total = request.POST.get('total') created = datetime.datetime.now() user = request.user project.user = user project.name = name project.total = total project.created = created project.save() #return HttpResponse(reverse("homepage.views.homepage")) return render(request, 'homepage.html') else: return render(request, 'homepage.html') What I need now is to have a queryset that gets me the combination of the total of a given user Project object so that I can make calculations on it, how would I go about doing that? ideally I would get the logged in user and I could add to my view the sum of all Project.object.total with user = currently logged in. Thanks -
Django Chartjs outputs "No data" when data has value 0
I was trying to plot some Doughnut graphs with Django and chartJS. But stuck at a problem. When the data has value = 0, I want the output in place of doughnut as "No data". I researched for ngIf but the output is not as expected. Here is my code index.html <div class="card-body card-body-cascade text-center"><div class="chartjs-size-monitor" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;"><div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"> <div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div></div><div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"> <div style="position:absolute;width:200%;height:200%;left:0; top:0"></div></div></div> <canvas id="doughnutChart" height="250" width="730" class="chartjs-render-monitor" style="display: block; width: 408px; height: 272px;" ng-if="data.length <= 0"></canvas> <span ng-if="data == 0">No data</span> </div> And the JS for doughnut is like this <script> chartIt(); async function chartIt() { const data = await getData(); var ctx = document.getElementById("doughnutChart").getContext('2d'); var myLineChart = new Chart(ctx, { type: 'doughnut', data: { labels: ['d1','d2'], datasets: [{ data: ['0','0'], backgroundColor: ["#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360"], hoverBackgroundColor: ["#FF5A5E", "#5AD3D1", "#FFC870", "#A8B3C5", "#616774"] }] }, options: { responsive: true } }); } </script> -
Adding form in a ListView template
So, I built a listview which works fine. I was also able to add the form onto the same page as the listview. However, when I submit the form, the listview does not get updated with the recent form I submitted. I also get a strange error as well. I am not sure what went wrong. views.py class BlogListView(ListView, ModelFormMixin): model = Post context_object_name = 'blog_list' template_name= 'blog/blog_home.html' cats = Category.objects.all() ordering = ['-post_date'] form_class = PostForm def get(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) return ListView.get(self, request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) if self.form.is_valid(): self.object = self.form.save() return self.get(request, *args, **kwargs) def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(BlogListView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu context["form"] = self.form return context urls.py path('',BlogListView.as_view(),name='blog_home'), forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields =('title', 'category', 'body') widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'category': forms.Select(choices=choice_list,attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } blog_home.html: <div class="card-body"> <form action="" method="post"> <div class="form-group"> {% csrf_token %} {{ form.media }} {{ form|crispy }} <input type="submit" value="Post"/> </div> </form> </div> Error when form method is "post": IntegrityError at / null value in column "author_id" violates not-null constraint … -
I want to assign a specific customer's grand total into a variable
I want to assign a specific customer's grand total into a variable. I have this Model: class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey(Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey(PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True, blank=True) def save(self, *args, **kwargs): self.total = self.price * self.quantity return super().save(self, *args, **kwargs) Here i have a field called total. When a customer place a order its show a total. so here i want to take total_by_customer_id after that i want to assign into a variable then i want to substract with the balance. Here is views: class UserInvoice(View): def map_func(self, product): cart = self.request.session.get('cart', None) product_id = str(product.id) if product_id in cart: return product.price * cart[product_id] def get(self, request, id): user_orders = Order.objects.get(pk=id) args = {'user_orders':user_orders} return render(self.request, 'Home/invoice.html', args) def post(self, request, *args, **kwargs): customer = request.session.get('customer') print(customer) index = Order.get_orders_total_by_customer(customer.total) print(index) balance = request.session['customer']['coin'] print(balance) if balance >= index.total: balance = balance - index.total print(balance) # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer = Customer.objects.get(id = request.session['customer']['id']) customer.coin = balance customer.save() request.session['customer']['coin'] = balance return … -
Overriding AdminTimeWidget for a different input_type
If i pick up the default TimeInput class i'm able to change the input type of the element rendered in the template, for example: from django import forms class TimeInput(forms.TimeInput): input_type = 'time' If i use this widget, i'll get a <input type="time">. However, if i try to override the AdminTimeWidget, which also descends from TimeInput, the element is rendered as <input type="text">. Example: class AdminTimeWidget(forms.TimeInput): input_type = 'time' class Media: js = [ 'admin/js/calendar.js', 'admin/js/admin/DateTimeShortcuts.js', ] def __init__(self, attrs=None, format=None): attrs = {'class': 'vTimeField', 'size': '8', **(attrs or {})} super().__init__(attrs=attrs, format=format) class CountTimeForm(forms.Form): from_time = forms.TimeField(widget = AdminTimeWidget(), required=False) In here, the from_time input will be rendered as a text input... How can i fix it, in order to render as a time input? -
Error loading psycopg2 module on OS Big Sur i.c.w. Apple Silicon
Try to install a Django Project on my new Apple Silicon machine with OS 11/Big Sur. When I try to run a manage.py command I get the following error: /venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 29, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen({removed}/venv/lib/python3.8/site-packages/psycopg2/_psycopg.cpython-38-darwin.so, 2): Symbol not found: _PQbackendPID Referenced from: {removed}/venv/lib/python3.8/site-packages/psycopg2/_psycopg.cpython-38-darwin.so Expected in: flat namespace I have postgres installed with the Postgres.app Tried al kind go things. f.i. setting up the following symlink in /usr/local/lib libpq.5.dylib -> /Applications/Postgres.app/Contents/Versions/latest/lib/libpq.5.13.dylib Installing the psycopg2-binary gave me other errors. So far, no luck. Not sure if the cause is OS11 or the new Silicon. -
Sendgrid API - Adding complete HTML Template (including the headers and styles)
I am not able to figure out how I can send a complete HTML email template to Sendgrid using the v3 API. I need to create templates on Sendgrid on the fly on the basis of user input (the user input determines the CTA link in the template as well as send these email to actual people using personalizations.) But at the same time, I should be able to send an entire HTML (along with Headers and Styles) to Sendgrid for processing these email. Thanks