Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The value of array must not be a ManyToManyField
I have a problem with my models for my django project. I'm had to use a ManyToManyField to get multiple foreign key but I don't get how it correctly works. I tried to look around the internet, google my mistake but still don't know how to resolve it. Here is the code for the model: class Framework(models.Model): name = models.CharField(max_length=200) language = models.ManyToManyField(Language) version = models.CharField(max_length=20) typeOfFramework = models.ForeignKey(TypeOfProgram, on_delete=models.CASCADE) cotationOfFramework = models.IntegerField(default = 5) additionalInformation = models.ForeignKey(web,blank=True,null=True ,default = None ,on_delete=models.CASCADE) def __str__(self): template = '{0.name} {0.version} {0.language} {0.typeOfFramework} {0.cotationOfFramework}' template.format(self) and here is the code for the admin page: class FrameworkAdmin(admin.ModelAdmin): list_display = ('name', 'language', 'version', 'typeOfFramework' ,'additionalInformation','cotationOfFramework') I got this error: (admin.E109) The value of 'list_display[1]' must not be a ManyToManyField. Can anyone help me on how to understand this and make it work? Thank you all a lot! -
Why is this Django IntegerField Select not marked as required?
I have a Django form with an IntegerField and ModelChoiceField, both of which use a Select widget. my_integer_field = forms.IntegerField(widget=widgets.Select(choices=[], attrs={'autocomplete': 'off', 'class': 'fw-select'})) my_mc_field = forms.ModelChoiceField(queryset=None, empty_label=None, widget=widgets.Select(attrs={'autocomplete': 'off', 'class': 'fw-select'})) The options are populated dynamically. I've noticed that when the form is rendered, my_integer_field is not marked as required, but my_mc_field is. What is the reason for this? I can make my_integer_field required by adding required: True to the attrs, but it was my understanding that required is the default behaviour (which my_mc_field seems to confirm). I'm using Django 3.0.2. -
python manage.py shell < script.py gives EOF error when using input()
I'm running Python3.7 I have two Python scripts: print("hi") and a = input() print(a) I can successfully run the first one in a django shell with python manage.py shell < script.py The second one gives me this error: File "<string>", line 1, in <module> EOFError: EOF when reading a line Why? This doesn't happen in the PyCharm terminal but only on the Linux CLI. -
Display image on raspberry PI
I developing a basic digital signage website for displaying different kinds of images, videos, and text files. This will be integrated with Rasberry Pi as a media player that will be connected to a monitor through HDMI. The website is already implemented and installed on the raspberry, however, I couldn't display the selected images on the monitor. Anyone who can assist or guide me through this. Thanks in advance. -
How do I create an html code with a string on python to render on django template
In my views: post_image = '<div class="images slides"></div>' console.log(document.body): <body> "<div class="images slides"</div>" </body> What I want: <body> <div class="images slides"</div> </body> -
Django - specify upload path
So I have a upload form: def upload(request): if request.method == 'POST': uploaded_file = request.FILES['file'] fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) return render(request, 'nas/upload.html') But I am not sure where to specify where the file gets uploaded to. I would like it to come from the currently active drive, which has an attribute Drive.path -
"<Comment: >" needs to have a value for field "id" before this many-to-many relationship can be used?
I'm new to use (many-to-many) relationship, I need to allow the users can leave the comment on the user post. this site looks like Quora or StackOverflow the user should signup to get the questions field to put his question and other users whose in site can leave there comments. so, how can I continue by adding (add) in (many-to-many) or the real question is: how can I add a comment by (many-to-many) in this code if anyone help me to complete this issue, please. views.py from django.shortcuts import render, redirect, get_list_or_404 from .forms import UserAskingForm, CommentForm from .models import UserAsking, Comment from django.contrib.auth.decorators import login_required @login_required def user_asking(request): form = UserAskingForm if request.method == 'POST': form = UserAskingForm(request.POST, instance=request.user.userprofile) if form.is_valid(): asking = form.save(commit=False) asking.title = form.cleaned_data['title'] asking.question = form.cleaned_data['question'] asking.field = form.cleaned_data['field'] asking = UserAsking.objects.create(userprofile=request.user.userprofile, title=asking.title, question=asking.question, field=asking.field) asking.save() return redirect('community:user_questions') else: form = UserAskingForm() return render(request, 'community/asking_question.html', {'form': form}) return render(request, 'community/asking_question.html', {'form': form}) @login_required def user_questions(request): all_objects = UserAsking.objects.all().order_by('-title') all_objects = get_list_or_404(all_objects) return render(request, 'community/user_questions.html', {'all_objects': all_objects}) def question_view(request, user_id): my_question = UserAsking.objects.get(pk=user_id) # question number e.g '1' for user 'medoabdin' comment_form = CommentForm if request.method == 'GET': comment_form = comment_form(request.GET) if comment_form.is_valid(): comments = comment_form.save(commit=False) … -
Create project-level permissions at project initialization
When I first run manage.py migrate on a Django project, I would like the database to be initialized with some extra permissions. I have seen here that this can be done at the app level, in the apps.py files. However the permissions I would like to have are rather related to the whole project than to one of its apps. My questions are: Is it OK to define project-level permissions, or are permissions meant to always be part on an app? If project-level permissions are fine, what would be the appropriate place to define them so that they are created at project initialization? -
List all values used in a session from a variable in Django
I did a simple search view to query based on this inputs. def search(request): try: query_x = request.GET.get('query_x') query_y = request.GET.get('query_y') points_returned = request.GET.get('points_returned') distance_condition = request.GET.get('distance_condition') object_list = Points.objects.filter( geom_point__distance_lte=('POINT({0} {1})'.format(query_x, query_y), D(km=10)) ).order_by('geom_point')[:int(points_returned)] request.session['query_x'] = query_x return render_to_response('search_results.html', {'object_list': object_list}) except KeyError: return render_to_response('home.html') This search will be used many times (probably with same values) so I want to save and list all the inputs used to do the query by the user (for query_x and query_y variables). I already achieved to get the value in template, but just the last one input appear when I put {{request.session.query_x}} in the template to see the results - I need to get all values used. -
Django - Calculator GUI with user input
I have a Django website and would like to include an app that serves as a form of a calculator, i.e. the user will make a few input specifications and click a button upon which Python will perform the calculations and present the output. I am trying to figure out how to build the front end for this as the user will have dropdowns and tickboxes, all of which need to be sent to the views as variables. Do I need to learn JavaScript for the front-end? If so, are there any sections of JavaScript I can focus on for this specific goal or do I resort to "a beginners guide to JavaScript" How do I "send" the user selection criteria to the Django view? TLDR; what I am actually trying to build: The end goal is a multiple regression tool where the user is presented with historic macro-economic data and an independent variable. The user will select one/many of the columns of data on which to regress the independent variable. There will also be a tick box for each chosen variable which indicates whether or not the user would want to transform the chosen variable. Once the selection has … -
convert django migrations to laravel migration
I have a django project with a large number of migration files. I want to convert these migration files to laravel migrations or directly import in laravel project to migrate. Migrating in django then export is not an option. Is there any tool or online convertor or something to do this ? -
Reload table data without refreshing the page in Django and JQuery
This post is based on a previous thread which seem to have a nice solution on how to reload table data in Django without refreshing the page. What it does In this way we use setInterval to make a GET AJAX request every 5 seconds a my view which renders a separate HTML file using this new context and then sends it as a response back to the main HTML table. I have modified the code to fit my needs, but I must have missed something since it is not working. If I try to navigate to the new html page itself it gets me the following error message: MultiValueDictKeyError at /myapp/more/ 'append_increment' Request Method: GET Request URL: http://localhost:8000/myapp/more/ Django Version: 2.2.6 Exception Type: MultiValueDictKeyError Exception Value: 'append_increment' I start to suspect the "int" in my view, I won't render only integers. increment = int(request.GET['append_increment']) If someone could point me in the right direction it would be highly appreciated! My main-table and JQuery script <script> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: {% url 'get_more_tables' %}, // URL to your view that serves new info data: {'append_increment': append_increment} }) .done(function(response) { $('#_appendHere').append(response); append_increment += 1; }); }, … -
Passing data from python to html view in django framework
I have an Application where users can enter news they heard.The entered 'news headline' , 'news' , 'time' are stored in elasticsearch noSql database.The entered news items are first analysed with NLP techniques to detect and remove unethical words and again stored in elasticsearch database.After that I want to show them on a web page in an order.I completed the processing nlp task but still I cannot display all the news items on the web page.for that I'm using django framework. what I was trying to do was extract the news items from elasticsearch using a for loop and store each news item=[news headline,news,time] as a collection of lists inside a list [[],[],[]] and pass them to the html template python code, def news_items(request): newsData = [] es = Elasticsearch([{'host': 'localhost', 'port': 9200}]) for x in range(1, 101): results = es.get(index='reporter', doc_type='news', id=x) pyData1 = json.dumps(results) pyData2 = json.loads(pyData1) newsData = pyData2['_source'] pyNewsData1 = json.dumps(newsData) pyNewsData2 = json.loads(pyNewsData1) id = pyData2['_id'] headline = pyNewsData2['newsHeadline'] newsText = pyNewsData2['newsText'] date = pyNewsData2['date'] list = [id, headline, newsText, date] newsData.append(list) template = 'AppOne/news.html' return render(request, template, {'nd': newsData}) template code to access that data <ul> {% for a,b,c,d in nd %} <li>{{a}}</li> <li>{{b}}</li> … -
How to grab data that is coming from Django admin database and assign it a value that can be styled
Description I have a Django database model with articles, each has a "title" and a number of "columns". I have looped these using a for loop inside a template tag in my HTML file. The data displays well How can I grab the different column numbers and assign style attributes to them? models: from django.db import models class Article(models.Model): title = models.CharField(max_length=128) columns = models.IntegerField() views: from django.shortcuts import render from gamerNetApp1.models import Article import collections import re # Create your views here. def index(request): Article_list = Article.objects.order_by('title') Article_dict = { 'Articles': Article_list} return render(request, 'gamerNetApp1/index.html', context=Article_dict) CSS: body { padding: 20px; font: 1em Helvetica Neue, Helvetica, Arial, sans-serif; } * {box-sizing: border-box;} p { margin: 0 0 1em 0; } .container { border: 5px solid rgb(111,41,97); border-radius: .5em; padding: 10px; display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); width: 900px; } .item { padding: 10px; background-color: rgba(111,41,97,.3); border: 2px solid rgba(111,41,97,.5); width: 300px; } HTML: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static "gamerNetApp1/css/styles.css" %}"> <title>Document</title> </head> <body> {% if Articles %} {% for col in Articles %} <div class="container" id="container"> <div class="item">{{ col.title … -
Export callback if window is close on Django import/export package
I have a form post request that directs to views to export a file. I am loading a spinner on a form request if internet connection is slow, I think I needa callback if the window is closed or download export file to hide the spinner. How do I detect if I close the window or after I export a file? -
"GET / HTTP/1.1" 200 2163 "GET /static/images/ComapnyLogo.png HTTP/1.1" 404 1692
I got this error in Django 3.0 every time. Is there any issue with the static files or setting.py path is not well defined. my settings.py path: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATIC_DIRS = [ os.path.join(BASE_DIR, 'static') ] -
how to get a query from set of queries stored in a file and display the queries related to searched queries with python
'Want to take input query from use and display the queries related to that query as output'enter link description here -
How create application backend in django and create a api so that other developers can use that as well
I just started learning Django and wanted to make an application with API (probably REST) endpoints so that other developers can use it as well (like GitHub API), and I could connect it to my react app and android app. I want my backend to be on a different server and do not want to build my react app integrated with Django backend using the REST Framework. Can anyone just give me the general idea of what I need to do? P.S. Sorry in advance if my question sounds silly, I am still new to backend. -
Django Application running on Ubuntu VPS: This site can’t be reached
I am running an ubuntu 16.04 cloud VPS server. I've set up a venv and activated it, and installed django. I run the server with python3 manage.py runserver 0.0.0.0:8000 I am trying to access this application from a remote computer (not inside the same LAN); I'm trying to make the application visible to the world outside the VPS and VPLAN. When I try to access the site in my home computer broswer like: xx.xx.xxx.xxx:8000 I get the error: This site can’t be reached. http://xx.xx.xxx.xxx:8000/ is unreachable. Now I've tried a traceroute and it seems to reach the server ok. I also did sudo ufw enable sudo ufw 8000 allow sudo iptables -S | grep 8000 (and see the proper entries) If I wget localhost:8000 I get a response fine. I have tried doing all of the above as root and as another dedicated user but it makes no difference. Does anyone have any other ideas? Thanks in advance -
Scraped pictures on Django website are not loaded, only after I visit the src in another browser tab
I have scraped images with beautifull soup. The img source and href are send to my front end. However when my page is loaded, the pictures are not. When I open the src in a seperate tab, it suddenly works on my website as well. Do I have to download these image first? In order for them to show up. This is the html result in the browser <img src="//images.5movies.to/thumbs/us-and-them-2018-108200.jpg" alt="Us and Them (2018)"> This is what is in my html file in Django. <a href="{{ allContainers.2 }}"> <img src="{{ allContainers.1 }}" alt="{{ allContainers.0 }}"/></a> -
How to have single view for multiple HTML forms - Django
This is my view.So I want to keep 2 different HTML forms in same view ,But I am unable to do so beacuse whenever I add 1 form , I get the error of other on being none. def home(request): name = None if request.method == 'POST': name = request.POST.get('name') choices = request.POST.get('choices') subtest = request.POST.get('subtest') reference = request.POST.get('reference') unit = request.POST.get('unit') test = Test() test.name = name test.save() subtest = Subtest() subtest.test = Test.objects.get(name=choices) subtest.name = subtest subtest.unit = unit subtest.reference_value = reference subtest.save() # print(name) return redirect('home') return render(request,'main.html',{}) I have got 2 different forms . I didn't use django forms because I wanted to try something new. MY FIRST FORM <form method="POST"> {% csrf_token %} <div class="icon-holder"> <i data-modal-target="test-popup" class="icon-cross"></i> </div> <div class="input-group"> <input type="text" name="name" placeholder="Test name" /> </div> <div class="button-group"> <button type="submit">Submit</button> </div> </form> MY SECOND FORM <form method="POST"> {% csrf_token %} <div class="icon-holder"> <i data-modal-target="menu-test-popup" class="icon-cross"></i> </div> <div class="input-group"> <label for="test-select">Test Name:</label> <select name="choices" id="test-select"> {% for test in test %} <option value="{{test.name}}" name='choices'>{{test.name|title}}</option> {% endfor %} </select> </div> <div class="input-group"> <input type="text" name="subtest" placeholder="SubTest name" /> </div> <div class="input-group"> <input type="text" name="reference" placeholder="Reference rate" /> </div> <div class="input-group"> <input type="text" name="unit" placeholder="Unit" /> … -
How to add a feature of adding image to a post on a website?
I am developing a social networking website for my college project in Django. One of the features of any social networking website is to allow its users to write posts that have text and images. I have been trying to implement the same. First, I thought I could use a special tag in the text for an image as StackOverflow does and before the post is shown to followers the server would parse through and look for the tag and then replace it with the image. I am not really sure about this idea. Are there any other ways to do this. Is there any post-maker-like plugin available to do this? -
Not able to login after created account in django
I created login and signup pages in Django. I am not able to login using that username and password which I set up during sign up. although I am able to login using superuser username and password. I checked that data of signup is going in database. but while I am trying to login it is showing 'Please enter a correct username and password. Note that both fields may be case-sensitive.'. please help models.py- class userprofileinfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) phone = models.CharField(blank=False,max_length=10) hotel_manager = models.BooleanField() def __str__(self): # Built-in attribute of django.contrib.auth.models.User ! return self.user.username views.py- def HomePage(request): if request.user.is_authenticated: print('.................................-') print(request.user.email) return render(request,'homepage.html') else: print('not online..........................') return render(request,'homepage.html') return render(request,'homepage.html') def register(request): registered = False if request.method == 'POST': user_form = UserCreateForm(data=request.POST) profile_form = Formextends(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() registered = True return redirect('/login/') else: print(user_form.errors,profile_form.errors) else: user_form = UserCreateForm() profile_form = Formextends() return render(request,'signup.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) forms.py- class UserCreateForm(UserCreationForm): class Meta: fields = ("username","email","password1","password2") # ,"phone","hotel_manager") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" class Formextends(forms.ModelForm): class Meta(): model = userprofileinfo fields = ("phone","hotel_manager") settings.py- """ … -
Django Signals - creating folder on model create
I got a model where I would like to create a folder when a model is created: The model: class Drive(models.Model): user = models.ManyToManyField(User) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) path = models.CharField(max_length=150, editable=False, default='C:/Users/User/Desktop/Python/RavNet/media/storage/drives/{}'.format(str(id))) def save(self): super().save() I am trying to use signals, but I must admit this is my first ever attempt at making a signal not following a tutorial on point, and even after reading the documentation I am having a tough time. from django.db.models.signals import post_save from django.dispatch import receiver from .models import Drive import os @receiver(post_save, sender=Drive) def create_drive(sender, instance, created, **kwargs): if created: os.mkdir(Drive.path) Nothing happens when I create a new drive model via the django admin. I have tested out my code in the shell and using a placeholder path (C:/Users/User/Desktop/Python/RavNet/media/storage/drives/test) that I know works in the signal in a try to debug, and have gotten as far as realising I am having two issues. The first: When calling the Drive.path in the shell, I am getting the path: 'C:/Users/User/Desktop/Python/RavNet/media/storage/drives/<django.db.models.fields.UUIDField>' Instead of a path with the actual id as I hoped for. How do I solve this? Secondly, my signal isn't working. It's like it isn't getting called. What am I doing wrong? -
authenticate() returns None for User in system when using self.client.post()
So I'm currently working on redoing a project I did when I was new to Django. This time I'd like to ensure I'm using tests for practice and getting to know Django better. My issue is that I have a User that I know is in the system, as I have ogged in as them before, but when I run a test using self.client.post(), it returns None. I have triple checked spelling of username and password along with copy-paste the working strings in the func test and still nothing. Here is the test in question def test_login_authenticates_users(self): response = self.client.post('/', {'username' : 'TestUser', 'password' : 'password'}) self.assertRedirects(response, '/') # IDK why this line fails self.assertNotEqual(None, authenticate(username='Test.User', password='Usetheforceluke')) response = self.client.post('/', {'username' : 'Test.User', 'password' : 'Usetheforceluke'}) self.assertRedirects(response, '/home') Here is the functional test that works: from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import unittest class NewTeacher(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_teacher_adds_a_new_class(self): # The MCSP Department has a webpage used for all of the assignments # A teacher decides to go to the MSCP homepage to manage their classes self.browser.get('http://localhost:8000') # The title mentions MCSP in the title self.assertIn('MCSP', self.browser.title) # They then …