Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Access values from dictionary in Javascript
I am try to fetch my item_id field from model.py in django in query set form that below <QuerySet [<Item: Shoulder Bag Boys Shoulder Bag (Yellow )>, <Item: Sweeter Cotton Sweeter>, <Item: Shirt Full Sleeves Shirt>, <Item: Jacket Jackson Jacket>, <Item: Yellow Shoes Leopard Shoes>, <Item: Bag Mini Cary Bag>, <Item: Coat Overcoat (Gray)>, <Item: TOWEL Pure Pineapple>, <Item: Coat Pure Pineapple>, <Item: TOWEL Pure Pineapple (White)>]> Here is my JS Code $.ajax({ type: 'GET', url: '/shopsorting/' + selected_value, // data: formData, encode: true }) .done(function(data) { items = JSON.parse(data) console.log(items) for (var item in items) { console.log(item['product_id']) }; But it print in console `(index):765 {items: "<QuerySet [<Item: TOWEL Pure Pineapple>, <Item: Ba…s Leopard Shoes>, <Item: Jacket Jackson Jacket>]>"} (index):767 undefined` -
Ajax sending data twice in views.py django
I have this form in index.html and two submit button on clicking on one button named .graph-btn I m using jquery and ajax to send data from form to Django. Code: index.html <form action="{% url 'Graph' %}" method="post"> {% csrf_token %} <table class="table table-striped table-dark" cellspacing="0"> <thead class="bg-info"> <tr> <th>Company's Symbol</th> <th>Current Price</th> <th>View Current chart</th> <th>Action</th> </tr> </thead> <tbody> {% for a,b in stocks %} <tr> <th scope="row" class="comp_name">{{ a }}</th> <td>{{ b }}</td> <td> <input type="submit" class="btn graph-btn" name="_graph" value="View Graph"> </td> <td> <input type="submit" class="btn predict-btn" formaction="{% url 'Graph' %}" name="_predict" value="Predict Closing Price"> </td> </tr> {% endfor %} </tbody> </table> </form> <script> $(".graph-btn").click(function(e) { var $row = $(this).closest("tr"); var $text = $row.find(".comp_name").text(); var name = $text; console.log(name); $.ajax({ type:'POST', dataType: "json", url:'{% url 'Graph' %}', data:{ 'text': name, 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), }, success:function(json){ }, error : function(xhr,errmsg,err) { } }); }); </script> here I want to take data from th row named .comp_name and pass the data to views.py in Django. There is problem is Ajax. views.py def graph(request): if request.method == 'POST': print("testing....") print(request.body) print(request.POST.get('text')) name = request.POST.get('text') context = { 'name': name, } print(context) return render(request, 'StockPrediction/chart.html') else: return render(request, 'StockPrediction/greet.html') I m using Print statement … -
Django create_or_update get changes fields
I'm using Django create_or_update function. In case of update, Is there a way to know the list of changed fields. Obviously I can use the get_or_create function before and in case, after this, I can update the model.. but I'm looking for a way to have this using a single query. Is it possible? -
Overwrite float:left property in span
I want the submit button to appear below the map. I can achieve this by deactivating float:left. How could I achieve this? I tried overwriting the properties of <Span>. <html> <head> <style> input[type=submit] {display: block} span {float:none} </style> {{ form.media }} </head> <body> And modifying the properties of the widget. Neither worked. widgets = { 'Location': OsmPointWidget(attrs={ 'map_width': 300, 'map_height': 300, 'style':'float:none'}), -
How to set href in Django template page
I'm fairly new to Django. I have homepage template that looks like this: {% block content %} {% for link in embededLinks %} <div class="row justify-content-center"> <blockquote class="twitter-tweet"> <p lang="en" dir="ltr">Do you get the impression that the Supreme Court doesn’t like me?</p> &mdash; Donald J. Trump (@realDonaldTrump) <a href="{{%link%}}">June 18, 2020</a> </blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> </div> {% endfor %} {% endblock %} The loop runs through a list of links for my website to display embedded tweets correctly. This html will be put in a base template I have. Only problem is I get an error at this line: <a href="{{%link%}}">June 18, 2020</a> The href link is generated in another python file and is of type str. Only thing is I'm not sure how to set the href using Django. -
Password not set for new django users
When a new user signs up for an account, the admin panel shows that a password has not been set for the user (despite saving it via views.py). Another strange thing I noticed is that the password is being saved to the email field in the database. The code appears fine. Not sure where I went wrong. Any help would be greatly appreciated. sign up html template {% if user.is_authenticated %} <h2>currently logged in as {{ user.username }} </h2> {% else %} <h1 class="h5 text-center">Create Account</h1> <h4>{{ error }}</h4> <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" name="username" autocomplete="username" placeholder="Username" id="id_username" required> </div> <div class="form-group"> <label for="password1">Password</label> <input type="password" class="form-control" name="password1" placeholder="Password" autocomplete="new-password" required id="id_password1"> <small>Password must be at least 8 characters</small> </div> <div class="form-group"> <label for="password2">Confirm Password</label> <input type="password" class="form-control" name="password2" placeholder="Confirm Password" autocomplete="new-password" required id="id_password2"> </div> <ul> <li>Your password can’t be too similar to your other personal information.</li> <li>Your password must contain at least 8 characters.</li> <li>Your password can’t be a commonly used password.</li> <li>Your password can’t be entirely numeric.</li> </ul> <!-- <div class="form-group"> <div class="custom-control custom-checkbox text-small"> <input type="checkbox" class="custom-control-input" id="sign-up-agree"> <label class="custom-control-label" for="sign-up-agree">I agree to the <a target="_blank" href="utility-legal-terms.html">Terms &amp; Conditions</a> </label> … -
MultiValueDictKeyError in Django trying to change profile pic
i ve got this . I just want to change profile informations in that request i tried to change first_name and last_name. Here is my views.py. Check my code and tell me what's wrong . I need a solution for my error, i didnt try anything because i dont understand and know django very well And thank you ! views.py def profile(request): if request.method == 'POST': if not request.POST['first_name'] == '' and not request.POST['first_name'] == request.user.first_name: if not request.POST['last_name'] == '' and not request.POST['last_name'] == request.user.last_name: if not request.FILES['image'] == '': User = request.user User.first_name = request.POST['first_name'] User.last_name = request.POST['last_name'] User.save() User.profile.image = request.FILES['image'] User.profile.save() return redirect('profile') else: User = request.user User.first_name = request.POST['first_name'] User.last_name = request.POST['last_name'] User.save() return redirect('profile') else: User = request.user User.first_name = request.POST['first_name'] User.save() return redirect('profile') elif not request.POST['last_name'] == '' and not request.POST['last_name'] == request.user.last_name: if not request.POST['first_name'] == '' and not request.POST['first_name'] == request.user.first_name: if not request.FILES['image'] == '': User = request.user User.profile.image = request.FILES['image'] User.first_name = request.POST['first_name'] User.last_name = request.POST['last_name'] User.save() User.profile.save() return redirect('profile') else: User = request.user User.first_name = request.POST['first_name'] User.last_name = request.POST['last_name'] User.save() return redirect('profile') else: User = request.user User.last_name = request.POST['last_name'] User.save() return redirect('profile') elif not request.FILES['image'] == '': if … -
How to center Text Under iFrame when text is wrapped around it
I have my iframe floating left and text wrapped around it. I'm trying to put text under it aligned center but everything I've tried seems to not work or mess the whole format up.. I have the code and preview here. https://codepen.io/Religion/pen/QWydbow. and what's on codepen below . Thanks! <style> .container p { font-size:1.2rem; } .container { height:100%; max-height:100%; } </style> <div class = "container"> <iframe style = "float:left;margin:5px 25px 0 0;margin-bottom:20px; width:350px; height:300px;" src="https://embed-fastly.wistia.com/deliveries/7f74ec7de31d90e32a1d465fcebc1d0e12a27d18/file.mp4" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <h2 class = "all-headings">Periodontal Maintenance</h2> <p><strong>Periodontal diseases are infections of the gums, which gradually destroy the support of your natural teeth.</strong> There are numerous disease entities requiring different treatment approaches. Dental plaque is the primary cause of gum disease in genetically susceptible individuals. Daily brushing and flossing will prevent most periodontal conditions.</p> <br> <h2 class = "all-headings">Why is oral hygiene so important?</h2> <p>Adults over 35 lose more teeth to gum diseases, (periodontal disease) than from cavities. Three out of four adults are affected at some time in their life. The best way to prevent cavities and periodontal disease is by good tooth brushing and flossing techniques, performed daily.</p> <p>Periodontal disease and decay are both caused by bacterial plaque. … -
Django throws ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
Sorry in advance if my question looks obscure. This is the error thrown by Django when I'm trying to serve multiple Django media(videos) URLs in my React homepage.This is the stacktrace: Exception happened during processing of request from ('127.0.0.1', 5511) File "D:\Django\myproject\app\env\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() Traceback (most recent call last): File "C:\Users\Anshul\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "D:\Django\myproject\app\env\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Anshul\AppData\Local\Programs\Python\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) File "C:\Users\Anshul\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine ---------------------------------------- File "C:\Users\Anshul\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 720, in __init__ self.handle() File "D:\Django\myproject\app\env\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "D:\Django\myproject\app\env\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Anshul\AppData\Local\Programs\Python\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine This is the React snippet: <video preload="metadata" id={this.props.id} muted ref={this.videoRef} onClick={this.play.bind(this,1,this.props.id)} onTimeUpdate={this.updateTime.bind(this,this.props.id)} onCanPlay={this.getReady.bind(this,this.props.id)}> <source src={this.props.source} type="video/mp4"/> </video> where video source refers to django media url provided by drf serializer.E.g this.props.source = 'http://localhost:8000/media/buck_bunny.mp4' The homepage contains multiple videos.The media URLs are fetched through API calls.Its a content feed page.Subsequent API calls to fetch … -
Django admin - make image appear over the django admin list view
Following up on a question from Django Admin - display image on hover. I'm able to make the image appear on hover like I was hoping. However, if the django admin list view only has a few items in it, part of the image appears behind the bottom of the list Here's an example of what it looks like, with some column headers greyed out The image extends beneath the bottom of the list (as hinted at by the appearance of the scroll bar). We'd like it to pop over the top, so the full image is visible regardless of the length of the list Here's the code we have def image_column(self, object) return format_html(text+" "+\ '''<a href="{}"" target="_blank" style="font-size: 18pt; position: relative;" onmouseover="document.getElementById('{}').style.display='block'; position: relative;" onmouseout="document.getElementById('{}').style.display='none';"><div style="position:relative">📷</div> <img id="{}" style="display:none; position: absolute; top: 0px; left: 0px; width:550px; border:5px solid; z-index:1000;" src="{}" /> </a>'''.format( url, img_id, img_id, img_id, url)) I've tried setting the position:absolute in the image tag to position:relative. This makes sure the whole image is displayed when you mouse over (expanding the containing row). However, it affects the the layout of the rest of the document, which is disorienting the user Thank you!!! -
whats is the problem on this code? need help to resolve django search error
Here is the views.py #search def search(request): query = request.GET.get["query"] if len(query)>78: allItem = Item.object.none() else: allItemTitle = Item.object.filter(title__icontains=query) allItemDescription = Item.object.filter(description__icontains=query) allItem = allItem.Title.union(allItemDescription) if allItem.count() == 0: messages.warning(request, "No result found") params = {'allItem': allItem, 'query':query} return render(request, 'home/search.html', params) #search here is the url.py path('search/', views.Search, name='search'), and finally HTML Source code is here {% extends 'base.html' %} {% load static %} {% block content %} <div class="breadcrumb-area section-padding-1 bg-gray breadcrumb-ptb-2"> <div class="container-fluid"> <div class="breadcrumb-content text-center"> <div class="breadcrumb-title"> <h2>Shop 3 Column</h2> </div> <ul> <li> <a href="index.html">Home 01 </a> </li> <li><span> &gt; </span></li> <li class="active"> shop </li> </ul> </div> </div> </div> <div class="shop-area pt-70 pb-100"> <div class="container"> <div class="container"> <h3>Search Results</h3> {% if allItem|length < 1 %} <p>No Search result found</p> did not match any document Your search query:<b>{{query}}</b> {% endif %} <div class="row"> {% for item in object_list %} <div class="col-lg-4 col-md-6 col-sm-6 col-12"> <div class="product-wrap mb-50"> <div class="product-img default-overlay mb-25"> <a href="{{ item.get_absolute_url }}"> <img class="default-img" src="{{ item.image }}" height="463" width="370"alt=""> <span class="badge-black badge-right-0 badge-top-0 badge-width-height-1">{{ item.label }}</span> </a> <div class="product-action product-action-position-1"> <a title="Add to Cart" href="{{ item.link }}" target="_blank"><i class="fa fa-shopping-cart"></i><span>Shop Now</span></a> </div> </div> <div class="product-content-2 title-font-width-400 text-center"> <h3><a href=""></a>{{ item.title }}</a></h3> <div class="product-price"> {% … -
How can I set some value to inherited model class field in Django model?
I made one model(ModelA) in which 2 choices present there, I am inheriting this model, in the other two models CHOICES = (("work", "work"), ("Home", "Home")) class ModelA(models.Model): type_of_address = models.CharField(choices=CHOICES) ... class ForWorkModel(ModelA): type_of_address--->work class ForHomeModel(ModelA): type_of_address--->Home I want to inherit the model and want to set some field values, as I mentioned in the code. Is there any way? -
Django 'holding page' and redirect for background processes
I have a form (IngestFormView), which on submission kicks off multiple background processes (dealing with files uploaded in the form). I also have an API view (IngestStatusView) which shows the status of the various background processes. Finally, I have a second form (IngestCompletionFormView) which is dynamic, based on the results from the various background processes I need users to be redirected to IngestCompletionFormView, but not until the aforementioned processes have concluded. I am really quite new to JavaScript, but I know I need to do something with AJAX/JQuery to show the user the, regularly updated, status from IngestStatusView, before redirecting the user to IngestCompletionFormView. Does anyone have any recommendations for how to achieve this? I don't think I can do anything on IngestFormView as I need that to deal with form errors, so adapting it could become complex. So I had wondered if I should created a separate view to sit between the two form views. This view will then use AJAX/JQuery to call IngestStatusView and update the user on progress. Then, based on a field in IngestStatusView, it would identify that all background tasks have concluded, and redirect to IngestCompletionFormView. Thank you for any thoughts. -
Lists are currently not supported in HTML Input
I am having this problem with my browsable API: "Lists are not currently supported in HTML input." Here are my models: class Breed(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class BreedImage(models.Model): breed = models.ForeignKey(Breed, related_name='BreedImages', on_delete=models.CASCADE) breedImage = models.ImageField(upload_to='photos', null=True, blank=True) My Serializers: class ImageSerializer(serializers.ModelSerializer): class Meta: model = BreedImage fields = ['id', 'breedImage'] class BreedSerializer(serializers.ModelSerializer): BreedImages = ImageSerializer(many=True, allow_null=True, required=True) class Meta: model = Breed fields = ['name', 'BreedImages'] My view: class BreedList(generics.ListCreateAPIView): parser_classes = (MultiPartParser,) queryset = Breed.objects.all() serializer_class = BreedSerializer pagination_class = None -
Does LiClipse admit Django Templates?
I am new to Django/Python and LiClipse (Django 3, Python 3.8, Liclipse 6.1.0), and when writing the html templates, I find that the Django blocks seem to interfere with the html correction. For instance, this code in base.html: <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <meta name="generator" content="Bootply" /> <title>Report</title> <title>Este es un título</title> </head> <body> <h4>Home page de prueba de cjg</h4> </body> </html> Everything is fine, but if I add {% load static %} <!-- CSS --> {% block css %} {% endblock %} <!-- JAVASCRIPT --> {% block js %} {% endblock %} right after the title I get errors like Stray end tag “head”. for /head and An “body” start tag seen but an element of the same type was already open. Seems that the editor won't recognize django blocks. Is there any configuration I should make or some plugin I should add?. Thanks in advance for your help. -
How to split a queryset in several tranches to implement a "load more" logic using Django/jQuery to build a blog?
I am building a blog and display the 10 latest blog posts from the query which fetches the last 100 blog-posts from the database. I then want to implement a "load more" button to display another 10 blogposts and so on and so forth until all 100 are displayed. So my basic idea is that I fetch all 100 in the view and then populate the DOM using jQuery on each "load more" click. How can I accomplish this? Do I need Ajax calls to trigger a view for each button click? And how to handle the DOM since it is populated with Django variables. I guess I somehow have to re-trigger the for-in / end-for Django loop to make the new posts append and not overwrite the existing DOM? From a tutorial I tried to approach a paginator solution but I don't know how to link this to jQuery/make the magic on the frontend. blog.views def render_blog(request, template="blog.html"): category_count = get_category_count() # Display last 10 blog posts on landing page, make pagination in 10x steps via button click most_recent = Post.objects.order_by('-timestamp')[:99] post_list = Post.objects.all() paginator = Paginator(post_list, 10) page_request_var = 'page' page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except … -
ORA-00904: "TOOL_WEBPAGE"."ID": invalid identifier
I have a preexisting database which I am trying to access. I have already ran the command python manage.py makemigrations dashboard and python manage.py migrate, however I am getting an error when trying to migrate -> Unable to create the django_migrations table (ORA-2000: missing ALWAYS keyword) -
How to update the django model after useing filter or order_by?
I wanna make a website that users can update the information. here is part of my website But I have a problem here, the update only works when it is in the normal order, it won't work when I order by price or order by rank or after I filter by some choice (e.g Dell, N2840). Here is my code view.py. if request.method == 'POST' and 'update_bt' in request.POST: i = 0 asin = [] alldata = Output.objects.all() for i in alldata: asin.append(i.asin) while i < len(request.POST.getlist('brand')): Output.objects.filter(asin = asin[i]).update(List = request.POST.getlist('list')[i]) Output.objects.filter(asin = asin[i]).update(brand = request.POST.getlist('brand')[i]) Output.objects.filter(asin = asin[i]).update(cpu = request.POST.getlist('cpu')[i]) Output.objects.filter(asin = asin[i]).update(screen = request.POST.getlist('screen')[i]) Output.objects.filter(asin = asin[i]).update(ram = request.POST.getlist('ram')[i]) Output.objects.filter(asin = asin[i]).update(Type = request.POST.getlist('type')[i]) Output.objects.filter(asin = asin[i]).update(model = request.POST.getlist('model')[i]) Output.objects.filter(asin = asin[i]).update(os = request.POST.getlist('os')[i]) Output.objects.filter(asin = asin[i]).update(DVD = request.POST.getlist('DVD')[i]) Output.objects.filter(asin = asin[i]).update(keyboard = request.POST.getlist('keyboard')[i]) Output.objects.filter(asin = asin[i]).update(security = request.POST.getlist('security')[i]) Output.objects.filter(asin = asin[i]).update(vc = request.POST.getlist('vc')[i]) i += 1 alldata = Output.objects.all() return render(request, 'polls/base.html', {'alldata': alldata}) I understand why it only works in this way, but I just don't know how to make it work in every possible situation. I am new to Django. Does anyone know how to make it work? Thank you. -
Django 3 'User' object has no attribute 'admin'
SITUATION I am modifying this GitHub project from this YouTube Series and this is a demo how the original application runs. My goal is to add settings option for Merchant(in the code Admin or AdminUser) accounts in the marketplace, because in the original project only buyers have the option to add image and their contact details. CODE model.py #database table create class Customer(models.Model): #empty fields accept - null=True user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="profile1.png", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) #show customer name in admin panel def __str__(self): return self.name class Adminuser(models.Model): #empty fields accept - null=True user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="profile1.png", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) #show customer name in admin panel def __str__(self): return self.name url.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ ... path('customer/<str:pk_test>/', views.customer, name="customer"), path('adminuser/<str:pk_test>/', views.adminuser, name="adminuser"), ... ] views.py #CUSTOMER_ONLY PROFILE SETTINGS @login_required(login_url='login') @allowed_users(allowed_roles=['customer']) def accountSettings(request): customer = request.user.customer form = CustomerForm(instance=customer) if request.method == 'POST': form = CustomerForm(request.POST, request.FILES,instance=customer) if form.is_valid(): … -
Multiple Images Upload using Django Claases
I am creating an e-commerce web app using Django and I am stuck at adding multiple Images to a product. This is my Forms.py class ProductForm(forms.ModelForm): images = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta(): model = Products labels = { "isbn": "ISBN" } fields = ('isbn', 'title', 'authors', 'publication_date', 'quantity', 'price', 'images') widgets = { 'publication_date': DateInput() } this is my Models.py class Products(models.Model): isbn = models.CharField(max_length=50) title = models.CharField(max_length=264) authors = models.CharField(max_length=264) publication_date = models.DateField(max_length=264) quantity = models.DecimalField(max_digits=3, decimal_places=0) price = models.DecimalField(max_digits=6, decimal_places=2) seller = models.ForeignKey(User, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True) updation_date = models.DateTimeField(auto_now=True) images = models.ImageField(upload_to='images/',null=True,blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("book_item", kwargs={'pk': self.pk}) def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'pk': self.pk }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ 'pk': self.pk }) This is my Create View class ProductCreate(LoginRequiredMixin, SuccessMessageMixin, CreateView, ): form_class = ProductForm model = Products template_name = 'books/new_book.html' success_message = "Books Added" def form_valid(self, form): form.instance.seller = self.request.user Products = form.save() Products.save() return super().form_valid(form) I want to add multiple images to my product. -
Setting up deployment for Django+React project having each run on different ports with Nginx
I am developing a Django (for Web API serving) + React (frontend purpose) project where the codebase for both Django and React are consolidated in a main project folder, meaning both are on the same git repository, as below: . +-- _backend | +-- _config | | +-- settings.py | | +-- urls.py | | +-- wsgi.py | +-- _sample_app | +-- _static | +-- _media | +-- manage.py | +-- requirements.txt +-- _frontend | +-- _public | +-- _src | | +-- App.css | | +-- App.js | | +-- index.js | +-- babel.rc | +-- package-lock.json | +-- package.json | +-- webpack.config.js Now, I would like to implement the recommended way of integrating both technologies: Django as a standalone backend app that only serves API (no UI, assets, templates) React as a standalone SPA whose purpose is to serve the frontend (UI, web pages, assets, etc.) Which means that Django will be starting on its own port and React also on its own. Now, during development I could do: React on localhost:3000 Django on localhost:3001 However, I am not pretty sure how to deploy using the above setup on production server. I will be using Nginx for this … -
My user got log out when i'll try to send a form to a BDD (Django)
As the title said, i don't know why my user got disconnected when i create a new "Comment". AND The form should be save in the database but instead i got redirect to the root (with nothing in the database OFC :> ) halp aled ayuda Taskete My view : from django.shortcuts import render, redirect from .models import Comment from . import forms from django.contrib.auth.decorators import login_required def comments_create(request): if request.method == 'POST': form = forms.CreateComment(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/usercomments/') else: form = forms.CreateComment() return render(request,'usercomments/comments_create.html',{'form':form}) The templates : {% extends 'base.html' %} {% block content %} <div class="create_comment"> <h2>Write a comment</h2> <form action="site-form" action="{% url 'create' %}" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Create"> </form> </div> {% endblock %} Urls.py : from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.comments_list, name="list"), url(r'^create/$', views.comments_create, name="create"), url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"), ] Models.py : from django.db import models from django.contrib.auth.models import User from django.conf import settings class Comment(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) -
Django: Correct way to clear FieldField and set it to blank
I have a file field in a django model, which has a file associated with it. I would like to clear file for a record and perhaps set the filefield to the prior state it was before file was uploaded. What is the correct way to do this? -
Setting up Django-Casper
I have installed Django-Casper on my raspberry-pi following this tutorial: http://blog.daviddemartini.com/installing-casperjs-on-raspberry-pi/ I need it to tests the AJAX of my Django app. Everything worked fine but when I tried to run $ casperjs I've an error TypeError: Attempting to change the setter of an unconfigurable property. I have searched a way to fix this issue but with no luck. Has anyone encountered the same issue? -
Django says 'The _imaging C module is not installed' when I try to add images to database entries
I am working on ubuntu server,and this is my first web development project based on django. After I have hosted the site with apache2, mod_wsgi , the site is running but I have encountered two problems: 1)All the users and other database entries have been lost. I have tried makemigrations and migrate , but it didnt solve it. 2) I tried to add all the entries again, but now there is a problem with adding images to the ImageField in the databases using Pillow module.It says The _imaging C module is not installed . The error takes place in sites-packages\PIL\Image.py (I am using a virtualenv) somewhere around line 93 which is from . import _imaging as core . Python version: 3.7, django version: 3.0 , ubuntu version: 18 Here are all fixes I've tried: 1) Changed line 93 in PIL/Image.py from from . import _imaging as core to from PIL import _imaging as core . No changes, the error still occurs. 2)Tried installing libjpeg with the following code- sudo apt-get install libjpeg-dev . Turned out that I already had it globally. 3)Changed the location of virtualenv directory from somewhere inside /var/www/ to /usr/local/ because somewhere I had read that there …