Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there Open-source ERP based on Django?
I am looking for Open source ERP for my father's manufacturing business. We have lost a lot in this covid-19 time and cant afford any expensive ERP. I am Django developer and I am looking for Django based ERP. Please help. Thanks. -
Models CharField Blank and Null
I have the following model : class Scenario(models.Model): title = models.CharField(max_length=30) subtitle = models.CharField(max_length=60) description = models.TextField(max_length=1000) image_url = models.ImageField(upload_to ='scenarios-pictures/%Y/%m/%d', default="", blank=False, null=False) slug = models.SlugField(null=True, unique=True) active = models.BooleanField(default=False) def __str__(self): return self.title If I try to create a scenario with empty values, it doesn't raise any exception. >>> from ihm_maquette.models import Scenario >>> scenario = Scenario.objects.create(title='', subtitle='', description='', image_url='', slug='') >>> scenario <Scenario: > >>> I don't get why, because I've read in the doc that blank and null are False by default. I've also read this explanation. Do you have any idea why the object is created? -
Django: Create QuerySet baed on number of one-to-many obejcts in DB
In Django, if I have two models One and Many with a one-to-many relationship how can I filter a Manager of One objects to create a QuerySet that only contains Ones that have one or more Manys? (This is a challenge proposed in the "Ideas for more tests" section of the Part 5 of the tutorial on the Django website) -
How to pass a parameter to a view with HTMX and Django?
I am trying to implement kind of a like-button with Django and htmx using django-htmx,but I do not know how how to pass the id as a parameter to my view in order to save the related item. # models.py class Item(models.Model): name = models.CharField() like = models.BooleanField(null=True, default=None) The (simplified) table shows items like this: id name like -- ----- ---- 1 Alpha None 2 Beta None The idea is by klicking e.g. on the first "None", Django should change the like-value for the first item in the database to "True" and this should be reflected in the table: id name like -- ----- ---- 1 Alpha True 2 Beta None The table is generated by a template like this: <table> {% for item in page_obj %} <tr> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td id="like-{{ item.id }}" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}' hx-post="{% url 'save-like' %}?id={{ item.id }}" hx-target="#like-{{ item.id }}" hx-swap="outerHTML"> {{ item.like }} </td> </tr> {% endfor %} </table> With a click on "None", there is a request to the following function: #views.py def save_like(request): success = False if request.method == 'POST': item = Item.objects.filter(pk=request.POST['id']).first() item.like == True item.save() success = True if success: return HttpResponse('<td>True</td>>') else: … -
i want to print the data of input tag in views.py django
enter image description here enter image description here enter image description here enter image description herei have searched alot but couldnt find the bug.. there is no print of input tag information -
django html file load image like `{{post.image.url}}`
-models.py- class Post(models.Model): image = models.FileField(upload_to='note/static/note/') -html file- <img src={{note.image.url}} -error code- [14/May/2021 08:42:07] "GET / HTTP/1.1" 200 402 Not Found: /note/static/note/test.png [14/May/2021 08:42:07] "GET /note/static/note/test.png HTTP/1.1" 404 2357 Did I do anything wrong? -
How create csrf_token with js?
I create many different forms in a foreach loop but I can't send anyone because of the csrf_token. inputToken = _("input", null, newFormModiferReduction) //create <input> with null content, in newFormModiferReduction inputToken.setAttribute("name", "_tokenDelRed") inputToken.setAttribute("type", "hidden") inputToken.setAttribute("value", "{{ csrf_token() }}") When I did console.log of the value I get : {{ csrf_token() }} I tried without quotes, without braces, but it still doesn't work. I couldn't find a solution on the Internet. I tried with only one token in but it doesn't work without anny "error", I conclued that one form = one csrf_token I send these forms with AJAX so if there is another solution it could be find too -
Django fetch data from two table related to foreign ket
i want to fetch data from one model and related images means i want to get vehicle id and related to that vehiceid its related images based on F key relationship. #Model1 from django.db import models class VehicleAd(models.Model): vehiclename = models.CharField(max_length=50) #model 2 from django.db import models from .vehiclead import VehicleAd class Vehicleadimages(models.Model): vehiclead = models.ForeignKey(VehicleAd, on_delete=models.CASCADE,enter code hererelated_name="relatedvehiclead") image = models.ImageField(upload_to="images/vechileadimage") #views def viewVehiclead(request): vehiclead = VehicleAd.objects.all() vehicleadimages = Vehicleadimages.objects.all() print(vehiclead) context = { 'vehiclead':vehiclead, 'vehicleadimages': vehicleadimages } return render(request,'vehiclead/view.html',context) #html {% block body %} <div class="container bg-color-w shadow-lg custom-style-cont "> {% include "menu/top-menu.html" %} <div class="col-md-12 pd-arn2prc"> <div class="container"> <div class="row"> <div class="col-md-12 mx-auto"> <h1>h2</h1> <table> {% for v in vehiclead %} <a href="#">{{ v.vehicleadimages.image }}</a> {% endfor %} </table> </div> </div> </div> </div> </div> {% endblock body %} -
Is there a way to integrate django with react without using api?
I am trying to make a website using django and react (I dont know REST framework). And i have had some trouble communicating between front-end and back-end. I thought of a way to communicate but im not sure if it is a good one. Django has its own templating language so in index.html (of react app) can i do add a div that contains all the useful information like this and then further use that information to display on the page or there might be some security concerns. maybe something like this in index.html <div id='data'>{{ data }}</div> where data can be a JSON string. -
Performance: Database, Django, reverse lookup or direct?
I have 2 models. first contain 5000 objects. second contain 10M objects. class Follower(models.Model): username = models.CharField( _("username"), max_length=250, db_index=True) class Influencer(models.Model): username = models.CharField( _("username"), max_length=250, unique=True, null=False, blank=False, db_index=True) followers = models.ManyToManyField( "instagram_data.Follower", verbose_name=_("Followers")) I tried both options to get Followers objects out of influencer's usernames: influencer_choosen_by_user = ['nike', 'adidas'] if self.REVERSE_SCAN: qs = Follower.objects.filter( influencer__username__in=influencer_choosen_by_user) else: qs = Follower.objects.none() qs_influencer = Influencer.objects.filter(username__in=influencer_choosen_by_user) for influe in qs_influencer.iterator(): qs = qs | influe.followers.all() It seems that both results in same around 20 seconds .... are thay SQL the same ? I think the "REVERSE_SCAN" JOIN 10M with the middle table (manytomany middle table) while the second JOIN the 5K table with the middle table. am I right ? -
Importing Issue in Django
enter image description here it is not importing the DjA package in 19th line -
django.db.utils.IntegrityError: could not create unique index - DETAIL: Key (player)=(Lonergan) is duplicated. - without unique constraint in model
I did a few commits offline including updating the model a couple of times and later when all was deployed to production it was not possible to migrate the database. The error message is: django.db.utils.IntegrityError: could not create unique index - DETAIL: Key (player)=(Lonergan) is duplicated. It is over 100 players with a duplicate name in the table, the strange thing is that the field player was never set to be unique. Why is this happening? class Player(models.Model): player = models.CharField(max_length=50) team = models.ForeignKey(Team, related_name='players', on_delete=models.PROTECT) position = models.CharField(max_length=5) cost = models.FloatField() selection = models.FloatField() form = models.FloatField() points = models.IntegerField() lastgwscrape = models.DateTimeField(null=True) lastapiupdate = models.DateTimeField(null=True) currentgwdt = models.DateTimeField(null=True) apiid = models.IntegerField(null=True) The apiid field was previously defined as unique and it was removed as a test to make this migration work. class APIPlayerGW(models.Model): player = models.ForeignKey(Player, related_name='apigws', on_delete=models.CASCADE) gwid = models.IntegerField() points = models.IntegerField() minutesplayed = models.IntegerField() goalsscored = models.IntegerField() assists = models.IntegerField() cleansheets = models.IntegerField() goalsconceded = models.IntegerField() owngoals = models.IntegerField() penaltiessaved = models.IntegerField() penaltiesmissed = models.IntegerField() yellowcards = models.IntegerField() redcards = models.IntegerField() saves = models.IntegerField() bonuspoints = models.IntegerField() bonuspointsystem = models.IntegerField() influence = models.FloatField() creativity = models.FloatField() threat = models.FloatField() ictindex = models.FloatField() datetime = models.DateTimeField(default=timezone.now) … -
Why Ip in django honybot is None
I download honeypot using bib and added it in my url django project file, and I use it in my website that is production, I use nginx. and why Honeypot return <a href="?ip_address=None">None</a> -
CSS and JS of base django template not loading in other django templates which extends it
I made a base template for my django project called 'base.html' Now , I tried to extend this base template from 2 other templates called 'homepage.html' and 'product.html' the code for homepage.html is as follows: {% extends 'base.html' %} {% block content %} <!-- ========================= SECTION ========================= --> <section class="section-name padding-y-sm"> <div class="container"> <header class="section-heading"> <a href="#" class="btn btn-outline-primary float-right">See all</a> <h3 class="section-title">Popular products</h3> </header><!-- sect-heading --> <div class="row"> {% for product in newest_products %} <div class="col-md-3"> <div href="{% url 'product' product.category.slug product.slug %}" class="card card-product-grid"> <a href="{% url 'product' product.category.slug product.slug %}" class="img-wrap"> <img src="{{ product.get_thumbnail }}"> </a> <figcaption class="info-wrap"> <a href="{% url 'product' product.category.slug product.slug %}" class="title">{{ product.title }}</a> <div class="price mt-1">Rs {{ product.price }}</div> <!-- price-wrap.// --> </figcaption> </div> </div> <!-- col.// --> {% endfor %} // --> </div> <!-- row.// --> </div><!-- container // --> </section> <!-- ========================= SECTION END// ========================= --> {% endblock %} Now when I try to do the same in product.html page , that is , when i try to extending base.html from product.html too , the css and js is not working for some reason {% extends 'base.html' %} {% block content %} {% endblock %} What is the issue here … -
Django hosting on Cloudera applications: server not starting
I am trying to port a django web application from some server to cloudera "applications" and I was trying to make it work. I managed to do so with flask and fastapi applications, just the django framework is missing. My problem, when trying the base setup (https://docs.djangoproject.com/en/3.2/intro/tutorial01/), locally works like a charm but when I try to start up the server from an instance in cloudera, the server does not start and, more curiosuly, I get a weird output related to some package of the image I am spinning. (you can see I am bypassing the traditional runserver command on django because in the cloudera applications side I cannot run shells directly and also due to the fact that I would to tie it up with some environmental variable) below the manage.py import os import sys if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") from django.core.management import execute_from_command_line port_to_pass = 8000 args = ['name', 'runserver', '127.0.0.1:%d' % port_to_pass] execute_from_command_line(args) weird "print" (the instance I am spinning has got the exact same package versions installed locally): when I should be getting: any idea what might the problem be? -
How do I solve an OSError [Errno2] no such file or directory
I am trying to install Django but there was a problem the first time I installed it so I uninstalled it. When trying to install it again I got back a message saying that the requirement is already fulfilled in a certain folder then it brings up an error saying that packages could not be installed because there is no such folder or directory. -
Error Trying to save Image to django model
I used beautiful soup to scrap and extract images from a website describe below successfully but when I viewed the extracted images they appear as Url as shown below. I then experience difficulty in attempting to save the scraped image to my django database as a particular error shown below keeps on appearing. After I got the error I also tried using a forloop to create the post because I thought am trying to save a list element in a single data but it still shown the same or I got the same error not commited but when I remove the image scrap data from the file in title, summary, content and try to save to django database.it was a success. Saving image is the problem and I need help Below is my sample code My scraped images appear as a list of url as shown below https://people.net/wp-content/uploads/2021/03/ad1-746x375.jpg https://people.net/wp-content/uploads/2020/08/caroon-1-600x375.jpg something like this brought the images images = [i['data-src'] for i in soup.find_all('img', {'class','attachment-jnews-750x375 size-jnews-750x375 lazyload wp-post-image'})] but am unable to save the images scraped above like this because it will bring an error Post.objects.create( title=title, content_1=paragraphs, image=images, sources=lnk, ) this will bring an error when i try saving to models … -
Is there any reporting tool similar StimulSoft for using in Python and Django?
I'm looking for a reporting tool which capable generate printable docs same as StimulSoft in .net. I'm new in Django and I would be glad to help me. thanks -
PayPal payment method with commission
I am currently working on a project on which one user can personally send files or documents to other users. If the sender wants he could set a price for the file and the receiver have to pay in order to download that file. I have decided to use PayPal for the payment processes. Now from each transaction(of money), I want a little commission from the money that the sender gets. At first I had a idea of receiving all the payments(form the receiver) on my personal account, keep some commissions and transfer the remaining to the sender. But it would make the entire process so difficult and hard to maintain. I have currently read this and I am wandering if that gives you some commission for the transactions or it doesn't? At the end, My question is 'Can you get some commission(or money) using paypal payee.(or directly sending the money form sender to receiver)?' If I have made some mistakes, Please forgive me.. Thank you -
Filter related values from Django Admin M2M relation
Is it possible to filter related values in Django admin? I have many to many relationship set to be displayed inline. However there are many values so I want to somehow be able to search/filter those that I need. So here are the two models (I used Join table): # Create your models here. class Country(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name='Country') class Meta: verbose_name_plural = "Countries" def __str__(self): return self.name class OpenDestination(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name='Country') origin_country = models.ManyToManyField(Country, through='BorderStatus') def __str__(self): return self.name class BorderStatus(models.Model): STATUS_CHOICES = [ ('OP', 'OPEN'), ('SEMI', 'CAUTION'), ('CLOSED', 'CLOSED') ] Country = models.ForeignKey(Country, on_delete=models.CASCADE) OpenDestination = models.ForeignKey(OpenDestination, on_delete=models.CASCADE) status = models.CharField(max_length=6, choices=STATUS_CHOICES, default='CLOSED') class Meta: unique_together = (('Country', 'OpenDestination')) def __str__(self): return str(self.Country) + ' and ' + str(self.OpenDestination) And in admin.py class OpenDestinationInline(admin.TabularInline): model = OpenDestination.origin_country.through class ConutryAdmin(admin.ModelAdmin): inlines = [ OpenDestinationInline ] filter_horizontal = ('origin_country',) admin.site.register(Country, ConutryAdmin) admin.site.register(OpenDestination) admin.site.register(BorderStatus) So now when I access one coutry from Country model I see list of many countries from OpenDestination model (each having own status thanks to the Join Table). Now Im trying to figure out if its possible to filter countries from 'OpenDestination' when accessing single country from 'Country'. I tried adding filter_vertical/horizontal … -
Celery task not saving into Django sqlite db
I'm new to programming and I'm trying to schedule a task with celery to save data into sqlite db. I can't seem to get the data into the database. I am using redis as my broker, windows 10, and the latest version of both celery and django. models.py from django.db import models class Ticker(models.Model): BULLISH = 'Bullish' BEARISH = 'Bearish' NEUTRAL = 'Neutral' SENTIMENT = ( (BULLISH, 'Bullish'), (BEARISH, 'Bearish'), (NEUTRAL, 'Neutral'), ) ticker = models.CharField(max_length=200) date_posted = models.DateTimeField() sentiment = models.CharField(max_length=200, choices = SENTIMENT) sentence = models.TextField() def __str__(self): return ("Ticker: " + str(self.ticker) + " Date: " + str(self.date_posted) + " Sentiment: " + str(self.sentiment)) celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wsbscraper.settings') app = Celery('wsbscraper') app.config_from_object('django.conf:settings', namespace='CELERY') @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. app.conf.beat_schedule = { 'add-every-30-seconds': { 'task': 'main.tasks.scrape_test', 'schedule': 10.0, # 'args': (16, 16) }, } # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py @shared_task def simple_print(): print("Hello World!") @shared_task def scrape_reddit(): run() @shared_task def scrape_test(): test_run -
django data shows all but images
My product card: product name and price shows but not image <Card> <Card.Img src={product.image_one} /> <Card.Body> <Card.Title as="div"> <strong>{product.name}</strong> </Card.Title> <Card.Text>${product.price}</Card.Text> </Card.Body> </Card> My settings.py: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_ROOT = 'static/images' My urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('core.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The image shows when i enter in the image url in replace of the image_one props. What am i doing wrong? -
Using jquery clone function only one data is saved to database Django
if there are two forms then only the value of last form is registered on the data base if clicked on submit button. The thing that i want is to dynamically add forms according to the integer provided by the user (eg. If the user wants 3 rooms then 3 forms are to be added dynamically) and the data in the form is to be added on the database HTML CODE <form id = "mainForm" method ="post"> {% csrf_token %} <div id="first-group" class = "new"> <div id="bookform"> <n class="fa fa-user" aria-hidden="true"></n> <input name="name" type="text" id="input" placeholder="Name" name="name" required/> </div> <div id="bookform"> <n class="fa fa-flag" aria-hidden="true"></n> <select name="nationality" id="nation" style="width: 95%; border: none;" required> <option data-display="">Nationality</option> <option value="afghan">Afghan</option> <option value="albanian">Albanian</option> <option value="algerian">Algerian</option> <option value="american">American</option> <option value="andorran">Andorran</option> <option value="angolan">Angolan</option> <option value="antiguans">Antiguans</option> <option value="argentinean">Argentinean</option> <option value="armenian">Armenian</option> <option value="australian">Australian</option> <option value="austrian">Austrian</option> <option value="azerbaijani">Azerbaijani</option> <option value="bahamian">Bahamian</option> <option value="bahraini">Bahraini</option> <option value="bangladeshi">Bangladeshi</option> <option value="barbadian">Barbadian</option> <option value="barbudans">Barbudans</option> <option value="batswana">Batswana</option> <option value="belarusian">Belarusian</option> <option value="belgian">Belgian</option> <option value="belizean">Belizean</option> <option value="beninese">Beninese</option> <option value="bhutanese">Bhutanese</option> <option value="bolivian">Bolivian</option> <option value="bosnian">Bosnian</option> <option value="brazilian">Brazilian</option> <option value="british">British</option> <option value="bruneian">Bruneian</option> <option value="bulgarian">Bulgarian</option> <option value="burkinabe">Burkinabe</option> <option value="burmese">Burmese</option> <option value="burundian">Burundian</option> <option value="cambodian">Cambodian</option> <option value="cameroonian">Cameroonian</option> <option value="canadian">Canadian</option> <option value="cape verdean">Cape Verdean</option> <option value="central african">Central African</option> <option value="chadian">Chadian</option> <option value="chilean">Chilean</option> <option value="chinese">Chinese</option> <option … -
How to get the pk of several objects in the domain name url www.site.com in Django
I try to build a blog and this blog in the home view www.site.com consist of posts and these posts have comments, Now I Show the posts using List [] because the user has the ability to follow the content and in this list, I show the content based on the user, Now I successfully to show the posts but this post contains comments that's mean I need to get the pk of the post but as I said this post in the home view www.site.com without any extra URL that's mean as My knowledge I can't pass the pk in the def home_screen_view(request, pk) because this raise error home_screen_view() missing 1 required keyword-only argument: 'pk' So my qustion how can I get the pk in the base url www.site.com My view def home_screen_view(request, *args, **kwargs): users = [user for user in profile.following.all()] post = [] for u in users: p = Account.objects.get(username=u) posts = p.post_set.all() post.append(posts) my_posts = request.user.post_set.all() post.append(my_posts) if len(post): post= sorted(chain(*post), reverse=True, key=lambda post: post.created_date) posts = Post.objects.filter(pk=post.pk) # here I want to get the pk of the post in order to show the comments related this post comment = PostCommentIDE.objects.filter(post=posts) The url path('', home_screen_view, name='home'), … -
Django image compression and resize not working
I don't understand why this code can't resize image? Why image is uploading it's actual size? here is my code: #models.py from django.db import models from PIL import Image class Post(SafeDeleteModel): header_image = models.ImageField(upload_to="blog/images/", blank= True, null= True) def save(self,*args,**kwargs): super().save(*args, **kwargs) img = Image.open(self.header_image.path) if img.height > 300 or img.width > 300: out_put_size = (300,300) img.thumbnail(out_put_size) img.save(self.header_image.path) I aslo want to know how to applay format and quality attribute of PIL in django model. see below: ("kenya_buzz_compressed.jpg", format="JPEG", quality=70)