Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way in Django to create and populate a column to the database with a string's length value?
I have a class/model in my models.py that can receive a textField. I want to add a column in my database that corresponds to the length of this textField. What is the best way of doing that? -
How do I make the edit and cancel link appear only if its the logged in user is the one who created the object? Django
The edit and delete function works fine but I cant make it specific that it only appears to the person that created that object? {% for job in jobs %} <tr> <td>{{ job.job }}</td> <td>{{ job.location }}</td> <td><a href="/jobs/{{ job.id }}/view">View</a> <a href="/main">Add</a> <a href="/jobs/{{ job.id }}/edit">Edit</a> <a href="/jobs/{{ job.id }}/delete">Cancel</a> </td> </tr> {% endfor %} -
Django Form submit in foor loop
I tried many things, now I have to ask you. The user has multiple Buttons. My goal is to count every click on a specific button. The specific button is the Field (Field Model). How the models look: class Field(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) description = models.CharField(max_length=255) title = models.CharField(max_length=255) url = models.CharField(max_length=255) ... class Hits(models.Model): field = models.OneToOneField( Field, default=None, null=True, on_delete=models.CASCADE) hits = models.IntegerField(default=0) \\HTML Template {% for i in request.user.field_set.all %} {% if request.user == i.user %} <form method="POST"> {{ hits_form }} {% csrf_token %} <div class="full-w-button"> <p class="preview-description">{{ i.description }}</p> <button onClick="javascript:window.open('{{i.url}}', '_blank');" type="submit" class="link-box"> <p class="text-bold-medium">{{ i.title }}</p> </button> </div> </form> {% endif %} {%endfor %} The hits_form is supposted to be a hidden input for counting the click. My problems are: -when user clicks button, counter for specific Field += 1 -having a form for each Field, currently one form is probably saving the counter for all fields, so i am looping with forms but every form is the same \\views.py In the Views File, the important parts is the hits_form, the other form works fine if request.method == 'POST': hits_form = #here i am stuck form = FieldForm(request.POST, instance=Field(user=request.user)) … -
How to force graphs to stay inside a bootstrap container/card (html, css, plotly, bootstrap, django)?
I'm making a django-based web app that has bootstrap cards with some graphs inside of them. I'm using bootstrap so both the graphs and the cards are responsive; however at some screen sizes, the graphs extend beyond the size of the cards. Is there a way to force everything in a card (or some other container) to say inside the container? Partial html code. Can post the graph code if helpful - it is written in python + plotly. I'm not sure if the problem is with the graphing or with the html/script. I'm also working on posting an image, but the upload is failing :). <div class="container"> <h2 class="pb-2 border-bottom mt-4">Scores for {{ user.username }} </h2> <div class="row mb-4 mt-4"> <div class="col-lg-6"> <div class="card"> <div class="card-body"> <h5 class="card-titler">Result</h5> <p style="color:gray;"> {{last_test_date | safe}}</p> {{score | safe}} <!-- <div class="chart" id="bargraph1", style="height: 150px">--> <div class="chart" id="bargraph1"> <script> var graphs = {{plot1 | safe}} </script> </div> <a href="#" class="card-link text-end p-2">Learn More</a> </div> </div> <div class="col-lg-6"> <div class="card"> <div class="card-body"> <h5 class="card-title">Results Over Time</h5> <br> <!--<div class="chart" id="bargraph2", style="height: 225px">--> <div class="chart" id="bargraph2"> <script> var graphs = {{plot2 | safe}} </script> </div> </div> </div> </div> </div> -
Handle Django MIgrations
I'm working on a Django project with Postgres database using Docker. We are facing some issues in with our migrations, I did not add Django migrations inside .gitignore because I want everyone to have the same database fields and same migrations as well, but every time when someone changes the models or add a new model and push the code with migrations so migrations re not applying in our database as it should be, every time we faced this issue that sometimes ABC key doesn't exist or ABC table doesn't exist, so how can I overcome from it. Dockerfile: EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts RUN pip install --upgrade pip COPY requirements.txt /app/ RUN pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts USER app CMD ["/scripts/run.sh"] run.sh #!/bin/sh set -e ls -la /vol/ ls -la /vol/web whoami python manage.py collectstatic --noinput python manage.py makemigrations python manage.py migrate uwsgi --socket :9000 --workers 4 --master --enable-threads --module myApp.wsgi docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: … -
TypeError: unsupported type for timedelta seconds component: NoneType
File "C:\Users\rafae\Projects\Django and React Tuto\music_controller\spotify\util.py", line 22, in update_or_create_user_tokens expires_in = datetime.now() + timedelta(seconds=expires_in) TypeError: unsupported type for timedelta seconds component: NoneType Hey guys, getting this error when redirecting from spotify api and going back to my local server. Above is the error message and the location. Below is the code inside models.py, determing the value of "expires_in": class SpotifyToken(models.Model): ... expires_in = models.DateTimeField() ... Thanks in advance! -
convert 'django.contrib.gis.geos.point.Point' object into coordinates in Django
I heve a model Location where I have such fields as: location_id, city, address, point. I using 'django.contrib.gis.geos.point.Point'. In my database in a column named point HEX point representation is laying. It is looks like: 0101000020E6100000644ADA43B1FF374026EE6767872E2A40. It is a fake location. The question is: how can I I get just coordinates like: (23.9987986 13.0908768)???? Now I can get only Point object like SRID=4326;POINT (23.9987986 13.0908768) using for cycle. Can any one help??? -
Run telegram bot with uWSGI
I have a Django app running on nginx+uWSGI. Inside my Django app there is a Telegram bot (python-telegram-bot). It is a Long Polling bot, not a Webhook one. Django part is completely ok, I managed to configure uWSGI and nginx. Bot is ok as well, while I run it with: python bot.py But I want to run it with uWSGI (emperor mode) and I can't find any tutorials on how to make it work. Here is my bot code (a small part. It actually has a dozen of commands and uses Django models): import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") import django django.setup() from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import ( Updater, CommandHandler, CallbackContext, PicklePersistence, ) from app.secrets import tg_token def start(update: Update, context: CallbackContext) -> None: update.message.reply_text('hi') def main() -> None: persistence = PicklePersistence( filename='arbitrarycallbackdatabot.pickle', store_callback_data=True) # Create the Updater and pass it your bot's token. updater = Updater(tg_token, persistence=persistence, arbitrary_callback_data=True) updater.dispatcher.add_handler(CommandHandler('start', start)) # Start the Bot updater.start_polling() # Run updater.idle() if __name__ == '__main__': main() Any ideas on how to configure uWSGI to run my Django app and bot.py at the same time? -
I cant update an object in Django?
Ive created a Django application where you add jobs and Im fully able to add new jobs but I can update them for some reason? The update feature isn't working and I don't know why?? <form action='/update_job/{{job.id}}' method="POST"> <ul> {% for message in messages %} <li>{{message}}</li> {% endfor %} </ul> {% csrf_token %} Title: <input type='text' value="{{job.job}}" name='job'> Description: <input type='text' value="{{job.description}}" name='description'> Location: <input type='text' value="{{job.location}}" name='location'> <input type='submit'> </form> def update_job(request, job_id): errors = Job.objects.job_validator(request.POST, job_id) if job.creator.id != request.session['user_id']: messages.error(request, "This isn't yours to edit!") if len(errors): for key, value in errors.items(): messages.error(request, value) return redirect(f'/edit_job/{job_id}') job = Job.objects.get(id=job_id) job.job = request.POST['job'] job.description = request.POST['description'] job.location = request.POST['location'] job.save() return redirect('/main') Page not found (404) Request Method: POST Request URL: http://localhost:8000/update_job/2 Using the URLconf defined in Python_Exam.urls, Django tried these URL patterns, in this order: register login logout main job_link job/create jobs/<int:job_id>/view jobs/<int:job_id>/delete jobs/<int:job_id>/edit jobs/<int:job_id>/update_job The current path, update_job/2, didn't match any of these. -
How to remove duplicates from the database table, alter the model with unique=True and makemigrations?
class CommonInfo(models.Model): name = models.CharField(max_length = 100) age = models.PositiveIntegerField() class Meta: abstract=True ordering=['name'] class Student(CommonInfo): home_group =models.CharField(max_length=5) class Meta(CommonInfo.Meta): db_table='student_info' Blockquote I have a similar database model with existing data. I want to add a uique=True on the field name. Is there any way I could remove the existing duplicate data before I alter the field name as unique? -
Exporting field data in many to many relationships using django-input-output only shows primary key
I am trying to export the data from my database from the django admin page using the django-import-export package. When I export a model, I also want to show the data in a particular field for every object in a many to many relationship. It looks something like this: models.py class Item(models.Model): part_number = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=250, blank=True) def __str__(self): return self.part_number class Bin(models.Model): name = models.CharField(max_length=50, unique=True) items = models.ManyToManyField(Item, blank=True) def __str__(self): return self.name admin.py class ItemResource(ModelResource): class Meta: model = Item fields = ('part_number', 'description') @admin.register(Item) class ItemAdmin(ImportExportModelAdmin): save_as = True resource_class = ItemResource class BinResource(ModelResource): class Meta: model = Bin fields = ('name', 'item__part_number') @admin.register(Item) class ItemAdmin(ImportExportModelAdmin): save_as = True resource_class = BinResource The way I would expect this to work is that if I export Items, I will get a document that has all the part numbers in one column and the description in another. This works just fine. However, I would also expect that when I export Bins, one column would show all the names, and another column would display a list of all the part numbers of the items that are associated with the bin. What I actually get is a … -
TypeError: __init__() got an unexpected keyword argument 'bot_id' when i pass a variable from views to form
I need to pass a variable from views to form to limit the selection of objects in the ModelChoiceField depending on the bot_id Tell me how to do it right, in the current implementation, the code gives an error TypeError: init() got an unexpected keyword argument 'bot_id'. My code: views.py def edit_question(request, bot_id, question_id): bot = get_object_or_404(SettingsBot, id=bot_id) question = get_object_or_404(Questions, id=question_id) QuestionInlineFormSet = inlineformset_factory(Questions, RelationQuestion, exclude=('bot',), fk_name='base', form=SubQuestionForm) if request.method == "POST": form = QuestionsForm(data=request.POST, instance=question) formset = QuestionInlineFormSet(request.POST, request.FILES, bot_id=bot_id, instance=question) if formset.is_valid(): formset.save() return redirect(question.get_absolute_url()) else: form = QuestionsForm(instance=question) formset = QuestionInlineFormSet(bot_id=bot_id, instance=question) return render(request, 'FAQ/edit_questions.html', {'question': question, 'bot': bot, 'form': form, 'formset': formset}) forms.py class SubQuestionForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.bot_id = kwargs.pop('bot_id', None) super(SubQuestionForm, self).__init__(*args, **kwargs) self.fields['sub'] = forms.ModelChoiceField(Questions.objects.filter(bot=self.bot_id)) class Meta: model = RelationQuestion fields = ['sub'] models.py class Questions(models.Model): question = models.CharField(max_length=30, verbose_name="Вопрос") answer = models.TextField(default="No text", verbose_name="Ответ на вопрос") id = models.BigAutoField(primary_key=True) bot = models.ForeignKey("SettingsBot", related_name="Бот", on_delete=models.CASCADE, verbose_name="Бот") general = models.BooleanField(default=False, verbose_name="Отображать на стартовой странице") created = models.DateTimeField(auto_now_add=True, verbose_name="Создан") updated = models.DateTimeField(auto_now=True, db_index=True, verbose_name="Изменен") class Meta: verbose_name = "Вопрос" verbose_name_plural = "Вопросы" ordering = ('-id',) def get_absolute_url(self): return reverse('FAQ:edit_questions', kwargs={'question_id': str(self.id), 'bot_id': str(self.bot)}) def __str__(self): return self.question def data(self): return [self.question, self.answer, self.id, … -
Automatically submit a value on click to a form using Javascript/Java in a Django form
I am working on a web app using Django/Python/Javascript/Java. The focal point is a map of the USA. A user should be able to click on a region and the value of that region should automatically query a database and return certain information. Currently, my code produces a const called regionName and the value of regionName is passed automatically as input to the search bar; however, from here a user needs to manually click the 'search' button to submit the form and query the database. As below: onRegionClick: function(event, code){ console.log('event', event, 'code', code); const regionName = map.getRegionName(code); console.log('regionName', regionName); $("#selection").val(regionName); }, }); What I am trying to do with the code is to automatically submit the value of regionName after it is passed to the search bar. Efforts thus far have been similar to the code below. $("#selection") - the form $("#q") - the name of the button $("#selection").on('change', function(){ if ($("#selection").val() === regionName ) { $("#q").click(); } }); This is not producing any errors, but it's not producing any results either. I've tried various substitutes along similar lines such as: .on('input'.. instead of 'change' .submit() instead of .click() I've also have an .autocomplete() method I'm using. I'm not … -
get() returned more than one Product -- it returned 2 Django Rest Framework
DRF returning this: get() returned more than one Product -- it returned 2!, when im trying to get objects from my DB by PK Serializers class ProductSerializer(serializers.ModelSerializer): # cat_id = serializers.SlugRelatedField(slug_field='cat_id', read_only=True) class Meta: model = Product fields = ('name', 'description', 'cat_id', 'use', 'diametr', 'len', 'color', 'photo') Views class CategoryProductView(APIView): def get(self, request, pk): product = Product.objects.get(cat_id=pk) serializer = ProductSerializer(product) return Response(serializer.data) Urls path('api/categorylist/<int:pk>', CategoryProductView.as_view()) -
Django serialize One to One
I have a model named client and it has a two foreign key relationships. One is to the region they are from and the other is to an agent. I am trying to serialize all clients. Using, use_natural_foreign_keys=True is giving me the region name. How would I get the agent name without using DRF? Model: class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Client(models.Model): name = models.CharField(max_length=20, default="") agent = models.ForeignKey("Agent", on_delete=models.CASCADE) region = models.ForeignKey("Region", on_delete=models.CASCADE) View: class ClientLog(View): page_limit = 100 def get_paginated_context(self, queryset, page, limit): if not page: page = 1 if limit: self.page_limit = limit paginator = Paginator(queryset, self.page_limit) page_obj = paginator.get_page(page) serialized_page = serialize("json", page_obj.object_list, use_natural_foreign_keys=True) serialized_page = [{**obj["fields"], **{"pk": obj["pk"]}} for obj in json.loads(serialized_page)] return { "data": serialized_page, "pagination": { "page": page, "limit": limit, "has_next": page_obj.has_next(), "has_prev": page_obj.has_previous(), "total": queryset.count() } } def get(self, request, *args, **kwargs): page = request.GET.get('page') limit = request.GET.get('limit') queryset = Client.objects.all() to_return = self.get_paginated_context(queryset, page, limit) return JsonResponse(to_return, status = 200) -
ModuleNotFoundError: No module named 'blog.models'
I was experimenting with my database and made some errors and messed up the whole database. I deleted the database and created a new blank db. When I go to makemigrations i get the error ModuleNotFoundError: No module named 'blog.models' refering to the line in my views.py where i import my models. I tried creating a a new project and moving the files over same error. Everything was working fine before I messed up the DB. Sorry for not a ton of information I dont know what the issue really is -
Django permissions view access for only one permission in the list
I have a Django class based view in which I am using the PermissionRequiredMixin. I would like a user who has at least one of the permissions in the permissions_required attribute to be able to access the view. From the Django documentation: The decorator may also take an iterable of permissions, in which case the user must have all of the permissions in order to access the view. So, if User1 has permission, "add_polls" and User2 has "change_polls", and I have a form view that lets a user add a poll and another view that lets a user change a poll (with permissions_required="add_polls" and permissions_required="change_polls" on each of those views, respectively), it works great. But, what if I have an interim page/view that has links to both of those views with permissions_required = ("add_polls", "change_polls") that I need the user to pass through first? Now, neither user will be able to access to that page because the users only have access to one or the other permission, not both - if I understand the documentation correctly, a user will need BOTH those permissions to access the interim page. If I did give both users access to both those permissions so … -
This QueryDict instance is immutable (Trying to manually set form data)
When I go to save. It will not allow me. I am trying to add details into the database through inputting the form manually. I am struggling to actually input the data into the form so I can save it. For example, I have tried to get the form data then set the data I would like it to be set to however Im guessing this is incorrect? I cannot find a command to set the form data manually. Is this possible? views from telnetlib import LOGOUT from django.shortcuts import redirect, render from django.http import HttpResponse from matplotlib import use from matplotlib.pyplot import get from matplotlib.style import context from werkzeug import Request from .models import Account, Question, sni, Option from django.contrib.auth.hashers import make_password, check_password from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, logout from django.contrib.auth import login as dj_login from django.forms import ModelForm, forms from django.contrib.auth.decorators import login_required from .forms import AccountAuthenticationForm, SNIForm, createUserForm, resultForm def login(request): context = {} if request.method == 'POST': username = request.POST.get('username').lower() password = request.POST.get('password') user = authenticate(request, userID = username, password = password) form = AccountAuthenticationForm(request.GET) if user is not None: dj_login(request, user) return redirect('dashboardPage') else: messages.info(request, "userID or password … -
How to know the key of a DRF Serializer DictField from within that field's child?
Let's say we have some Django Rest Framework Serializer (we'll call it "serializer") that has a custom DictField as one of its fields. Within that custom DictField, the child field is tasked with recording the dictionary key that it is the value of whenever serializer.save() is called. How would one go about knowing the key of the dictionary being deserialized when interpreting the internal value to be saved? class ChildField(Serializer): parent_key = CharField() def to_internal_value(self, data): # At this point, the likely candidate for the # key is self.field_value, but it is actually '' # data['parent_key'] = ??? return super().to_internal_value(data) class ParentField(DictField): child = ChildField() Assume the data being deserialized is the following: { "the_dictionary": { "key_we_want_to_save": { "arbitrary_other_child_data": True } } } -
Django if statements in forms
I am trying to allow a user to upload a file of unknown type through a form and then save it to a folder depending on the type of file it is. I was hoping I could use 'if' statements, but I can't make them work inside the form. I currently just have direct upload paths: class Post(models.Model): Priority_Upload = models.FileField(default='priority', upload_to='priority/', blank=True, null=True) title = models.CharField(max_length=100) content = models.FileField(default='text', upload_to='text/', blank=True, null=True) image = models.ImageField(default='default', upload_to='images/', blank=True, null=True) video = models.FileField(default='video', upload_to='videos/',blank=True, null=True) large_video = models.FileField(default='large_video', upload_to='large_video/', blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) # user owns the post, but post doesn't own the user. author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I'd like to do something like this, but it doesn't work: class Post(models.Model): Priority_Upload = models.FileField(default='priority', upload_to='priority/', blank=True, null=True) title = models.CharField(max_length=100) if(*image ends in .txt*) content = models.FileField(default='text', upload_to='text/', blank=True, null=True) if(*image ends in .png*) image = models.ImageField(default='default', upload_to='images/', blank=True, null=True) ... is there any way to do this? -
Problems running the app locally with heroku and django
I'm trying to use my project locally to do some migrations since I was using heroku, but to migrate I need the local environment. Suddenly I got these errors whenever I use: python manage.py collectstatic and python manage.py runserver I already have my .env file with its variables, the SECRET_KEY and DEBUG. What I did notice is that in the file of settings, the config marks it in red from decouple import config I don't know where to start or how to translate them. -
How can I package my Django project with a server software so that it is ready to run on any machine?
I want to share the project to multiple clients so that they can use it on their own local networks without doing a lot of work. So somehow packaging the Django project along with a secure server software together so that it easily can be run on any machine would be nice. -
Escape single curly brace in Django template
I am looking to generate a string like \usepackage{mypackage} from a Django template. Suppose there is a variable package.name in the context how can I generate this? Firstly I tried, \usepackage{{{package.name}}} but that throws TemplateSyntaxError Then I tried \usepackage{ {{package.name}} } which works but has the two spaces in the output, ie, \usepackage{ mypackage } Is there an easy way to generate this string with Django template engine? -
Django default image not saving
I am having an issue while saving a default image whenever I am not uploading an image in ImageField. I can't understand what I am doing wrong, for me it seems everything ok but couldn't find where the bug is. models.py class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) date_of_birth = models.DateField() fiscal_code = models.CharField(max_length=50) phone = models.CharField(max_length=50) license = models.ForeignKey( License, on_delete=models.CASCADE, blank=True, null=True) picture = models.ImageField( blank=True, null=True, default='default.png') id_card = models.ForeignKey( IDCard, on_delete=models.CASCADE, blank=True, null=True) address = models.CharField(max_length=100) cap = models.CharField(max_length=10) city = models.CharField(max_length=100) province = models.CharField(max_length=100) country = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py def create_student(request): context = { } if request.method == 'POST': username = request.POST.get('username') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') date_of_birth = request.POST.get('date_of_birth') email = request.POST.get('email') phone = request.POST.get('phone') password = request.POST.get('password') address = request.POST.get('address') cap = request.POST.get('cap') province = request.POST.get('province') country = request.POST.get('country') fiscal_code = request.POST.get('fiscal_code') id_number = request.POST.get('id_number') expire_date = request.POST.get('expire_date') picture = request.FILES.get('picture') id_image = request.FILES.get('id_image') # fs = FileSystemStorage() # filename = fs.save(picture.name, picture) # profile_pic_url = fs.url(filename) # filename2 = fs.save(id_image.name, id_image) # id_image_url = fs.url(filename2) try: user = CustomUser.objects.create_user( username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=3) user.student.address = address user.student.date_of_birth = date_of_birth user.student.cap = cap user.student.province = province … -
new locale not redirecting properly
I have a basic django cms running with lots of localised content. I have been assigned to add few more languages before content can take over. here is a sample english url: <domain>/en/myhelp/ this is the sample menu which is supposed to render the menu dropdown: <body> {% cms_toolbar %} <div class="container faq-main main-block"> <div class="select-wrapper"> <select name="language" id="faq-lang" class="lang-btn hide"> <option value="en">English</option> <option value="hi">हिंदी</option> <option value="mr">मराठी</option> <option value="te">తెలుగు</option> <option value="ta">தமிழ்</option> <option value="kn">ಕನ್ನಡ</option> <option value="bn">বাংলা</option> <option value="ml">മലയാള൦</option> <option value="gu">ગુજરાતી</option> </select> </div> {% block content %}{% endblock content %} {% block contact %}{% endblock contact %} {% block actions %}{% endblock actions %} </div> {% render_bundle 'faq' 'js' %} {% render_block "js" %} </body> any language selected from menu dropdown updates the url accordingly. for example on selecting mr, url mentioned above would change to: <domain>/mr/myhelp/ All good so far. Now i have added 2 more langs in this menu: <option value="od">ଓଡିଆ</option> <option value="as">অসমীয়া</option> Problem is that when i select od / as from menu, url changes to: <domain>/en/od/myhelp/ <domain>/en/as/myhelp/ basically, en is not removed from url locale causing page not found error. Any help or indication in right direction to correctly add this locale is appreciated. version: django-cms: 3.7.1 Django: …