Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React-Native and Django Rest Framework problem
I have rode that is not necessary the token in mobile app, but i have in the same back end a web app, so if i disable the Token in Django, the web app will not work. -
djangobyexample book - jquery bookmarklet not working
I'm working through Django By Example and in one chapter a jQuery bookmarklet is built within a Django app so that a user can easily save jpg images from a website into their user profile area within the Django app. The tutorial does give exact instructions on what to do which I have followed and although I have managed to get the bookmarklet button to appear in my bookmarks bar in Chrome, nothing happens when I click it when browsing a webpage with jpg images. This is my local Django dashboard where the bookmarklet button is added to the bookmarks bar and this part works fine. dashboard and this is how it must look like when clicked on the bookmarklet, this is the part where nothing happens for me when I clicked on bookmarklet. (how to solve this?) result After I dragged Bookmark it! button to my bookmarks toolbar and opened HTTP site i saw that button doesn't work. In the developers tool/console i have an error Uncaught SyntaxError: Unexpected end of input and this info in console. console error These are the relevant js files https://github.com/davejonesbkk/bookmarks/blob/master/images/templates/bookmarklet_launcher.js https://github.com/davejonesbkk/bookmarks/blob/master/images/static/js/bookmarklet.js The JavaScript launcher is getting called through a Django template tag "include" … -
session meaning in programming and OS
can someone make it clear the idea of representing "session" in programming(django(cuze this question created in my mind in the progress of coding with django)) and OS concept. -
Bad request error when fetching files from AWS with django
I'm creating a website and I'm ready to put it into production. I have chosen to use AWS to host my static files and it's being a little weird about serving up files. I may just be doing things completely wrong. Here's my settings (I do have the correct keys and domain names but I edited them out for security) """ Django settings for lunaSite project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*******************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ # Default 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom "home", "blog", "reviews", "pages", "gallery", #Third Party "storages", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'lunaSite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates"], … -
Invalid block tag 'Static...' Django 3.1
I hope my message finds you well. I have this error: Invalid block tag on line 8: 'Static'/Style/style.css'', and I followed all the solutions I found here and it didn't work. enter image description here enter image description here enter image description here enter image description here -
Mocking for requests.Session.get
I have a new management command that grabs a csv from a url and saves it locally, then does some stuff with it afterward and deletes it. Here's where I retrieve it in my "download code": url = 'http://blahblahblah/output.csv' with requests.Session() as s: download = s.get(url) csv = open('temp_fallback.csv', 'wb') csv.write(download.content) # this works for url tests but not mock csv.close() It's working great for the real url, and things are peachy. I wrote a couple unit tests calling my management command and they're working, but now I'm adding a unit test to use a mocked response instead of hitting the live url. I'm trying it like so, where I'm hoping to substitute what happens for requests.Session.get): @patch('requests.Session.get') def test_mock_pass(self, mock_response): """ Test using mock response """ test_response = { 'content': 'bunch_of_content_here' 'status_code': 200, 'encoding': 'ISO-8859-1', 'reason': 'OK', 'elapsed': 'OK' } mock_response.return_value = test_response print("mock_response.return_value['content'] has: ", mock_response.return_value['content']) try: call_command('download_fallback_csv') except CommandError as e: self.fail("Failed download csv. {}".format(e)) But something is different between the response I get when calling the url vs the response I'm trying to mock: the tests work fine that use the url, but this mocked test fails during the csv.write with: "AttributeError: 'dict' object has no … -
Django filtering a model query with filter method
Why does this code: products_model = Product.objects.filter(sub_category__name__iexact=sub) supplier_filter = SupplierFilter(request.GET, queryset=products_model) products = supplier_filter.qs Give me this error: Field 'id' expected a number but got 'BYGGMAX'. Ive had trouble with this alot now. Can someone explain whats goin on. When i use the filter method its more complicated to filter the model, how so? Really interested in learning more on how this works. -
'django-admin' is not recognized as an internal or external command , pycharm
I don't know what is the problem but I downloaded Django and when I try to make a a Django project it creates this problem i tried several ways to make it work but nothing worked. 'django-admin' is not recognized as an internal or external command, operable program or batch file. -
Django: Getting the page an object is on
Let's say I have a class Foo. I want to know what page a particular instance of Foo will be on: eg: api.myapp.com/foos/?page=25. Given an object: Foo.objects.get(id=500), how can I determine what page my instance will be on? -
When don't we use "__all__" in ModelSerializer in Django Rest Framework
This is just my curiosity but I will be very happy if anyone answers my question. I am using Django Rest Framework but I'm a beginner. In serializers.py, I use ModelSerializer and "all" to fields attribute. This is an example. class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" And then, I just thought when don't we use "__all__" in serializers.py?? As long as we create models.py in advance, I think we usually use all fields in each Model. I would like you to teach me when we omit specific fields that come from each Model. Thank you. -
Passnig paramters via URL to template not working (404)
I have a link in a table which works with the following url path: f"""<a href="/link/{record.id}"><button class="btn">link</button></a>""" path(r'link/<int:pk>/', views.AssocView.as_view(), name="link") which works fine in combination. As soon as I want to pass another integer to the view, I get a 404: f"""<a href="/link/{record.id}/??test_id=12345/"><button class="btn">link</button></a>""" path(r"link/<int:pk>/(?P<test_id>[0-9]+)/(?P<test_2_id>[0-9]+)/", views.AssocView.as_view(), name="link"), AssocView: class AssocView(TemplateView): model = Product template_name = "app/product_all.html" def get_success_url(self): return redirect("product-all") def get_context_data(self, **kwargs): context = super(AssociateView, self).get_context_data(**kwargs) context["table"] = Product.objects.all() return context As soon as I add URL parameters like test_id I get a 404 - what am I missing here? Could it be because something is interfering? Middleware with response = self.get_response(request) or so? Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8001/link/35/?test_id=12345&test_2_id=221 -
Adding products and services to the cart from different apps
Hi Everyone, I am new to python and django and creating a fitness website. I have three apps, one is for the products, one for exercise plans and one for nutrition plans. I am able to add the products in the shopping cart. But wonder how can i do this for the exercise plan app and nutrition plan app. Can any one please suggest a simple way out please. -
Read Data from a PDF image python django
I have a PDF and its like images in pdf . and I want to read text from it . I tried to use PyPDF4 but it works only if pdf is in text form . in 2nd step I searched futher and found pytesseract . But Not found any link to convert PDF image to text. Any help would be highly appreciated. Thanks -
form.cleaned_data.get is not producing any data from my form when posted
form.cleaned_data.get is not getting the data I need from a dropdown from a database. I have a database table that filters by an 'area' selection then uses Ajax to load in the 'machine' list that corresponds to that 'area'. I then select the 'machine' I want from that loaded dropdown and submit. This goes to a new page based off of that selection. The problem I'm running into is in 'def post' machine_id = form.cleaned_data.get('machine') returns None so there is no information for the next loaded page. I have tested it with form.cleaned_data.get('area') and that returns the area selected from the dropdown. All values on the database are filled out. Thank you! Views.py: class MachineSelectView(TemplateView): template_name = 'machines/machine_select.html' def get(self, request): form = MachineSelectForm() args = {'form':form} return render(request, self.template_name, args) def load_machines(request): area_id = request.GET.get('area') MACHINE_CHOICES_UNSORTED = list(Tasks.objects.values_list('machine', flat=True).filter(area=area_id).exclude(machine__isnull=True)) MACHINE_CHOICES = list(dict.fromkeys(MACHINE_CHOICES_UNSORTED)) machine = MACHINE_CHOICES return render(request, 'machines/machine_dropdown_list_options.html', {'machines': machine}) def post(self, request): form = MachineSelectForm(request.POST) form.is_valid() machine_id = form.cleaned_data.get('machine') return redirect('/machines/%s/'%(machine_id)) Forms.py (These are text imputs that I've changed to dropdowns so the table can also be written to.) class MachineSelectForm(forms.ModelForm): area = forms.ChoiceField(choices=AREA_CHOICES) machine = forms.ChoiceField() class Meta: model = Tasks fields =( 'area', 'machine', ) def … -
How to display form validation error on HTML template in Django
How should I display the error messages on the HTML template, for Example I write a condition in the forms.py that if username already exist in the database, it should display the message on the HTML page, How should I do this? Following is my code: View.py from django.shortcuts import render,redirect from django.views.generic import View,TemplateView from .forms import Registration_Form from .models import User_Registration from django.contrib import messages # Create your views here. class MainPageView(TemplateView): template_name='main.html' class LoginView(TemplateView): template_name='login.html' def RegistrationView(request): form=Registration_Form() if request.method=='POST': form=Registration_Form(request.POST) if form.is_valid(): user_name=form.cleaned_data['username'] print(User_Registration.objects.filter(username=user_name)) form.save() return redirect('login_view') else: # messages.error(request,"Form is Invalid!") return redirect('registration_view') else: return render(request,'registration.html',{'form':form}) # template_name='registration.html' forms.py from django import forms from .models import User_Registration class Registration_Form(forms.ModelForm): class Meta: model=User_Registration fields=('company_name','username','password','email') widgets={ 'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}), 'username':forms.TextInput(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } def clean(self): user_name=self.cleaned_data['username'] if User_Registration.objects.filter(username=user_name).exists(): raise forms.ValidationError("Username Already Exist") -
Why The Image Is Not Being Rendered In Html Template Even Being Added To Static Files - Django?
I have tried using the image address in the normal HTML file, and it works great, but as I try to render the image with an HTML template with Django all it shows is just an image placeholder. And When I Inspect The Image Element It Has The Correct Src Attribute But Still It Doesn't Load. Here Is The Peace Of HTML <h1>{{article.title}}</h1> <div class="box"> <img src= "{{article.article_thumbnail_image_url}}" alt="Failed To Load Thumbnail Image"> </div> -
UnicodeDecodeError: skipped file doc1_UTF-16BE.html in
in the same error I had Ubuntu v20x Python 3.8.4 Django 3.0.2 / venv I wanted to internationalize my site but when calling django-admin makemessages --all I was getting this error. UnicodeDecodeError: skipped file doc1_UTF-16BE.html in ./venv/lib/python3.8/site-packages/weasyprint/tests/resources (reason: 'utf-8' codec can't decode byte 0xdc in position 339: invalid continuation byte) processing locale ru processing locale en Solutions. i changed encoding on the file doc1_UTF-16BE.htmlto doc1_UTF-8.html and coding to utf-8 please tell me, did I do the right thing? -
Issue with using query in Django
So what I'm trying to get is the following. User can choose 3 categories as seen in the code. Inside those categories they can add any number of plants. In my view: collection I want the user to see the following: COLLECTION Category_selected_by_user plant_1 plant_2 .... Category_selected_by_user2 What I get right now is: COLLECTION Category_selected_by_user Category_selected_by_user2 Category_selected_by_user3 so basically this is the code in models.py: class Plant_name(models.Model): """This class contains the plant name that is housed within a certain category""" """Links the plant to one of the chosen categories""" category = models.ForeignKey(Plant_category, on_delete=models.CASCADE, related_name='plant_names') # Placeholder for connection with a plant database API plant = models.CharField(max_length=50) """Return the plant input from the user""" def __str__(self): return self.plant this is the code in views.py: def collection(request): """The page that opens the collection of plants""" plant_categories = Plant_category.objects.all().order_by('category') context = { 'plant_categories': plant_categories, } return render(request, 'plntz_main/collection.html', context) And this is the code in collection.html: <ul> {% for category in plant_categories %} <h3>{{ category }}</h3> {% for name in plant_categories.plant_names.all %} <li>{{ name.plant }}</li> {% endfor %} {% empty %} <li>No category has been added yet.</li> {% endfor %} There must be something wrong with the data pulled for the plants inside … -
Error When Importing requirements.txt to project on Ubuntu Server(Digital Ocean)
I am currently trying to import my requirements.txt from my local django project to my django project on the my Ubuntu Server in digital ocean. Each time I run my pip command to install the packages in "requirements.txt" I get the below error. Command I am currently running: pip install -r requirements.txt ERROR: Could not find a version that satisfies the requirement asgiref==3.2.10 (from -r requirements.txt (line 1)) (from versions: 0.8, 0.9, 0.9.1, 0.10.0, 0.11.0, 0.11.1, 0.11.2, 0.12.0, 0.12.1, 0.13.0, 0.13.2, 0.13.3, 0.14.0, 1.0.0, 1.0.1, 1.1.0, 1.1.1, 1.1.2, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.6, 2.2.0, 2.3.0, 2.3.1, 2.3.2, 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.2.0, 3.2.1, 3.2.2, 3.2.3) ERROR: No matching distribution found for asgiref==3.2.10 (from -r requirements.txt (line 1)) -
Handling fetch api in javascript
I am working on a twitter like web page. In one single page I have a form to write a tweet and enough space down there to show the tweets. To asynchronously show them, I`m using fetch api to intercept the form and do this dynamically: document.querySelector('form').onsubmit = (event) => { event.preventDefault(); fetch("", { method: 'POST', body: JSON.stringify({ body: document.querySelector('#new_message').value }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { document.querySelector('#new_message').value = "" let div = document.createElement('div') div.innerHTML = ("<p>" + result.creation_date + "</p>" + "<a href='#'>" + result.username + "</a>" + ' said:' + '<br><br>' +"<div class='container'>" + "<p>" + result.body + "</p>" + "</div>"); div.style.cssText = "box-shadow: 0px 0px 2px; ; background-color:#F5F5F5; border-radius:10px; padding: 10px; margin: 5px;"; document.querySelector('#posts').append(div); }); } This dinamically shows the tweet when it`s posted without reloading the html. But the problem comes when I want to show the tweets them when a user actually reloads the page, I mean, via a get method: if request.method == "GET": if request.user.is_authenticated: posts = Posts.objects.all().order_by('-creation_date') return render(request, "network/index.html", { "posts":posts }) else: return render(request, "network/login.html") This makes me handle the tweet html from the javascript code and also with django templating … -
Can't reach Django server
I have begun working on a Django project and am testing whether Django is working. I have just started a project with django-admin startproject testing I haven't done anything to the project and have simply tried to run python manage.py runserver to make sure Django is working. Unfortunately when I try to access the server I simply get this: This site can’t be reached 127.0.0.1 refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED Could somebody tell me how I can actually access my Django project? I am using CS50 IDE on Google Chrome. -
creating a folder automatically for each user Django
So I am trying to create a folder automatically for each user in Django when they first sign up, where all their stuff gets saved in that folder. What I tried: #Creating a folder automatically for each user def folder_path(instance, filename): return "user_{0}/MyFolder/{1}".format(instance.user.id, filename) # Create your models here. class MyModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) user_folder = models.FileField(upload_to= folder_path, default= None) views.py myfolder = MyModel(user_folder= '/path/to/folder/') I also tried: #Creating a folder automatically for each user def folder_path(instance, filename): user = instance.user.username basename, file_extension = filename.split(".") new_filename = "%s-%s.%s" %(user, instance.id, file_extension) return "MyFolder/%s/%s" %(user, new_filename) # Create your models here. class MyModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) user_folder = models.FileField(upload_to= folder_path, default= None) views.py myfolder = MyModel(user_folder= '/path/to/folder/') I want to know why its not working, it does not give an error, but does not create a folder automatically. Thanks. -
How to expose Django Rest APIView fields to swagger?
I have something like this: class MyCustomView(APIView): serializer_class = serializers.MyCustomSerializer def post(self, request): #my custom logic here, working on multiple tables, etc But the serialization fields do not show up in swagger or default Django rest HTML view. How can I make it so it does? -
Getting this error after running 'manage startapp user'
Hey I have been working with django these days and it worked for me fine until now it is just giving me this error after running the command manage startapp user in my environment. It actually does create the app but also responded with this error. Traceback (most recent call last): File "E:\django\Amron\MyCafe\manage.py", line 22, in <module> main() File "E:\django\Amron\MyCafe\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\django\Amron\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "E:\django\Amron\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\django\Amron\env\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "E:\django\Amron\env\lib\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "E:\django\Amron\env\lib\site-packages\django\utils\asyncio.py", line 24, in inner return func(*args, **kwargs) File "E:\django\Amron\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "E:\django\Amron\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "E:\django\Amron\env\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable Also the server stops reloading after I save to any of the project files. Really need your help. Thanks!! -
django redirect user to the post after creating it
i want to redirect the user to the post after creating in with django forms in models.py class Text(models.Model): title = models.CharField(max_length=200, null=True) document = models.TextField(max_length=None, null=True) requirements = models.TextField(max_length=200, null=True) date_created = models.DateField(auto_now_add=True, null=True) deadline = models.DateField(null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.title in my view.py def text(request, pk): form = TextForm() if request.method == "POST": form = TextForm(request.POST) if form.is_valid(): text = form.save() text = Text.objects.get(id=pk) return redirect('text') text = Text.objects.get(id=pk) context = {'form': form, 'text': text} return render(request, 'main/text.html', context) in my forms.py class TextForm(ModelForm): class Meta: model = Text fields = ['title','document','requirements','deadline'] widgets = { 'title' : forms.TextInput(attrs={'placeholder':'Title','class':'form-control m-2 mb-4 pb-2'}), 'deadline' : forms.DateInput(attrs={'placeholder':'Deadline','type':'date','class':'form-control m-2 pt-2', 'id':'opendate'}), 'requirements' : forms.Textarea(attrs={'placeholder':ps_note,'class':'form-control col m-2','rows':'3'}), 'document' : forms.Textarea(attrs={'placeholder':ps_text,'class':'form-control'}), } i had to add this to be able to the question gets accepted