Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django editable ListView
I have a model: class Question(models.Model): question_text = models.CharField(max_length=200, unique=True) pub_date = models.DateField(verbose_name='date published') def __str__(self): return self.question_text I want to list all questions and edit them like inline forms. I can list questions with ListView: class UpdateDirectry(generic.ListView): model = Question template_name = 'accounts/editable_directory.html' fields = ['question_text'] queryset = Question.objects.all() but this just list all questions. I can also edit each question with UpdateView but I want all questions on a page to edit them. -
Django Admin Inline static initial data
Is there a way to simply set default values for a new inlined model instance in Django Admin? I want the same default values to always appear when the "+ Add another" button is pressed. The same thing as using get_changeform_initial_data on a normal ModelAdmin, but for an inline: def get_changeform_initial_data(self, request): return {'fieldA': 'always here', 'fieldB': 0} I've tried every solution on the internet, played a lot with formsets, but couldn't make it work. Any ideas? -
Django Rest Framework - object has no attribute post
I have this url in my urls.py path('foo/bar/api', foo.APIBar.as_view(), name='foo-bar-api'), and in my view.py I have this class that hands the api: class APIBar(APIView): def post(request, self, format=None): date= request.POST['date'] person= get_object_or_404(Person, id=request.POST['person']) return Response(status=status.HTTP_201_CREATED) And I'm trying to send this ajax: $.ajax({ url: "{% url 'foo-bar-api' %}", method: "POST", data: { date: date.val(), person: person.val() } }); But Django it's giving this error to me: AttributeError: 'APIBar' object has no attribute 'POST' I don't know why this is happening. I used the same structure in other models and works like a charm, but this one it's giving this error. Please, can you tell me what am I doing wrong? I spent some hours trying to fix this error. -
django 2.1 execute function on add new item from admin panel
i need to execute command every time when admin add new item in tabele Videos. Example admin.py class VideosAdmin(admin.ModelAdmin): list_display = ('__str__', 'author', 'created_at', 'title_gen', 'deleted') list_filter = ['created_at', 'author', 'deleted'] search_fields = ['Title', 'Description', 'Tags', 'Playlist'] exclude = ['title_gen', 'Playlist', 'Tags', 'deleted', 'author', 'Category', 'Language'] class Meta: model = Videos def get_queryset(self, request): return self.model.all_objects.all() def save_model(self, request, obj, form, change): if getattr(obj, 'author', None) is None: obj.author = request.user obj.save() admin.site.register(Videos, VideosAdmin) Every time when admin add new Video item i need to execute function proccessing(video_id), how i can do this ? -
Django-filters FilterView shows empty list on page load
So I want to link to a given page that has filters on it, and have it display every item in the table before I click search, and only stop displaying items when bad input is given. My problem is similar to the following problem, with a few differences. Empty result list on django-filter page startup The differences being the poster's default behavior is my desired behaviour and I am using class based views, not functional views. My urls: from django.urls import path from . import views app_name = 'advising' urlpatterns = [ path('', views.MyList.as_view(), name='MyList'), ] my views: from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.views import generic from django.template import loader from .models import * from django_filters.views import FilterView from .filter import * class MyList(FilterView): template_name = 'advising/MyList.html' context_object_name = 'tables' filterset_class = MyFilter def get_queryset(self): return Table.objects.order_by('Name') my filter: import django_filters from .models import Table class MyFilter(django_filters.FilterSet): Name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Table #The table this form will reference fields = ["Name"] my template: <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> {% if tables %} <ul> {% for table in tables %} <li>{{table}}</a></li> {% endfor %} </ul> {% else %} … -
Search function returning nothing -Django
def Search(request): if request.method == 'GET' and request.GET['x']: parameter = request.GET['x'] results = Category.objects.filter(advert__Seller_Name__icontains = parameter) return render(request, 'campusbuy/search.html', {'results': results}) else: return render(request, 'campusbuy/search.html') Above is my search function. When I try to search in my template, it returns nothing. However, when I deliberately search for a Seller_name that's not in the db it returns the {% else %} value. Below is the template: % extends 'campusbuy/base.html' %} {% block content %} {% if results %} {% for ads in results.advert_set.all %} <p>{{ads.Seller_Name }}</p> <p>{{ads.Location}}</p> <p>{{ads.Description}}</p> <p>{{ads.Asking_Price}}</p> {% endfor %} {% else %} <p>No Ad matched your search criteria.</p> {% endif %} {% endblock %} Thank you in advance! -
Django tables not updating column data
I'm trying to pull data from mongodb and display it as a table in display.html page. My data from table looks something like this: [{u'Subjects': u'[Sub1, Sub2, Sub3, Sub4]', u'Student Name': u'A'}, {u'Subjects': u'[Sub2, Sub12, Sub7, Sub9]', u'Student Name': u'B'},{u'Subjects': u'[Sub1, Sub2, Sub14]', u'Student Name': u'AC'}, Below is my code: views.py def data_list(): dis_data = db_data.find() table = DataTable(list(dis_data)) RequestConfig(request).configure(table) return render(request, 'app/dispaly.html', {'table': table}) My tables.py import django_tables2 as tables class DataTable(tables.Table): Names = tables.Column(verbose_name = "Student Name") Subjects = tables.Column() display.html <html> <body> {% load render_table from django_tables2 %} <div> {% render_table table %} </div> </body> </html> But when displaying its only displaying subjects but not Student Name. Where is it going wrong ? -
django 2.1 Cannot delete Item
i want to delete element from table Video, and return me this error, Deleting the Video 'add test video' would require deleting the following protected related objects: Video Title: dadsadas this is my curent models: class Videos(models.Model): Title = models.CharField(max_length=100, unique=False, help_text='video title') class TitleVideo(models.Model): title = models.CharField(max_length=100, unique=False, help_text='youtube video title') video = models.ForeignKey(Videos, related_name='video_id', null=False, blank=False, on_delete=models.PROTECT) i want do this : when i delete item from table Videos, automatic remove all titles related to videos items, how i can do this ? -
Django : ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'myblog.routing'
I searched stack over a day but still haven't got any solution till now. I made a chat app which uses websockets. setting.py ASGI_APPLICATION = "myblog.routing.application" directory structure mysite ->myblog ->chat ->myblog ->routing.py ->otherfiles routing.py inside of ,myblog directory from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) this is the error im getting File "C:\Users\JIDNYE~1.J\MYPROJ~1\mysite3\lib\site-packages\channels\routing.py", line 35, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'myblog.routing' Im stucked here from a very long time , searched every where but got no solution on web. Will be great help if someone can solve error. -
Is it possible to run a group containing chains in celery?
I am trying to run some chains inside a group and for some reason it is being blocked or and the task doesn't start at all. It just stops and halts. Basically the code boils down to this: group([ chain(chained_tasks[0]), chain(chained_tasks[1]) ] ).apply_async() which hangs forever, I would appreciate any help, I checked backendresult and rabbitmq they are running fine. I can even execute chained_tasks[0].apply_async() and it works properly. -
how to add downsampling using bokeh combined with django
i need downsampling for the following plot/figure: #plotting.py p1 = figure(title="Main Plot, start time: " + str(start_time), output_backend="webgl", toolbar_location="right", width=plot_width, height=plot_height) ... mass_spec["xs"].append(x) mass_spec["ys"].append(y) mass_spec["y_labels"].append(str(cycle) + " " + str(cycle_data[channel_name][0])) ... mass_spec['color'] = colours source = ColumnDataSource(mass_spec) p1.multi_line(xs="xs", ys="ys", legend="y_labels", line_width=2, line_color='color', line_alpha=0.8, # hover_line_color='color', hover_line_alpha=1.0, source=source) or p1.line(x, y, alpha=1, color=colours[colour_cnt], legend=(str(cycle) + " " + str(cycle_data[channel_name][0])) , line_width=2) ... script1, div1 = components(p1, CDN) in the html <div class="{{ plot_size }}"> {{ plotting_values.the_div1|safe }} {{ plotting_values.the_script1| </div> This all works fine. now i want to add downsampling, depending on the actual zoom of the chart (in total i got 2.8 million points) should be downsampled to 10%, 1% or even less) thaught about adding a Callback to the components() or somehow... or do i need to use curdoc() and implement the server view into my django template? if yes, please give a full example (plotting.py, template) --> its should be startable without terminal comand "bokeh serve", just by starting it with python manage.py runserver -
Python gets 'permission denied' to a file in Linux
I have a method to log actions on a json file: def log(self, action, data): import json import os current_directory = os.path.dirname(os.path.realpath(__file__)) try: with open(current_directory+'/logs/log_'+str(data['id'])+'.json', 'a+') as outfile: log_data = { str(datetime.today()): { 'action': action, 'data': data } } json.dump(log_data, outfile, indent=2) except Exception as e: print('\033[91m'+"Couldn't access log file to log changes in Reservation model: [{}]".format(str(e))+'\033[0m') print('Current directory is {}'.format(os.path.dirname(os.path.realpath(__file__)))) It works locally on my mac, but it always returns permission denied in Linux server. The logs directory permissions is set to 755 with chmod, but I still get the same error: [Wed Nov 28 16:27:23.551207 2018] [wsgi:error] [pid 18955:tid 139905951835904] [remote 189.149.229.31:63243] \x1b[91mCouldn't access log file to log changes in Reservation model: [[Errno 13] Permission denied: '/home/axel/IntellibookProject/Intellibook/ReservationsManagerApp/logs/log_43.json']\x1b[0m [Wed Nov 28 16:27:23.551346 2018] [wsgi:error] [pid 18955:tid 139905951835904] [remote 189.149.229.31:63243] Current directory is /home/axel/IntellibookProject/Intellibook/ReservationsManagerApp -
Django background task - Object of type 'WSGIRequest' is not JSON serializable
I'm in need of running a background task using the django module. I have succesfully created my script and when I try to load my views with the background task, I receive the following exception value Object of type 'WSGIRequest' is not JSON serializable. My code looks like the following. from django.shortcuts import render import uuid import subprocess import sys import os import time from callgolem.models import Usertasks from background_task import background from django.contrib.admin.views.decorators import staff_member_required # Create your views here. @background(schedule=60) @staff_member_required def index(request): os.chdir("C:/Users/kr85m/Google Drive/gitlab/renderwithgolemnew/var/taskqueries") logfilnavn = str(uuid.uuid4()) logfile = open(logfilnavn, 'w') proc=subprocess.Popen(['golemcli', 'tasks', 'show'], universal_newlines=True, stdout=logfile, stderr=logfile) print(proc) outfile = "clean.txt" findstatus = ['Waiting', 'Finished', 'Timeout'] delete_list = ["id ETA subtasks status completion", "------------------------------------ ------- ---------- -------- ------------", " 100.00 %", " 0.00 %", " ??? 1 ", "0:00:00 1 "] fin = open(logfilnavn) fout = open(outfile, "w+") proc.wait() for line in fin: for word in delete_list: line = line.replace(word, "") fout.write(line) fin.close() fout.close() with open(outfile, 'r') as f: for lines in f: taskidlinjer = (lines[:36]) print(taskidlinjer) printstatus = lines for taskstatus in printstatus.split(r"\r\n"): # split here by _literal_ \\r\\n if any(word in taskstatus for word in findstatus): removebloat = str(*set( taskstatus.split() ) & set(findstatus)) print(removebloat) Usertasks.objects.filter(TaskID=taskidlinjer).update(TaskStatus=removebloat) … -
Integrating datetime picker into Django Crispy forms
I have the following code (HTML/JavaScript) which is a form input for a datetime picker. main.html <div class="form-group"> <div class='input-group date' id='datetimepicker1'> <input type='text' class="form-control"/> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> forms.py class MainForm(forms.Form): gender = forms.CharField(label='Template', widget=forms.Select(choices=GENDER)) first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') address = forms.CharField(label='Address') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.layout = Layout( Field('gender'), Field('first_name'), Field('last_name'), Field('address'), Submit('submit', 'Submit', css_class='btn-success') ) My question is how do I integrate/add/use the above datepicker HTML in my DJango Crispy form? Ideally I would like to add "date of birth" to my forms.py MainForm and use the datepicker. Please could someone suggest how I can do this? -
what's the advantage of using react+django rather than using only django?
I'm studying to develop a website. As I searched, Django can develop a whole website itself. What I wonder is why some people use React and Django together. What's the advantage of using those both programs, rather than just using one? And I also want to know the difference between Django and Django Rest. I want to make a website for selling something, then which do you recommend? -
duplicate model instance with all related objects
Hi there !! As stated in the title I'm trying to clone a model instance with all the related objects I have two models : class VersionContrat(models.Model): nom_version = models.CharField(max_length=25, blank=True, null=True) version = models.IntegerField() and : class Vacation (models.Model): poste_travail = models.CharField(max_length=50, default='') version_contrat = models.ForeignKey(VersionContrat, on_delete=models.CASCADE, default=9) date_debut = models.DateField(blank=True, null=True) date_fin = models.DateField(blank=True, null=True) I tried this method in VersionContrat to copy a VersionContrat object and all the Vacation objects related with the foreign key: def duplicate(self): vacations = Vacation.objects.filter(version_contrat=self) self.pk = None self.version = int(self.version)+1 self.save() for vacation in vacations: vacation.pk = None vacation.version_contrat = self vacation.save() return print('clone to {}'.format(self)) But it doesn't work and I can't find out why, anyone has an idea why ? -
django Multiple form submit in UpdateView
I want to update the built-in User model along with the Profile (user extended) model. this is forms.py: class UserUpdateForm(forms.ModelForm): class Meta: model = auth_models.User fields = ['first_name', 'last_name', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['date_of_birth'] this is my view.py: class ProfileUpdateView(LoginRequiredMixin, generic.UpdateView, MultiModelForm): model = Profile fields = '__all__' def get_object(self, *args, **kwargs): username = self.request.user return get_object_or_404(Profile, user__username__iexact=username) def get_success_url(self): return reverse('accounts:profile') This just edits Profile fields. I also tested django-betterforms but couldn't make it work. I could show 2 forms with get_context_data() but I couldn't save to model and that was just HTML. I just want to know how get_object for the second form? -
How to point django to put a template in the front page
I am trying to learn python in the django framework, I took a course, but it was based on an earlier version of django while I am using Django 2.1.3 and python 3.7.0, so I've got errors.My question is how can I point urls.py to take an html template and put it in the main page in this version of Django? Thank you!! -
How to save form input in database for multiple inputs at the same time in django?
I am learning django and am creating an application that can register the students in a particular class based on their name and registration number. So, I created an application where the user can add form elements from where the user can add options to add different students directly into the form at the same time. Thus, the user can decide the number of student he wants to add at the same time, and add the students by their name and registration number. I have created the following form: <form method="post" action="/add_rules/"> {% csrf_token %} <div class="field_wrapper"> <div> <label>Enter Name</label> <input type="text" name="personname"> <label>Enter registration number</label> <input type="text" name="personregnumber"> <a href="javascript:void(0)" class="addPerson">Add</a> <br><br> </div> </div> <button type="submit">Submit</button> </form> The corresponding javascript to add and remove the input fields is: $(document).ready(function () { var addButton = $('.addPerson'); var wrapper = $('.field_wrapper'); var field_html = '<div><label>Enter name</label><input type="text" name="personname"><label>Enter registration number</label><input type="text" name="personregnumber"><a href="javascript:void(0)" class="remove_button">Remove</a><br><br></div>' $(addButton).click(function() { $(wrapper).append(field_html); }) $(wrapper).on('click', '.remove_button', function(e) { e.preventDefault(); $(this).parent('div').remove(); }) }) I am stuck at how to add multiple student data fields to the data base at the same time? It will be great if someone could help -
django-allauth with Django v2+ custom user model and custom user manager
Note: As of writing this there are 197 questions when searching for "django-allauth custom user". I have not read all of them, but of the several I have read, these were notable: How to customize user profile when using django-allauth Django allauth custom login form not rendering all fields in custom user model Saving custom user model with django-allauth where the questions' authors have implemented custom user models, with no difficulty, but want to modify things like the login form. In addition, I have read and completed the official Django tutorial, the mozilla Django tutorial, and this very great post by Will Vincent (which introduced me to the django-allauth. Lastly, I also consulted the django-allauth docs. I would like to focus on the tutorial by Will Vincent, as I find it the most extensive of the several out there; notably it bothers to make a custom user model. For those who have not read the entire tutorial, at [this point]]Will Vincent User Model an app was created named users and in the file <project>/users/models.py we have a custom user model: from django.contrib.auth.models import AbstractUser, UserManager class CustomUserManager(UserManager): pass class CustomUser(AbstractUser): objects = CustomUserManager() Is this the most sophisticated custom user … -
Image uploaded increases size in Django-CMS
I've got a django-cms plugin with a image field and I've noticed that the size of the images I upload using this plugins is bigger than the originals one. This can't happen, do you have any idea what could be causing this? Could it be some kind of configuration? The definition of the field in the models.py: image = models.ImageField(db_column='IMAGE', verbose_name=_(u'Image (1280x600)'), upload_to='Destaques') This is a snippet of the template where I render the image: {% load cms_tags staticfiles i18n %} {% load thumbnail %} {% thumbnail instance.imagem '1660' as im %} <div class="item" id="item_{{ instance.id }}" style="background: url('{{ im.url }}') no-repeat center / cover;"> Could it be because of the thumbnail generation? Thank you :) {% endthumbnail %} -
Generic Class-Based Models for MySQL, works like Django's Migration System
Recently I have been using Django, and one of the features I like the best are the class-based models ( table definitions ) and the related "migration" system. This comes in super handy when working between the development and production environments. I have a legacy system which I work on which uses PHP but isn't created within any fixed framework. There is a MySQL database. I currently just create the database tables manually. The issue that I am running into is when going between development and production environment, I don't have any complete system to manage the database table definitions. I would like to have something like Django's models and migrations system, so I could make changes to the database model and propagate changes to development and production environments independently. I am looking for a system that works like the Django system, but it doesn't need to be in any specific programming language, PHP would be nice. Also it would be helpful that I could create the initial classes automatically to match what I have already, since I have hundreds of tables. I know this isn't a specific question, but the SO community always helps me so much I wanted … -
Docker&Celery - ERROR: Pidfile (celerybeat.pid) already exists
Application consists of: - Django - Redis - Celery - Docker - Postgres Before merging the project into docker, everything was working smooth and fine, but once it has been moved into containers, something wrong started to happen. At first it starts perfectly fine, but after a while I do receive folowing error: celery-beat_1 | ERROR: Pidfile (celerybeat.pid) already exists. I've been struggling with it for a while, but right now I literally give up. I've no idea of what is wrong with it. Dockerfile: FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /opt/services/djangoapp/src COPY /scripts/startup/entrypoint.sh entrypoint.sh RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] COPY Pipfile Pipfile.lock /opt/services/djangoapp/src/ WORKDIR /opt/services/djangoapp/src RUN pip install pipenv && pipenv install --system COPY . /opt/services/djangoapp/src RUN find . -type f -name "celerybeat.pid" -exec rm -f {} \; RUN sed -i "s|django.core.urlresolvers|django.urls |g" /usr/local/lib/python3.7/site-packages/vanilla/views.py RUN cp /usr/local/lib/python3.7/site-packages/celery/backends/async.py /usr/local/lib/python3.7/site-packages/celery/backends/asynchronous.py RUN rm /usr/local/lib/python3.7/site-packages/celery/backends/async.py RUN sed -i "s|async|asynchronous|g" /usr/local/lib/python3.7/site-packages/celery/backends/redis.py RUN sed -i "s|async|asynchronous|g" /usr/local/lib/python3.7/site-packages/celery/backends/rpc.py RUN cd app && python manage.py collectstatic --no-input EXPOSE 8000 CMD ["gunicorn", "-c", "config/gunicorn/conf.py", "--bind", ":8000", "--chdir", "app", "example.wsgi:application", "--reload"] docker-compose.yml: version: '3' services: djangoapp: build: . volumes: - .:/opt/services/djangoapp/src - static_volume:/opt/services/djangoapp/static # <-- bind the static volume - media_volume:/opt/services/djangoapp/media # <-- bind the media … -
Foreign key in the database
I have a problem, I have a Pessoa table and a Veiculo table, and a MovRotativo table, but when I register in MovRotativo I need to select Pessoa X only the Veiculo of Pessoa X is listed. How are you now I'm selecting Pessoa X and I can put person's Veiculo Y and wanted to solve this by model.py I'm using sqllite 3 that comes in django model.py class Pessoa(models.Model): nome = models.CharField(max_length=50, blank=False) email = models.EmailField(blank=False) cpf = models.CharField(max_length=11, unique=True, blank=False) endereco = models.CharField(max_length=50) numero = models.CharField(max_length=10) bairro = models.CharField(max_length=30) telefone = models.CharField(max_length=20, blank=False) cidade = models.CharField(max_length=20) estado = models.CharField(max_length=2, choices=STATE_CHOICES) def __str__(self): return str(self.nome) + ' - ' + str(self.email) class Veiculo(models.Model): marca = models.ForeignKey(Marca, on_delete=models.CASCADE, blank=False) modelo = models.CharField(max_length=20, blank=False) ano = models.CharField(max_length=7) placa = models.CharField(max_length=7) proprietario = models.ForeignKey( Pessoa, on_delete=models.CASCADE, blank=False) cor = models.CharField(max_length=15, blank=False) observacoes = models.TextField(blank=False) def __str__(self): return self.modelo + ' - ' + self.placa class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=False, blank=False, null=False,) checkout = models.DateTimeField(auto_now=False, null=True, blank=True) email = models.ForeignKey(Pessoa, on_delete=models.CASCADE, blank=False) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) veiculo = models.ForeignKey( Veiculo, on_delete=models.CASCADE, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) -
ModuleNotFoundError Django
This is my "views.py" code : from .models import Post from .forms import postForm #the problem is in here !! def post_create(request): #list items form = postForm() #creation of a variable form context = { "form":form, #form is the name of the variable we are going to call } return render(request,'post_form.html', context) On "forms.py" I have : from django.db import models from django import forms from .models import Post class postForm(forms.Form):#forms.ModelForm): class Meta: #this is an inner class, we do this to make our project more orientated model = Post fields = [ #Here, I can add all of the fields that are in my model Post to the Form "title", "text" ] enter code here the problem is when I run the server I get this error : from . import views File "C:\Users\fatiha\djangoSite\blog\views.py", line 5, in from .forms import postForm #the problem is in here !! ModuleNotFoundError: No module named 'blog.forms' I tried to replace the from .forms import postForm with blog.forms ... but it didnt work, when I comment the #from .forms import postForm I dont get no error, any help please