Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add a custom header to the swagger UI when using drf-yasg?
When doing API documentation there is an API which reads a token from the headers. It should not be a part of the authentication as the authentication system is not yet built. There is only one API which has to read this particular header. Is there anything that I can do with the annotation @swagger_auto_schema? -
Django email not sending mail
I created a view for email that worked for sometime but recently stopped sending mails. However I can see the mail in the console. I don't know what is wrong. I have used both send_email and Emailmessage but none of them work. views.py def mail(request): msg = EmailMessage('Request Callback', 'Here is the message.', to=['****@gmail.com']) msg.send() return HttpResponseRedirect('/') settings.py DEFAULT_FROM_EMAIL = '****@gmail.com' SERVER_EMAIL = '****@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = '****@gmail.com' EMAIL_HOST_PASSWORD = '***********' -
Can´t import an existing chatbot into Django Framework
I´ve already programmed a simple chatbot some time ago. Now I want to implement it into my Django project. I tried: from .bsbot import model bsbot.model.response() bsbot is the name of my folder in wich I programmed the bot. In this folder there is an training_data file wich was created when I run train.py. If I try to run my Django server the Errormsg says: File"bsbot/model.py", line 16, in <module> data = pickle.load(open("training_data", "rb")) FileNotFoundError: [Errno 2] No such file or directory:'training_data' If already tried some different kinds of importing like: import bsbot.model.response or from .bsbot import * or from smarthome.web.bsbot import model I´ve also put an init.py into my folder so that python knows it´s a package. But it´s empty. Should there be any code in it? I think the problem is that can´t find the training_data file. If I run just the bot everything works fine. -
How to remove Ck editor tag in django rest framework
I am using Django rest framework. The CkEditor tags I've used for the web appear in the API part. How do I remove these tags from the API I had not used Ckeditor before, I was using the Django TextField field models.py class Lesson(models.Model): ... lesson_content = RichTextField( verbose_name=_('Ders İçeriği'), blank=True ) ... seriaizer.py class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = (...,'lesson_content',...) output(Json Data) "id":1, "user":2, "lesson_name":"Microprocessors","lesson_content":"/<p>Merkezi .</p>", "lesson_notes":"<p>&nbsp;</p>\r\n\r\n<p>Yazıcı, R., 1998, Mikrobilgisayar Donanım ve Yazılımı, KT&Uuml; Yayınları, Trabzon, 345 s.</p>\r\n\r\n<p>Brey, B., B., 1984, Microprocessor/Hardware Interfacing and Applications, Merrill, 414 p.</p>\r\n\r\n<p>Leventhal, L., A., 1979, Z80 Assebly Language Programming, Osborne/McGraw-Hill, 612 p.</p>\r\n\r\n<p>Uffenbeck, J., 1985, Microcomputers and Microprocessors: The 8080, 8085, and Z80 Programming, Interfacing, and Troubleshooting, Prentice-Hall, 670 p.</p>\r\n\r\n<p>&nbsp;</p>" <p> & nbsp; </p> \ r \ n \ r \ n <p> I don't want the tags to appear -
Filter data on django admin console with URL
Is there any way to filter modal data on Django admin console with URL and POST request? I have a dynamic URL which I am creating on the basis of filters on template. As this is a GET request and length of URL depends on the results filtered. HTTP URL has length restriction. For smaller number of results it is working fine but problem with very long number of results. Is there any other way to filter data on admin console or is there any way to filter results rendered with POST request? Otherwise there is overhead to create custom template which may lead to performance and other issues for large numbers of records (>4K). url = self.reverse("admin:appName_modalName") + "?id__in=" + ",".join( [str(x) for x in records.values_list("id", flat=True)]) -
How to get uwsgi init status?
I use uwsgi to start my Django application by executing command uwsgi --init uwsgi.ini, uwsgi.ini is the uwsgi's config file. I use echo $? to check out the uwsgi init status, But I found out whether my Django application starting success or not, echo $? always return 0, the question is how can I get uwsgi starting status correctly? -
Putting methods in a class in views.py
I am creating a simple todo app just to learn Python & Django. My current code: def create_task(request): # code for creating a task def delete_task(request, task_id): # code for deleting task def show(request, task_id): # show a task def list(request): # show list of tasks def create_sub_task(request): # code for creating a sub_task def delete_sub_task(request, sub_task_id): # code for deleting sub_task def flip_sub_task_completed(request, sub_task_id) # make a sub_task completed/uncompleted As you can see, a task has subtasks. This is working fine. But I think it would be better to separate Tasks and SubTasks, and create 2 classes for them. Would it be better? And how would I go on achieving that? How would I need to change my urlpatterns = [ to make it work? Thanks a lot! -
attempt to write a readonly database SQLite, Django
I have implemented my simple Django applications on server, but my forms for users can not save anything. My database settings looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } My error which template receives looks like this: nvironment: Request Method: POST Request URL: http://68.183.76.239/wyniki-wyszukiwania/konta-bankowe/ Django Version: 2.2.2 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'django_filters', 'crispy_forms', 'django_select2'] Installed 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'] Traceback: File "/home/app/lib/python3.5/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) File "/home/app/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute 383. return Database.Cursor.execute(self, query, params) The above exception (attempt to write a readonly database) was the direct cause of the following exception: File "/home/app/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/app/app/app/views.py" in search_results_account 149. product_broken_form.save() File "/home/app/lib/python3.5/site-packages/django/forms/models.py" in save 458. self.instance.save() File "/home/app/lib/python3.5/site-packages/django/db/models/base.py" in save 741. force_update=force_update, update_fields=update_fields) File "/home/app/lib/python3.5/site-packages/django/db/models/base.py" in save_base 779. force_update, using, update_fields, File "/home/app/lib/python3.5/site-packages/django/db/models/base.py" in _save_table 870. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/app/lib/python3.5/site-packages/django/db/models/base.py" in _do_insert 908. using=using, raw=raw) File "/home/app/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/app/lib/python3.5/site-packages/django/db/models/query.py" in _insert 1186. … -
Not able to Migrate DB, using python manage.py makemigrations
I want to migrate model in DB, so I am using this command in my active environment python manage.py makemigrations But it gives me this error File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax Can you please provide me solution for it? -
Django Custom Multi User Model Data filling
I wanted to make an app which hold information about different types of account. Problem I can fill the form but its not taking the input and storing it in the model i want to store it into. Models.py from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) username_regex = '^[a-zA-Z0-9+-]*$' # Create your models here. class AccountManager(BaseUserManager): def create_account(self, username, email, password=None): if not email: raise ValueError('Users must have a email id') account = self.model( username = username, email=self.normalize_email(email), ) account.set_password(password) account.save(using=self._db) return account def create_student(self,username, email, password=None): account = self.create_account( username = username, email=email, password=password,) account.is_student = True account.save(using=self._db) return account def create_teacher(self, username, email, password=None): account = self.create_account( username = username, email=email, password=password,) account.is_teacher = True account.save(using=self._db) return account def create_superuser(self, username, email, password=None): account = self.create_student( username = username, email=email, password=password,) account.is_student = True account.is_teacher = True account.is_admin = True account.is_staff = True account.save(using=self._db) return account class Account(AbstractBaseUser): username = models.CharField(max_length=60, validators =[RegexValidator(regex = username_regex, message = 'Username must be alphanumeric', code = 'Invalid_username')], unique=True) email = models.EmailField(verbose_name='Email Address', max_length=255, unique=True, ) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default = False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = … -
Django models attributes - can't resolve attribute reference
I tried to resize profile photo, but it sends no errors, and it does nothing. Only thing that my pycharm says is this 'unresolved attribute reference path for class ImageField'. Any idea what should I do? I tried with .path and .url, neither work. But in django documentation for FieldFile, both attributes seem to exist. def save(self, *args, **kwargs): if not self.id and not self.image: return super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) -
how to pass the dictionary to django template using javascript
I am trying to pass the dictionary values to django template through JavaScript Views.py population_count = ( {'name': 'Year 1800', 'data': '[107, 31, 635, 203, 2]'}, {'name': 'Year 1900', 'data': '[133, 156, 947, 408, 6]'}, {'name': 'Year 2012', 'data': '[1052, 954, 4250, 740, 38]'}, ) population_count_js = json.dumps(population_count) jsonstring return render(request, 'index.html', {'data': population_country_js},{'count': population_count_js}) But I am getting the error like " Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at (index):17" var b = '{{count|safe}}'; console.log(JSON.parse(b)) index.html var a = '{{data|safe }}'; console.log(JSON.parse(a)) var b = '{{count|safe}}'; console.log(JSON.parse(b)) Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Historic World Population by Region' }, xAxis: { categories: JSON.parse(a) }, series: JSON.parse(b) }); I except the output in the chart Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at (index):17 -
How to change a OneToOneField into ForeignKey in django model with data in both table?
I am having a model Employee with a OneToOneField relationship with Django USER model. Now for some reason, I want to change it to the ManyToOne(ForeignKey) relationship with the User model. Both these tables have data filled. Without losing the data how can I change it? Can I simply change the relationship and migrate? -
After first query in the database, I want to Make a boolean field false
I'm trying to implement a mechanism were by only 1 one query will be made in the database after the query, a boolean field in the database will change its status from true to false. I don't know how to accomplish this. The Model class Code(models.Model): best_before = models.DateTimeField(auto_now=True) expiry_date = models.DateTimeField(auto_now=True) code = models.CharField(max_length=8, blank=True, unique=True) status = models.BooleanField(blank=True) And I'm using a get request to query code field in the database. View def index(request): info = Code.objects.all() query = request.GET.get('q') print(query) if query: info = info.filter(code__exact=query) context = { 'info':info, 'query':query } return render(request, 'drugs/index.html', context) -
Is it possible to find or match two names which has different special characters django
I am trying to populate cities in a state using OpenstreetMaps API to my django application. The database was populated with some cities already. I am facing duplicate data issue since the name in cities sometime has special characters in it. For example in country Turkey, The state Bursa has city Gursu. My database has a city object with name Gürsu. And the city name from Openstreet Map API is Gürsü. I am trying to find a solution to match existing city with special character name and update it if it exists. So that I can avoid duplicates. -
unique_together does not replace primary key
In my Django app, I want to insert a record with a composite primary key. Apparently this should be possible by making use of "unique_together". I'm quite sure this code was working in the past, but for some reason it does not seem to be working now. This code used to run on a Linux VM, and now I'm hosting it in Google App Engine. However I don't see how this can be the cause for this error. class TermsAndConditionsDocument(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE, verbose_name=_("Organization")) language = models.CharField(_('Language'),choices=LANGUAGE_CHOICES, max_length=5, help_text=_("The language of the content.")) content = models.TextField() class Meta: unique_together = ('organization', 'language') The error: IntegrityError at /transactions/settings/terms_and_conditions null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, nl-BE, <p>B</p>, 10). According to what I've read, using "unique_together" should cause Django to not need or include an ID as primary key. I checked the database, and the ID field DOES exist. I do not understand where the database constraint and the ID field are still coming from? -
Docker Django uWSGI strange connection error
I'm trying to test a production environment of a Django app in a docker container, using a uWSGI server. My dockerfile looks like this: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY config/requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ EXPOSE 8000 CMD ["uwsgi", "--ini", "./uwsgi.ini"] and my uwsgi.ini like this: [uwsgi] http = :8000 chdir = ./ module = testproject.wsgi master = 1 processes = 2 threads = 2 When I build the container and run it, everything seems to work, but when I visit localhost:8000, rather than seeing my app, I get this error: [uwsgi-http] unable to connect() to node "127.0.0.1:61104" (3 retries): Connection refused I have no idea where this 61104 port is coming from (it's not specified anywhere), but I think the issue is that uWSGI can't properly connect to django... I've tried setting debug=False in the settings.py, and also adding that weird port to allowed hosts, but no dice. If anyone knows the answer to this I'd appreciate it! -
How to access buttons in a separate HTML file in the HTML file it is included in as header?
So I'm making an application which require a header. On this header are navigation buttons and whatnot. I need to access these buttons at the respective homescreen where this header html is included in. However, when i try to access these buttons they wont do anything, even though I've got an if-statement which calls for all of these buttons if pressed. I've tried separating the Header.html to see if it works as a normal page, which it does. It only doesn't work when it is included as a header. The HTML of the header: <form method="POST"> {% csrf_token %} <div class="sidenav"> <button type="submit" name="vergelijken" value="vergelijken">Vergelijken</button><br> <button type="submit" name="dag" value="dag">Dag</button><br> <button type="submit" name="week" value="week">Week</button><br> <button type="submit" name="maand" value="maand">Maand</button><br> <button type="submit" name="jaar" value="jaar">Jaar</button><br> &nbsp; <button type="submit" name="live" value="live">Live</button> {% load static %} <img src="{% static 'images/rdot.png' %}" class="rdot_logo"/> </div> </form> The django code: def header(request): global keuze if request.method == "POST": if request.POST.get('vergelijken'): print('hallo') return HttpResponseRedirect('/vergelijk/') elif request.POST.get('dag'): keuze = 'dag' elif request.POST.get('week'): keuze = 'week' elif request.POST.get('maand'): keuze = 'maand' elif request.POST.get('jaar'): keuze = 'jaar' elif request.POST.get('live'): keuze = 'live' return render(request, 'header.html') Apologies, variables are in dutch. So basically I need these if statements in the django code to work … -
In Django, does `queryset is None` evaluates the queryset?
Is Django queryset evaluated in below cases? If no, then why? 1. if queryset is None: pass 2. from django.db.models.query import QuerySet if isinstance(queryset, QuerySet): pass Is it because in both the cases python performs object reference comparison, which does not lead to a query? -
Dynamic JS and Django Calculator
I have no clue of JS, I copied this and modified it in a 4 hours so please be kind. I have a simple calculator. The concept behind is this. 1. There are check boxes which take their number/integer value from the database. Check boxes appear according to the number of entries in the database. 2. When a check box is clicked it's value is to show in the display of the calculator. 3. By checking two or more check-boxes, their values get added together and then displayed on the display. 4. By Un-checking a box the value is to be deducted from the display and the remaining value is to show. I'm able to add two values but when there are more elements the values don't add up. When I un-check a box and check it again the value adds up in the total again and gives the total of 3 values instead of 2. (the third being it self all over again) The value isn't deducting from the total. cal.html <head> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> </head> <body> <div class="calc"> <form name="form"> <input class="calc-display" > </form> <table> <br> {% for i in food_data %} <tr> <td><input type="checkbox" id="foodCheck" data-value="{{i.item_price}}" … -
Add custom ROW in Django admin view
I want to add a custom ROW in my django admin page, such that the last row contains some values specified by me. I tried searching but only found things like adding a new column (using list_display ) or adding entirely new features using changelist_view function (like a button to perform an action or adding a chart etc) . What I want to do is: add a ROW to the table(containing the objects of the model) which is generated by django's default admin view. -
I want to exceute one process only after completion of another process in my django application using celery
I am new to the celery thing. I want to run one process only after the completion of another one. While searching I found one code class CallbackTask(Task): def on_success(self, retval, task_id, args, kwargs): print("success") pass def on_failure(self, exc, task_id, args, kwargs, einfo): print("fail") pass @celery.task(base=CallbackTask) # this does the trick def add_val(x, y): time.sleep(20) return x + y while running that code, it shows status in the following order: Received task //After 20 min timer success(it is getting printed from 'on_success' method) 3.task completed (#ans-7) Actually, the problem here is 'success' is getting printed before my actual answer, if there is any way that I get that after my answer, then I can easily put my second process in the 'on_success' method and execute it. -
I want to make .bat file on the desktop that once clicked the file starts django python server, and opens Chrome
Make .bat file from django that runs the server once clicked and opens chrome browser. @ECHO ON start cmd.exe /C "python manage.py runserver && cd C:\Users\admin\Desktop\JUDICIARY\ && C:" start C:\"Program Files (x86)"\Google\Chrome\Application\chrome.exe "http://127.0.0.1:8000/" The .bat file opens the chrome browser but it shows 'This site can't be reached' but if I start the server manually then if I open the .bat file it opens without problems. -
Django_select2 : How to filter ModelSelect2Widget queryset with a request data? (Django_tables2 + Django_filter +Django_select2 )
I use django_tables2 with django_filter according to django_tables2 tutorial: #views.py from django_filters.views import FilterView from django_tables2.views import SingleTableMixin class FilteredCarListView(SingleTableMixin, FilterView): table_class = CarTable model = Car template_name = 'template.html' filterset_class = CarFilter def get_queryset(self): return self.model.objects.filter(owner_id=request.user.id) Also I want to use django_select2 in django_filter: I want to have a filter's field and its ModelSelect2Widget with the same filter as in FilteredCarListView.get_queryset(self). For filter's field I found this decision (I guess it is not DRY): # filters.py from .models import Car from django_select2.forms import ModelSelect2Widget def get_cars(request): return Car.objects.filter(owner_id=request.user.id) class CarFilter(django_filters.FilterSet): car = django_filters.ModelChoiceFilter( queryset = get_cars, field_name='car', widget = ModelSelect2Widget( model = Car, search_fields=['car__icontains']) But how to limit choises in ModelSelect2Widget to display current user's cars only? -
Custom MultipleChoiceField does not preserve model's values
I have this form, where I customized the way items are displayed using the choices attribute. This works fine and users names are correctly displayed, but the problem is on edition (i.e. where the Form is given an instance of Story with existing assignees), the corresponding <li> are not selected... models.py class Story(BaseModel): assignees = models.ManyToManyField(User, blank=True, related_name="assigned") forms.py class StoryForm(forms.ModelForm): assignees = MultipleChoiceField(choices=[(user.id, user.get_full_name() or user.username) for user in User.objects.all()]) view.py def story_edit(request, story_id): if request.method == 'POST': story = get_object_or_404(Story, id=story_id) form = StoryForm(request.POST, instance=story) if form.is_valid(): form.save() else: story = get_object_or_404(Story, id=story_id) form = StoryForm(instance=story) return render(request, 'story_form.html', {'form': form}) story_form.html <p> {{ form.assignees.errors }} {{ form.assignees }} </p> I tried adding the initial arg to the MultipleChoiceField (see below), but nothing changed. class StoryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoryForm, self).__init__(*args, **kwargs) self.fields['assignees'] = MultipleChoiceField(choices=[(user.id, user.get_full_name() or user.username) for user in User.objects.all()], initial=[user.id for user in self.instance.assignees])