Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What does "uWSGI is a self-healing application" practically mean?
According to Django Official Documentation: uWSGI is a fast, self-healing and developer/sysadmin-friendly application container server coded in pure C. What exactly are self-healing applications and how is this paradigm implemented by uWSGI? Last but not least, what is the importance of this aspect of uWSGI for django? -
Possible to have react + Django on pythonanywhere.com
Is it possible to deploy react front end app and Django as back end app on pythonanyhere.com? I have django API as back end and React as Front app. -
DICOM image display in Django
How to display DICOM image in my Django 3 template HTML file. I have pydiacom, Pil & Matplotlib installed. I want to send the dicom image from view to template. How can I do this, is it the correct process for I'm doing wrong. -
Find and delete content with BeautifulSoup
I have blog text (application in django) where I want to get rid of some content. I try to search for content using BeautifulSoup. I want to find and delete everything between wphimage tags. Below is my code. What doesn't work is the wphimage tag that appears when I display soup objects after running it, where I did write to obj.text my code class Command(BaseCommand): def handle(self, *args, **kwargs): article = Blogposts.objects.all() for obj in article: soup = BeautifulSoup(obj.text, 'html.parser') for i in soup.find_all('wphimage'): obj.text = str(i.replace_with('')) obj.save() content of blog post Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. <wphimage data="{'FileId':6182,'Copyright':'John Smith','Alignment':'left','ZoomDisabled':false,'ImageOnly':false,'AlternativeText':'John Smith','ImageVersion':'conductorportraitlong','tabid':0,'moduleid':0}"> <span style="display:block; float:left;" class="DIV_imageWrapper"> <a data-lightview-title="Adela Frasineanu" data-lightview-caption="" class="lightview" href="//example.com/static/images/image.JPG"> <img src="//example.com/static/images/image.JPG" alt="John Smith"> </a> <a href="javascript:;">≡ <span>John Smith</span></a> <a class="A_zoom lightview" href="//example.com/static/images/image.JPG" data-lightview-title="John Smith" data-lightview-caption="">+ </a> </span> </wphimage> Lorem ipsum dolor sit amet, consectetur … -
Try to display images from a directory in Django
I try to display all images from a directory that is in the project. In the views.py def showimages(request): path='C:\\Users\Peter\PycharmProjects\displayimages\displayimages\display\static' img_list = os.listdir(path) return render(request, 'displayphotos.html', {'images':img_list}) In the html file {% for image in images %} <p>{{image}}</p> <img src="{% static '{{image}}' %}"> {% endfor %} But the display is <p>DSC_5390.jpg</p> <img src="/static/%7B%7Bimage%7D%7D"> <p>DSC_5392.jpg</p> <img src="/static/%7B%7Bimage%7D%7D"> If I print them in paragraph tag, all file names are correct, but all wrong in img tag. How can I fix it? -
What should I change to get access to the context data 'post'?
I have passed the context 'is_liked' to the home page and I have tried to set up the condition of is_liked in PostListView by getting the context data and modify it. But it did not run in the home page without any error message. I am thinking if it is because I have defined the context_object_name to post so that I should change the def get_context_data. Thanks Views.py def home(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post.objects.all(), 'is_liked': is_liked, 'total_likes': post.total_likes(), } return render(request, 'blog/home.html', context) class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context -
Geodjango: how to load .shp file and convert to geojson with the right CRS?
I have multiple shapefiles (.shp) with their auxiliary files that I want to display on a Leaflet map. The shapefiles use different coordinate reference systems (CRS) and I struggle to grasp the most straightforward and reliable way to show things on the map. In the geodjango tutorial, DataSource is used to load a shapefile and then manipulate it. However, in their examples they only retrieve the geometry of individual features, not of the entire shapefile. I have used PyShp and I am able to show a map using something like: sf = shapefile.Reader(filename) shapes = sf.shapes() geojson = shapes.__geo_interface__ geojson = json.dumps(geojson) However, this fails when the CRS is not WGS84 things don't work, and I don't see how to convert it. Reading a bit more, this post complains about CRS support and pyshp, and suggests using ogr2ogr. So after trying to understand the options I see using Datasource, pyshp, and ogr2ogr as possible options, but I don't know which option really makes most sense. All I want is convert a .shp file using Django into a geojson string that uses WGS84, so that I can include it on an HTML page that uses Leaflet. Can anyone with more experience … -
Summation of number in django
I have two models like this: class ItemType(models.Model): type = models.CharField(max_length=100) class Items(models.Model): item_type = models.ForeignKey(ItemType, on_delete=models.CASCADE) item_amount = models.FloatField() now I want to get sum of item_amount according to item_type. How I can do this? -
Dynamic Wagtail bgcolor templatetags
I am trying to get a dynamic background color with Wagtail templatetags when I convert an image like this : {% load wagtailimages_tags %} {% image my_file width-768 format-jpeg bgcolor-171721 as image_jpeg %} <img src="{{ image_jpeg.url }}"/> How I can change the value bgcolor-171721 with a dynamic variable in my template ? -
Log out when sending a form
I've got a problem, i've create an app where you can make comment (wich send a form to a database and save it) if you're login on only, but when i press the button "Create" instead of redirecting me to the page where it show all the comments, it log me out and bring me back to the "log out" view (wich is / ) the create Teamplate : {% extends 'base.html' %} {% block content %} <div class="create_comment"> <h2>Write a comment</h2> <form class="site-form" action="{% url 'create' %}" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Create"> </form> </div> {% endblock %} The Views of Create : @login_required(login_url='/userprofile/login/') def comments_create(request): if request.method == 'POST': form = forms.CreateComment(request.POST) if form.is_valid(): form.save() return redirect('/usercomments') else: form = forms.CreateComment() return render(request,'usercomments/comments_create.html', {'form':form}) Log out view : def logout_view(request): if request.method == 'POST': logout(request) return redirect('/') else: pass -
update() methid in CreateView django
i want to to update field whenever an instance been created i tried signals but it seems complicate to ManyToManyField class MobileCustomer(models.Model): customer = models.CharField(max_length=30) phone = models.CharField(max_length=13) mobile = models.ManyToManyField(MobileStorage,through='SelectMobile') class SelectMobile(models.Model): mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) item = models.ForeignKey(MobileCustomer,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) imei = models.ManyToManyField(Imei) class MobileStorage(models.Model): mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Mobile(models.Model): mobile_name = models.CharField(max_length=40,unique=True) class Imei(models.Model): imei = models.CharField(max_length=15,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) active = models.BooleanField(default=True) i want to update active field in Imei model when MobileCustomer created !? i tried this in my CreateView form_valid imei = Imei.objects.filter(selectmobile__item=self.object).update(active=False) print(imei) and it printed 0 ? how to make it work either using signals or update() whenever an instance created inside createview -
Django model autogenerate from a legacy mysql database: do I have to change the on_delete parameter's value from models.DO_NOTHING
I write a sql file for a mysql database as follows: create table bank ( bankname VARCHAR(20) not null, city VARCHAR(20) not null, money DOUBLE not null, constraint PK_BANK primary key (bankname) ); create table department ( departID CHAR(4) not null, departname VARCHAR(20) not null, departtype VARCHAR(15), manager CHAR(18) not null, bank VARCHAR(20) not null, constraint PK_DEPARTMENT primary key (departID), Constraint FK_BANK_DEPART Foreign Key(bank) References bank(bankname) ); create table employee ( empID CHAR(18) not null, empname VARCHAR(20) not null, empphone CHAR(11), empaddr VARCHAR(50), emptype CHAR(1), empstart DATE not null, depart CHAR(4), constraint PK_EMPLOYEE primary key (empID), Constraint FK_DEPART_EMP Foreign Key(depart) References department(departID), Constraint CK_EMPTYPE Check(emptype IN ('0','1')) ); create table customer ( cusID CHAR(18) not null, cusname VARCHAR(10) not null, cusphone CHAR(11) not null, address VARCHAR(50), contact_phone CHAR(11) not null, contact_name VARCHAR(10) not null, contact_Email VARCHAR(20), relation VARCHAR(10) not null, loanres CHAR(18), accres CHAR(18), constraint PK_CUSTOMER primary key (cusID), Constraint FK_CUS_LOANRES Foreign Key(loanres) References employee(empID), Constraint FK_CUS_ACCRES Foreign Key(accres) References employee(empID) ); create table accounts( accountID CHAR(6) not null, money DOUBLE not null, settime DATETIME, accounttype VARCHAR(10), constraint PK_ACC primary key (accountID), Constraint CK_ACCOUNTTYPE Check(accounttype IN ('SaveAccount','CheckAccount')) ); create table saveacc ( accountID CHAR(6) not null, interestrate float, savetype CHAR(1), … -
Django: How to compare two querysets and get the difference without including the PK
I don't think the word difference is correct because you might think difference() but it makes sense to me what I am trying to achieve. I do apologize if this is a common problem that's already been solved but I can't find a solution or dumbed down understanding of it. I have two querysets of the same model as follows: qs1 = ErrorLog.objects.get(report=original_report).defer('report') # 272 rows returned qs2 = ErrorLog.objects.get(report=new_report).defer('report') # 266 rows returned I want to compare the first one to the second one and find the 6 rows that don't match in the first qs1 I tried difference() and intersection() but I keep ending up with the same 272 rows or 0 rows. I have a feeling that it sees pk as a unique value so it never finds matching rows. I tried the following: # Get the 4 fields I want to compare and exclude field_1 = [error.field_1 for error in qs2] field_2 = [error.field_2 for error in qs2] field_3 = [error.field_3 for error in qs2] field_4 = [error.field_4 for error in qs2] # Assuming this would work qs3 = qs1.exclude(field_1__in=field_1, field_2__in=field_2, field_3__in=field_3, field_4__in=field_4) # But ended up with 10 rows in qs3 since it doesn't loop … -
How to restrict user going back after logout Using DJANGO
views.py def logout_user(request): # Contact Page logout(request) messages.success(request, f'logout successful') return redirect('login') -
ADDing file via Browsable Api in django rest framework
I am new to django and rest framework. There are two models named Video and Course and ManyToMany relationship as described below. class Video(models.Model): video = models.FileField(upload_to='static', null=True, blank=True) class Course(models.Model): title = models.CharField(max_length=250) video = models.ManyToManyField(Video) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) def __str__(self): return self.title When I add new course via admin panel, I can add new video to server by + sign in the right side. However, when I try to add new course via browsable API,(by POST method) It looks like I can only use videos which are already in the server, so I cant add new one.How can I add new Video when I add new course via api? -
django model method to return queryset with annotate
i am trying to define a field which being calculated based on user_type, I did the following method but its not working, if anyone can advise me to the correct approach. so what i am trying to achieve here is to construct a method such as <user>.book_limit to return the maximum number of allowed books based on user_type #models.py class UserProfile(models.Model): class UserType(models.TextChoices): FREE = 'FR', 'FREE' BASIC = 'BS', 'BASIC' PREMIUM = 'PR', 'PREMIUM' user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') bio = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) user_type = models.CharField(max_length=2, choices=UserType.choices, default=UserType.FREE) def __str__(self): return self.user.username @property def borrow_limit(self): return UserProfile.objects.annotate(book_limit=Case( When(user_type=UserProfile.UserType.FREE, then=Value('1')), When(user_type=UserProfile.UserType.BASIC, then=Value('2')), When(user_type=UserProfile.UserType.PREMIUM, then=Value('5')), default=Value('1'), output_field=IntegerField)) -
django url doesn't redirect properly
I am trying to send user to next page using button like this <a href="weekly/" class="btn">Weekly Report</a> <a href="daily/" class="btn">Daily Report</a> but when i click on header or another button at daily url keeps stacking like daily/weekly instead /daily or /weekly. It doesn't clear url and go to button instead just keeps adding it. this is url.py urlpatterns = [ path('', views.index, name="Home"), path('weekly/', views.weekly, name="weekly"), path('daily/', views.daily, name="daily"), ] i tried different ways to call url like {% url 'weekly' %} but still its same. All urls only keep stacking. even home page button does keep stacking -
How to store multiple values in a CharField in Django
Using TaggableManger from django_taggit didn't worked for two fields. The requirement is I have two fields in which I have to save the multiple keywords.For example user can give inputs like Hello World, 'Hi' and so on and I have to store them in one field and same goes to the another field also.How can I design my models properly ? class MyModel(models.Model): one_field = TaggableManager() another_field = TaggableManager() -
Am i missing something on templates on django
This is my code on html file on a django project. I am using this cod on this function def home(request): context = { 'post': posts } return render(request, 'blog/home.html', context) Template: <html> <head> <title> </title> </head> <body> {% for post in posts %} <h1>{{post.title}}</h1> <p>By {{post.author}} on {{post.date_posted}}</p> <p>{{post.content}}</p> {% endfor %} </body> </html> -
Why is MySQL Fulltext index not functioning?
I have a user table that looks something like this for testing: USER ---------------------------------- id username name 1 "djangoIsAwesome" "Ale" 2 "craze123" "John" 3 "hope this works" "JJ" 4 "Rage" "Ludo" 5 "coolguy1996" "Frank" I need to execute extremely performant queries that respond as the user is typing for a user. Normally one would use the LIKE %string% strategy but I can not afford to here as the USER table has millions of rows. I created a Fulltext index like so ALTER TABLE app.user ADD FULLTEXT ft_index_name(username, name); However, I tested the supposedly performant query: SELECT id, username, name FROM app.user WHERE MATCH (username, name) AGAINST ({string}); But I am not getting any rows returned in the query. I have also tried all the different modes (boolean, natural langauge, query extension) with no difference. Strings I have tried: "J", "wesome", "96", "k" What is wrong? -
MultipleObjectsReturned at /cart/ get() returned more than one Order -- it returned 3
I want to use get_or_create in my code, but when it returns more than one record, it shows MultipleObjectsReturned error. If there is single record its runs fine. Code at Views.py def cart(request): if request.user.is_authenticated: customer=request.user.customer order , created=Order.objects.get_or_create(customer=customer, complete=False) items=order.orderitem_set.all() else: items=[] order={'get_cart_total':0, 'get_cart_items':0} context={'items':items, 'order': order} return render(request, 'store/cart.html', context) Any help will be appreciated. Thanks. -
Django project can't grab frames
[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1159) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638 I am trying to do a simple project to show a webcam feed on my browser to learn how to do webApps with Python, and this error keeps popping up. Tried using the code of someone else on this site to learn and see how to improve upon it, to no avail. I am running this on Visual Studio Code. from django.shortcuts import render from django.http.response import StreamingHttpResponse from django.views.decorators import gzip from cv2 import cv2 import threading # Create your views here. class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() cam = VideoCamera() def gen(camera): while True: frame = cam.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def index(request): try: return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame") except: # This is bad! replace it with proper handling pass -
Django Oscar customize Dashboard
I am building a a website with django-oscar package, and I am looking for a solution to my problem. I want that the client can modify the product properties (ProductProperty class) from the dashboard. I think I have to create a new tab for editing properties at the left sidebar when I click on Edit product. Unfortunately I did not find any documentation to that. enter image description here -
Django: how to pass color as context variable to templates
I need some help: I want my view to pass as context parameter a color to the template in order to overrule the default colors within the svg files displayed by the page. I have a list of color constants: COLORS = {"W": "#ffffff", "V": "#065636", "B": "#0253A5", "R": "#CC1011"} I have within my view definition the definition of context variables: view_context = { 'user_display_name': user.user_display, 'lightcolor': COLORS[user.lightcolor], } return render(request, 'pages/page5.html', context=view_context) and within my template (pages/page5.html), I have a <style> section where to define the CSS styles: <style> .X { /* fill: #065636 !IMPORTANT; */ fill: "{{ lightcolor }}" !IMPORTANT; } </style> .X {fill: #065636 !IMPORTANT;} works just fine while .X {fill: "{{ lightcolor }}" !IMPORTANT;} does not work and is ignored, I guess because lightcolor is a string "#065636" instead of a RGBcolor #065636 similarly .X {fill: {{ lightcolor }} !IMPORTANT;} does not even appear to be a recognized syntax and I cannot find anything relevant on internet How could I pass the color as context parameter into the <style> section of the template and get this working? -
Angular HttpClient infinite loading by set header bearer
I have this code to get data from API return this.httpClient.get<any>(requestUrl, { headers: new HttpHeaders({ "Content-Type": "application/json", "Authorization": "Bearer " + this.cookieService.get('auth-token'), }), }); when I subscribe to this like this return this.api.loadAll('cuser').subscribe( result => { console.log(result); }, ); It doesn't return any data to me and just loading but when I remove the headers and call it again it shows me the data. return this.httpClient.get<any>(requestUrl, { // headers: new HttpHeaders({ // "Content-Type": "application/json", // "Authorization": "Bearer " + this.cookieService.get('auth-token'), // }), }); But I need the Authorization and the token to get current user data from Django back-end. So what make my code wrong? Following is the Post man sample that return correct data without issue var myHeaders = new Headers(); myHeaders.append("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkyNTUxMTE3LCJqdGkiOiIxMGJlZWExMDQ0MmE0NmUyOGVmM2E5NTBjY2NiNTRmOSIsInVzZXJfaWQiOjF9.5XOhaXANSk4CGbh7pHqE99Qh_yxj6YuewZHFC1UScIs"); var requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' }; fetch("http://localhost:8000/api/cuser", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));