Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
right way to deploy a django-rq worker
maybe it's a silly question, but I didn't found much while googling around. So I'm on the way to transform my development environment to a deploy environment. I connected django and nginx using uwsgi, put both in docker containers... so far no problem. But I'm using django-rq, so I need a Worker process. In all these nice examples about deploying django I didn't found much about deploying django-rq. All I found was "create a docker container and use the manage.py " like this: CMD python manage.py rqworker [queue1] [queue2] Really? Should I just start the worker like this? I think manage.py is just for testing!? -
Django forms 'str' object has no attribute 'get'
the error is with the following: registerform = UserCreationForm(request.POST) Error here!if registerform.is_valid(): class UserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': ("The two password fields didn't match."), "email_missing": ("Please enter email."), "name_missing": ("Please enter name."), } password1 = forms.CharField(label=("Password"), widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) password2 = forms.CharField(label=("Password confirmation"), widget=forms.PasswordInput(attrs={'placeholder': 'Repeat Password'}), help_text=("Enter the same password as above, for verification.")) first_name = forms.CharField(label=("First Name"), widget=forms.TextInput(attrs={'placeholder': 'First name'})) last_name = forms.CharField(label=("Last Name"), widget=forms.TextInput(attrs={'placeholder': 'Last name'})) username = forms.CharField(label=("Username"), widget=forms.TextInput(attrs={'placeholder': 'Username'})) email = forms.EmailField(label=("Email"), widget=forms.TextInput(attrs={'placeholder': 'Email'}),help_text=('Security is of upmost importance for Glocal. We require email address verification in order to prevent trolling and fake accounts. Please enter your email address below and click on "verify" in the email that we will send you, in order to activate your account.')) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) # remove username self.fields.pop('username') class Meta: model = User fields = ("username", "email",) field_order = ['first_name', 'last_name', 'password1', 'password2', 'email'] def clean(self): cleaned_data = super(UserCreationForm, self).clean() password1 = cleaned_data["password1"] password2 = cleaned_data["password2"] email = cleaned_data["email"] username = cleaned_data['first_name'] + "." + cleaned_data['last_name'] first_name = cleaned_data['first_name'] last_name = cleaned_data['last_name'] if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) if not email: raise forms.ValidationError( self.error_messages['email_missing'], code="email_missing") if not first_name or not … -
How to loop thru JSON list and save data in Django
I am trying loop thru JSON list data and save into the variable 'nfts'. Exception Value: string indices must be integers Traceback: nft_data_id = item['nfts'][item]['nft_data_id'], ... JSON response: {"result":{"page_count":3041,"nfts":[{"nft_id":"#-#-#-#","nft_data_id":"#-#-#-#", ... views.py Code: def market_data(request): URL = '...' response = requests.get(URL).json() nfts = response['result'] for item in nfts: nft_data = NFT_attributes( nft_data_id = item['nfts'][item]['nft_data_id'], ... -
How can I save a user's selected choice on refresh Django
I'm trying to save a user's choice which but on refresh or navigating to another page, the submission had been removed. How can I save the user's submission so it won't reset/change unless the user chooses to? I.e. if someone chooses AUD, that choice will remain submitted on refresh/navigation/login/logout. FORM class CurrencyForm(forms.Form): currency = forms.ChoiceField(initial=('USD', 'USD'), choices=['USD', 'AUD', 'GBP' 'CAD'], label='Choose Currency:') VIEW class MyDashboardView(TemplateView): template_name = 'coinprices/my-dashboard.html' def get(self, request, **kwargs): form_c = CurrencyForm(prefix='form_c') return render(request, self.template_name, { 'form_c': form_c, }) def post(self, request): currency = 'USD' form_c = CurrencyForm(request.POST, prefix='form_c') if request.method == 'POST': if form_c.is_valid(): currency = form_c.cleaned_data['currency'] rates = {'USD': 1.0, 'AUD': 1.321, 'GBP': 0.764, 'CAD': 1.249} deposit = 10000 / rates[currency] context = { 'deposit': deposit } return render(request, 'coinprices/my-dashboard.html', context) HTML <span> <form method="post"> {% csrf_token %} {{ form_c.as_p }} <button class="btn btn-outline-success btn-sm">Submit</button> </form> </span> <span class="text-xl">${{ deposit }}</span> -
Why does django continues naming my app as the previous name?
thanks for reading. When I run "py manage.py makemigrations" I get the following message: "ModuleNotFoundError: No module named 'transformaTe'" This is the apps.py code: from django.apps import AppConfig class TransformateConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'transformate' The name is updated there and in my INSTALLED_APPS: INSTALLED_APPS = [ 'transformate', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Where else should I look to change the name of the app? This is the simplified structure of the app: \my-app \transformate admin.py apps.py models.py urls.py views.py \my-app asgi.py settigs.py urls.py wsgi.py All this happened when I rename the app because I had a problem creating a table called transformaTe_myuser so I though all could be caused by the capitalized letter use. Is there a better way of renaming an existing app in Django? I followed this steps, except for the migration part (Because I deleted the db and the migrations folder): https://odwyer.software/blog/how-to-rename-an-existing-django-application Thanks for your help. -
Secure webapp with Django and React
I'm experimenting with these 2 technologies to make a secure web app [Currently learning React (60%) and Django (<50%). This is intended to be like a medical database, so doctors and nurses enters their patients' information. They need to login obviously. I wanted to implement React-based UI (And not using the classic method to create views from django), so I've found many tutorials just like this one: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react It basically turns Django into a restAPI, and then the React frontend uses axios to retrieve data from the endpoint. Sounds not bad at all (comparing to the native method of rendering data in a webpage from Django), but the problem is that I have no idea on how to make this secure, you know, Django provides an auth system, which is pretty good and secure, I have to say, but in a project with this structure, the auth needs to be done in React, so there many questions appear: To start with, is it a good idea to make a project of this structure? (If no, then what could be a good one) If it's a yes, how can I protect the API so only logged in users can interact with … -
Django: How to display the voting options that correspond to the logged-in user
Working through my first Django project. I'm trying to display the Result model record that has been pre-created specifically for the logged-in user and wherein that user/decision-maker can see the decision that they've been assigned to vote on, as well as the corresponding choices from which they must select one. The code further below "works"---but there are 2 problems related to the forms.py line: result_instance = Result.objects.create(decision_id=22) First problem is that I'm inadvertently creating a new record in the model Result by using the property "create"---when I just want to update an existing Result record (i.e., the logged-in user's record containing their assigned decision/choices, which in turn are foreign-keyed from the model Decision). Second problem is that the option, "decision_id"=22, obviously has a static value and needs to be changed to dynamically refer to the decision that has been pre-assigned to the logged-in user in their "personal" Result record. I think I need to pass the logged user's assigned decision from views.py to forms.py---but not sure how to do that. Hoping there is a solution that fixes both issues. Thanks! models.py class Decision(models.Model): custom_user = models.ForeignKey(CustomUser, default=None, null=True, on_delete=models.SET_NULL) summary = models.CharField(default="", verbose_name="Decision") option1 = models.CharField(default="") option2 = models.CharField(default="") class … -
How to filter products by category in Django?
There is a product page. I need to display only those products that belong to the same category.I tried to use get_queryset(), but got an error Unsupported lookup 'slug' for SlugField or join on the field not permitted.. How can I solve this? My code: model.py class Category(models.Model): name = models.CharField(max_length=50, verbose_name="Ім'я категорії") slug = models.SlugField(unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("category_detail",kwargs={'slug': self.slug}) class Product(models.Model): category = models.ForeignKey(Category, verbose_name='Категорія', on_delete=models.CASCADE) title = models.CharField(max_length=150, verbose_name='Ім\'я продукта') slug = models.SlugField(unique=True) product_code = models.IntegerField(default='0003001', verbose_name='Код продукту', blank=True, null=False) img = models.ImageField(verbose_name='Фотокартка') qty_product = models.IntegerField(default=1, verbose_name='Кількість товару') price = models.DecimalField(max_digits=5, decimal_places=0, verbose_name='Ціна') description = models.CharField(max_length=3000, verbose_name='Опис') def __str__(self): return self.title def get_absolute_url(self): return reverse('product_detail', kwargs={'slug': self.slug}) views.py class CategoryDetailView(DetailView): model = Category queryset = Category.objects.all() template_name = "mainapp/product-category.html" slug_url_kwarg = 'slug' context_object_name = 'products' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) category = self.get_object() context['categories'] = self.model.objects.all() context['products'] = Product.objects.all() context['category_products'] = category.product_set.all() return context def get_queryset(self): return Product.objects.filter(slug__slug=self.kwargs['slug']) -
Is there any way of solving a django static problem
directory: website static website images balloons.gif error: GET /static/website/images/balloons.gif HTTP/1.1" 404 1840 -
Storing datetime objects in django session?
I am storing a nested dictionary in a Django session variable. One of these fields that is pretty important is a DateTimeField. emp_list = [] employees = Employee.objects.filter(**filter here) for employee in employees: context = {} created = employee.created.strftime( "%Y-%m-%d %H:%M:%S" ) context["created"] = datetime.strptime(created, "%Y-%m-%d %H:%M" ) emp_list.append(employee) if I return a simple emp_list all works fine... return emp_list But if I return a... return request.session["emp_list"] = emp_list I get the common error TypeError: Object of type datetime is not JSON serializable So if I just want to just return the emp_list everything is fine, but trying to store inside of a session, I get the error. Is there any way around this to store datetimes inside of the sessions framework? Thanks in advance! -
How to run python commands in a new shell
I am learning django. I am stuck with this problem. So basically, I have designed a form (template) in HTML that takes a text file as input and generates a voiceover of that text file. I am using espeak for it in the backend. So, when a user uploads a file, this command - espeak -ven+m1 -f", uploaded_file.name where uploaded_file.name is the name of the uploaded file should run in a new terminal window. In order to achieve this, I wrote a print statement like this- print("espeak -ven+m1 -f", uploaded_file.name) in views.py but the problem with this is that it runs in the same shell but I want this print statement to execute in a different shell. So basically, my problem boils down to, I want to run a print command in a new shell but I am unable to figure out how. As I already said I am new to django and some help will be appreciated. -
HTML5 Audio Not Working on Mobile Browsers
I have a website that currently uses React and Django to serve all types of media - Video, Images, and Audio. I know its not as efficient as it should be with regards to delivery and I haven't implemented any streams, however, lets ignore that and get to the issue: My audio, with custom controls, doesn't play when on iOS. I haven't tested on any android devices but it works perfectly on Chrome, Firefox, Safari on MacOS. I know there's been some older topics and questions with iOS and the way certain media plays but they don't seem directly applicable or truly helpful with this particular situation. Heres the code for my audio component, I have a feeling its to do with the custom controls more than anything so I'll include that as well but as far as the HTML goes, I haven't found a logical issue yet. All of the following questionable variables here work with my other media components so I'm not sure the syntax is the issue exactly. import React, { useState, useEffect, useRef } from 'react' import AudioSpectrum from 'react-audio-spectrum'; export default function AudioBit({id, Media, Company, Cover}) { const [playing, setPlaying] = useState(false) const [mute, setMute] … -
Backend web developer career guide
I want to make a career as a backend web developer. I learned Python for my minor project and learned Django for my major project when I was in college. Now I am thinking of making a career as a backend web developer but I don't what else to learn. I have created a few projects like a library management system and currently working on a blog web application and I have little knowledge of HTML, CSS, and JS because I used bootstrap and Django form when I was creating Django apps. If anyone can tell me what else to learn or what to do to make a career in backend web development. Sorry for this question as I don't have anyone in real life to ask this question and my college teachers have no knowledge in this area. Thanks in advance and any advice will be helpful in making decisions for my career. -
How to make the div wide enough when I scroll the screen?
How should I adjust the CSS for the div class="breadcrumbs", if the table is wider than a screen and then background is not till the end. screenshot, where is the problem I would like the dark blue bar to be till the end of the horizontal scroll (not just width of the screen). Now it is like this: div.breadcrumbs { background: var(--breadcrumbs-bg); padding: 10px 40px; border: none; color: var(--breadcrumbs-fg); text-align: left; width:100%; margin:0; } -
Code from bootstrap documentation doesn't work
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse" id="navbarTogglerDemo03"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> I copy pasted this code from bootstrap to make a responsive navbar that turns into a collapsed menu with a button. I copy pasted into the body tag of an empty template in django. bootstrap is loaded, I get everything, even the button when the screen size is small enough. but when I click on the button the menu doesn't expand, the button does nothing. -
why Django admin short_description function not working?
I am trying to make some changes in my django admin panel such as want to show "title" instead of "blog_tile" but I am not understanding why changes not reflecting. class BlogAdmin(admin.ModelAdmin): readonly_fields = ['blog_publish_time', 'blog_update_time'] list_display = ['blog_title', 'blog_status', 'blog_publish_time', 'blog_update_time'] def rename_blog_title(self, obj): return obj.blog_title[:10] rename_blog_title.short_description = "title" admin.site.register(Blog, BlogAdmin) where I am doing mistake? -
How to get the path to your saved image in django
I created a form model using the code below class TrainImageForm(forms.ModelForm): class Meta: model = TrainImage fields = ( 'image', ) def customSave(self): lv = self.save(commit=False) lv.save() return lv.image.name And this is how I saved uploaded image. But any time I try to retrieve the image, I get a "FileNotFoundError" def testnetwork(request): if request.method == "POST": form = TrainImageForm(data=request.POST, files=request.FILES) if form.is_valid(): filename = str(form.customSave()) img_array = imageio.imread("media/train_images/" + filename,as_gray=True) img_data = 255.0 - img_array.reshape(784) img_data = (img_data/255.0 * 0.99) + 0.01 global n output = n.query(img_data) label = numpy.argmax(output) But when I input the path of the file manually (in the imageio.imread), it works without any error. Please how do I go about this -
Heroku Deployment Failed for a Django App while deploying current state of Git branch [duplicate]
I have synced the heroku app with my GitHub Source code so far it only did one successful build and the App gives an Application Error when I open the app. I have followed all the steps, added procfile added requirements.txt added runtime.txt added URLs in the ALLOWED_HOSTS = [''] in settings.py my project structure is as the following --Project Root --DjangoBase --API --Files --Files The error I get is the following -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt Traceback (most recent call last): File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> r = f.read().strip() File "/app/.heroku/python/lib/python3.10/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input ! Requested runtime (��python-3.10.2) is not available for this stack (heroku-20). ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed -
Django filter models with a list of related items
For a simple Book model with a related Tag table, I'd like to filter out Books that have a list of tags: class Book(models.Model): name = models.Textfield() class Tag(models.Model): value = models.Textfield() book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="tags") If I want to search all Books that have a both a "red" Tag and a "blue" tag, I can't simply run: Book.objects.filter(Q(tags__value="red") & Q(tags__value="blue")) because that tries to find an impossible Tag that has both the value "blue" and "red". Note that OR-ing the conditions is not correct either since I'm looking for Books that have both a "red" and a "blue" tag; a Book with just one or the other should not be returned. -
Migrate command error in Django with djongo
I am getting error while using the migrate command in djongo with Django. The error is djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: CREATE TABLE "django_content_type" ("id" int NOT NULL PRIMARY KEY AUTOINCREMENT, "name" string NOT NULL, "app_label" string NOT NULL, "model" string NOT NULL) Params: None Version: 1.3.6 -
Add a FileField path in django
I have a map in my app and im trying to 'paint' some territories with kml files. I can get the outlined version if i hardcode the absolute path but since i have multiple kmls im trying to do it with a for loop with a field.kml.path (kml being the Filefield in my model) as per django instructions but it doesnt work . Any idea how to fix that ? view : def map(request): field_list = models.Field.objects.all() context = { "title": "Map", "field_list": field_list, } template = 'agriculture/map.html' return render(request, template, context) My original map.html var polygon = omnivore.kml("{% static '../media/kml/Arnissa_cherry.kml' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); New version that doesnt work: {% for field in field_list %} $(".search_area").append(new Option("{{field.friendly_name}}")); //friendly name var polygon = omnivore.kml("{% static '{{field.kml.path}}' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); {% endfor %} -
Django GinIndex on a specific JSON key
There is a solution how to create an index for search against Django JSONField operations = [ migrations.RunSQL("CREATE INDEX JsonFieldNameIndex ON contracts_clause((custom_indexed_content->'name'));"), ] However, if I try to use Django GinIndex, that does not affect the search speed class Clause(CustomModel): title = models.CharField(max_length=255) not_indexed_content = models.JSONField(blank=True, null=True) manually_indexed_content = models.JSONField(blank=True, null=True) db_indexed_content = models.JSONField(blank=True, null=True, db_index=True) gin_indexed_content = models.JSONField(blank=True, null=True) class Meta: indexes = [GinIndex(fields=['gin_indexed_content'])] Django debug toolbar queries timeline Is there a way to create an index for a specific JSON field using Django ORM syntax, rather than using raw SQL? -
Can't edit django project
I installed django and python multiple times. Every time when i run django-admin startproject projectname it creates a project which is not responding. Anything I do just doesn't apply to website. It's in views.py or any of urls.py. I am using command: python3 manage.py runserver. It doesn't work with pipenv either. Problem is not in code I put in project because I worked by tutorial. -
Django webscraping JSONDecodeError
I'm trying to scrape data and it works fine if the {fplid} for url is like 30 for example. How do I fix this method, so it gets the user input and gets the data from the url without a decode error. This is the traceback ''' C:\Users\krish\OneDrive\Desktop\FPLHangout\scrape\views.py, line 31, in home data = get_html_content(fplid) … Local vars C:\Users\krish\OneDrive\Desktop\FPLHangout\scrape\views.py, line 9, in get_html_content managerdata = json.loads(r.text) def get_html_content(fplid): url = 'https://fantasy.premierleague.com/api/entry/{fplid}/event/30/picks/' r = requests.get(url) managerdata = json.loads(r.text) bootstrap = 'https://fantasy.premierleague.com/api/bootstrap-static/' bootstrapdata = requests.get(bootstrap) bootstrapjson = json.loads(bootstrapdata.text) for pick in managerdata['picks']: pick = (pick['element']) #correct id location = 0 for player in bootstrapjson['elements']: if player.get('id') == pick: break location += 1 #position = (pick['position']) firstname = bootstrapjson['elements'][location]['first_name'] secondname = bootstrapjson['elements'][location]['second_name'] return firstname + " " + secondname def home(request): if 'fplid' in request.GET: # fplid = request.GET.get('fplid') data = get_html_content(fplid) return render(request, 'scrape/home.html', {'fpldata': data}) return render(request, 'scrape/home.html') -
Django get models by model name
In Django I know that there is one and only one model with name foo, but I don't know the app that this model is registered with! How can I get the model with only model_name?