Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Mysql Database is not created in Docker
I setup a django project in docker container and every thing is working as expected, except I don't find the project database in mysql image. Dockerfile FROM python:3 RUN mkdir /django-website WORKDIR /django-website COPY . /django-website RUN pip install -r requirements.txt docker-compose.yml version: '3' services: db: image: mysql:5.7 restart: always environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=mywebsite - MYSQL_USER=root - MYSQL_PASSWORD=root ports: - '33060:3306' volumes: - /var/lib/mysql web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/django-website ports: - '8000:8000' links: - db I ran migrate and it worked: docker-compose run web python manage.py migrate I createdsuperuser: docker-compose run web python manage.py createsuperuser The development server is working docker-compose up and the site is working as expected, the issue when I navigate in mysql image I don't find my project related database which is mywebsite . can you please tell me what is missing? if the database is not created, where has the migration been applied? Thanks in advance. -
How should I display a notification in the Backend?
Web development projects are in progress. When the server is running, the background scheduler runs and periodically sends a GET request to the server. The server that received the GET request executes the data update operation and waits for the request again. Here, I want to show the notification on the screen while the server receives the request and processes the job. What can I do? We are developing in django. -
How to avoid Error in Multiple primary key path Django
I want to go see the result of the student by clicking pages: Select Session --> Select Course But getting error: Reverse for 'selectresult' with keyword arguments '{'pk_1': 1}' not found. 1 pattern(s) tried: ['Dashboard\/selectsession\/(?P[0-9]+)\/(?P[0-9]+)$'] My code: Url pattern in urls.py: path('selectsession/', views.SelectSession.as_view(), name='selectsession'), path('selectsession/<int:session_pk>/', views.SelectCourse.as_view(), name='selectcourse'), path('selectsession/<int:session_pk>/<int:pk_1>', views.BatchResult.as_view(), name='selectresult'), Templates: selectsession.html: <li><a href="{% url 'Dashboard:selectcourse' session_pk=sesid.sesid %}">{{sesid.sesid}}</a></li> selectcourse.html: <li><a href="{% url 'Dashboard:selectresult' pk_1=course.course.cid %}">{{course.course}} {{course.teacher}}</a></li> views.py: @method_decorator(login_required, name='dispatch') class SelectSession(ListView): template_name = 'Dashboard/selectsession.html' model = Session fields = ['sesid'] def get_queryset(self): return Session.objects.all() @method_decorator(login_required, name='dispatch') class SelectCourse(ListView): template_name = 'Dashboard/selectcourse.html' model = Course, Registration fields = ['all'] def get_queryset(self): course = Registration.objects.filter(session_id=self.kwargs['session_pk']) return course @method_decorator(login_required, name='dispatch') class BatchResult(ListView): template_name = 'Dashboard/batchResult.html' model = Result,Student,Registration,Assignation fields = ['all'] def get_queryset(self): result=Result.objects.filter(asign__reg__id=self.kwargs['pk_1']) return result -
Django rest framework remove a field from API Create form
I have a model and viewset related to this model, here is my code : class EMAILTemplate(models.Model): """ Message SMS Template """ user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() tokens = models.TextField() created = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.tokens = ",".join(re.findall(r'{{\s*(.*?)\s*}}', self.body)) super().save(*args, **kwargs) I don't want field tokens to be in my create form in Django rest framework create or edit form, because as you see It's going to be extracted from body field. but I want to have this field in view single model or list of models. and here is my ModelSerializer : class EmailTemplateSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = EMAILTemplate fields = ('name', 'body', 'user', 'tokens') -
Django two forms on the same page
I have two forms on the same page. The first form uses a 3rd party lib to upload a file to s3 and then preview what it just uploaded without changing state/ going to a different page. The second form is going to save the url of the uploaded file to my model However, when I submit the second form - the first form throws an error. About not having required fields. HTML <form id="s3form" name="s3form" action="{% url 'file_create' employee.uid %}" method="post" > {% csrf_token %} {{ form }} </form> <hr/> <form id="save-pic" name="save-pic" action="{% url 'employee_update_profile_pic' employee.uid %}" method="post" > {% csrf_token %} {# jquery inserts hidden input for image link after s3 upload #} <input id="save-pic-submit" name="save-pic-submit" type="submit" value="Save" > </form> -
Hyphen in place of date in django
I have issue regarding Date in Django. I have one Model and it has two date fields. I have registered it in admin. And this both field is working fine in local server. Now when I uploaded it on AWS and try to run the page it shows hyphen (-) in place of dates. Not a single date is visible all fields has hyphens. Please tell me solution for this. Thank you Models.py startTime = models.DateTimeField(auto_now_add=True) sendTime = models.DateTimeField(auto_now=False) -
Django--TypeError: validate_location() missing 2 required positional arguments: 'location' and 'parcare_on'
Am trying to create a validator for my models but i still have this error: validate_location() missing 2 required positional arguments: 'parcare_on' and 'location' What am i doing wrong here? def validate_location(self, parcare_on, location): parcare_on = self.parcare_on location = self.location q = Parcare.objects.all().filter(parcare_on=self.parcare_on) if location in q: raise ValidationError( _('%(location)s is already ocuppied'), params={'location': location}, ) My models: class ParcareManager(models.Manager): def active(self, *args, **kwargs): return super(ParcareManager, self).filter(draft=False).filter(parking_on__lte=timezone.now()) class Parcare(models.Model): PARKING_PLOT = ( ('P1', 'Parking #1'), ('P2', 'Parking #2'), ('P3', 'Parking #3'), ('P4', 'Parking #4'), ('P5', 'Parking #5'), ('P6', 'Parking #6'), ('P7', 'Parking #7'), ('P8', 'Parking #8'), ('P9', 'Parking #9'), ('P10', 'Parking #10'), ('P11', 'Parking #11'), ('P12', 'Parking #12'), ('P13', 'Parking #13'), ('P14', 'Parking #14'), ('P15', 'Parking #15'), ) def validate_location(self, parcare_on, location): parcare_on = self.parcare_on location = self.location q = Parcare.objects.all().filter(parcare_on=self.parcare_on) if location in q: raise ValidationError( _('%(location)s is already ocuppied'), params={'location': location}, ) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, default=1, on_delete=True) email=models.EmailField(blank=True, null=True) parking_on = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, help_text='Alege data cand doresti sa vii in office') parking_off = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True, help_text='Alege Data Plecarii') numar_masina = models.CharField(max_length=8, default="IF77WXV", blank=True, null=True, help_text='Introdu Numarul Masinii') location = models.CharField(max_length=3, blank=True,default="P1", null=True, choices=PARKING_PLOT, help_text='Alege Locul de Parcare Dorit', validators=[validate_location]) updated = … -
parsererror error when Trying to use Ajax on a Django Post LIKE DISLIKE functionality
I have a Django Post Like/Dislike feature in my App. The feature works amazing on its own. However when I add ajax to the Like/Dislike button the whole thing breaks giving me a Parsererror Working Code without Ajax Models.py class Post(models.Model): #title, slug, message, etc exist but not included here likes = models.ManyToManyField(User, blank=True, related_name='post_likes') def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username, 'slug': self.slug}) def get_api_like_url(self): return reverse('posts:like_post', kwargs={'username': self.user.username, 'slug': self.slug}) Views.py class PostLikeToggle(LoginRequiredMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): slug = self.kwargs.get('slug') print(slug) obj = get_object_or_404(Post, slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) print(url_) return url_ Template: <form action="{{post.get_api_like_url}}" method="post"> {% csrf_token %} {% if user in post.likes.all %} <button type="submit" name="post_slug" value="{{ post.slug }}" class="btn btn-link like_button"> <img class="like_heart" src="{% static 'images/HEART.RED.png' %}" height="25px"> </button> {% else %} <button type="submit" name="post_slug" value="{{ post.slug }}" class="btn btn-link like_button"> <img class="like_heart" src="{% static 'images/HEART.png' %}" height="25px"> </button> {% endif %} </form> Urls.py url(r'^(?P<username>[-\w]+)/(?P<slug>[-\w]+)/like_post/$', views.PostLikeToggle.as_view(), name="like_post") Everything above works perfectly I added Ajax. Below is my code after adding AJAX where I get the parsererror Template same as above Models same as above Urls same as above Views.py class PostLikeToggle(LoginRequiredMixin, RedirectView): def get_redirect_url(self, … -
File Browser configuration error: name 'settings' is not defined
I try to activate django-filebrowser-no-grappelli and I've use this indications for its configuration. Then I've updated setting.py with this: # Application definition INSTALLED_APPS = [ 'grappelli', 'filebrowser', 'tinymce', 'app4test', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djangosite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'app4test/templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djangosite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'it' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media-folder') MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'app4test/static'), ] # django-tinymce4-lite config data TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime … -
Django forms.ModelForm not calling init method
I don't really understand when django does call the init method... I tried to create a custom user model, which works fine in the admin view. Now I wanted to add a Form for User registration. The form looks now like this: class RegisterForm(forms.ModelForm): def __int__(self, *args, **kwargs): super(RegisterForm, self).__int__(*args, **kwargs) # EVT ERROR HIER self.fields['password1'] = forms.CharField(widget=forms.PasswordInput) self.fields['password2'] = forms.CharField(widget=forms.PasswordInput) print("STARTING FORM") #password1 = forms.CharField(widget=forms.PasswordInput) #password2 = forms.CharField(widget=forms.PasswordInput,) class Meta: model = User fields = ('email', ) def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): #raise forms.ValidationError(_("Mail is allready taken")) pass return email def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: #raise forms.ValidationError(_("Passwords don't match")) pass return password2 As you can see in the form, I tried around a little bit. But nothing what is inside the init method is called. I really don't get why. I want to use crispy-forms, and I put my helper method inside the init method. Fist I thought it is a crispy-forms error/bug. But after not even a print method is called, I get the feeling my init method is not called. Inside the views I got following: class SignUpView(bracesviews.AnonymousRequiredMixin, bracesviews.FormValidMessageMixin, generic.CreateView): form_class … -
Where is "views.py"
Him I am trying to set up my first django project. I have never done Django before so I don't know anything about it. I am trying to follow the official Django tutorial page, it tells me to open views.py. I can't find it anywhere in my "mysite" folder. In it, I have manage.py , db.sqlite3, __init__.py, settings.py, urls.py and wsgi.py along with the pycache folder, but no signs of views.py. Can anyone help me? -
Django; How to validate spaces or change paragraph in forms
Django forms don't recognize spaces. When I try to submit form like Hello World, the data is Hello World. Also I cannot change the paragraph. How can I fix this problem? -
Where do I import the `DoesNotExist` exception in Django 1.10 from?
I'm having trouble figuring this out. The line from django.core.exceptions import DoesNotExist gives me the cannot find reference in exeptions.py warning. If the exception is not specified in that file, where do I find it? -
In Django, after submitting a form, how to load the results page inside a div (On the same form page)?
I'm working with Django and i have a home.html template where the user fills a form and clicks on a submit button. When the user clicks on submit, i want to load the results template results.html just below the form in home.html (i'm loading the results template in a new tab right now, after processing the submitted data in my view). I searched a lot on internet but i don't know even how to start and how to do it with Django. Thank you so much in advance! -
Monitor videos watched using django
I am currently implementing a django project to help me with my studies. I would like to be able to monitor videos I watched (ie when? where I stopped if I did not watch it in full? how many times I watched it? ...). I don't plan to upload the videos to the database as it is several Gb of size, but to call with their path on my hard drive. Basically the features I'm looking for are similar to the ones present in Kodi for those of you which know it. I Googled for that question and could for instance found the following: How to check a user watched the full video in html5 video player But the solutions suggested make use of Javascript which I am not very familiar with. Would there be a django/python way to get the event and then just save it to the database with the videos? Thanks, Sophie -
Django rules object permissions
I am trying to use django rules to configure object permissions in django and the django admin interface. Now when I add permission rules, they will always only be called with the first param, but the object is always None. For example I if I would create this predicate: @rules.predicate def is_book_author(user, book): return book.author == user And then add it to the django permission set: rules.add_perm('books.add_book', is_book_author) Now when I log into the admin interface with a user, then the is_book_author will be called with the user and None. It will be called multiple times (once per object), but the object ist always None. I am using rules 2.0.0 with django 2.1.1 and python 3.7. Any ideas if I'm doing something wrong or how to configure django to call the predicate with the individual object? -
Error at OneToOneField in models while creating new models class django
I am facing below error while creating a new model class. the error pop up only at this line "user = models.OneToOneField(User)" "E1120:No value for argument 'on_delete' in constructor call" from django.db import models from django.contrib.auth.models import User class userProfile(models.Model): user = models.OneToOneField(User) admin.py from django.contrib import admin from section.models import userProfile admin.site.register(userProfile) If I add below entry with "on_delete=models.CASCADE" user = models.OneToOneField(User,on_delete=models.CASCADE) the error got subsided but the new class "userProfile" is not appearing in admin page, under Users tab. Could some one please guide me how to fix this ? -
Display images via TemplateView
I feel I am just too stupid to display my ImageField in my template. Tried some solutions and it never works. Guess I am doing something wrong. models.py class Photo(models.Model): title = models.CharField(max_length=40) subtitle = models.CharField(max_length=40) description = models.CharField(max_length=150) photo = models.ImageField(upload_to="hammers/") def __str__(self): return self.title urls.py urlpatterns = [ path('', views.HomeView.as_view(), name='home'), ] views.py: class HomeView(TemplateView): template_name = 'hammers/home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['images'] = Photo.objects.all() return context home.html {% for image in images %} <img src="{{ image.photo.url }}"> {% endfor %} The picture uploads to "/hammers/static/hammers/photos/" I haven't set anything in settings.py, only STATIC_URL = '/static/' because everything failed until now. -
django The current path, image/25x25, didn't match any of these
I am using Django 2.1.1 . this is my manage.py file: import os import sys from django.conf import settings settings.configure( ROOT_URLCONF=__name__, MIDDLEWARE_CLASSES=( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ), ) from django import forms from django.urls import path from django.http import HttpResponse, HttpResponseBadRequest def placeholder(request, width, height): ... if : ... return HttpResponse('OK') def index(request): return HttpResponse('Hello World') urlpatterns = [ path(r'image/(<int:width>)x(<int:height>)/', placeholder, name='placeholder'), path(r'', index, name='homepage'), ] ... when I browse '127.0.0.1:8000/image/10x10', this error occured: Using the URLconf defined in __main__, Django tried these URL patterns, in this order: The current path, image/25x25, didn't match any of these I think my code is right so what is going on?? may it cause of not using suitable middleware? '127.0.0.1:8000' in worked right. -
Deploying website with React frontend and Django rest framework backend
I am deploying my first website and currently have it running locally with React on the front end communicating with the Django backend which has a database and a rest API. I am now at the point I have been most concerned about. I need to find a way to get this onto an actual online service. Could I get some advice on what steps I need to take get this all online? And a suggestion on what services I should use? For further details this is a hobbyist website that will likely not have much traffic. However, I don't mind spending a bit of money to get it running quickly and consistently. -
Django: Transaction and select_for_update()
In my Django application I have the following two models: class Event(models.Model): capacity = models.PositiveSmallIntegerField() def get_number_of_registered_tickets(): return EventRegistration.objects.filter(event__exact=self).aggregate(total=Coalesce(Sum('number_tickets'), 0))['total'] class EventRegistration(models.Model): time = models.DateTimeField(auto_now_add=True) event = models.ForeignKey(Event, on_delete=models.CASCADE) number_tickets = models.PositiveSmallIntegerField(validators=[MinValueValidator(1)]) The method get_number_of_registered_tickets() do I need at several places in my application (e.g. template rendering). So I thought it makes sense to put it into the model also because it's related to it and I often heard it's good to have "fat models and lightweight views". My problem now: In order to prevent that two people want to register for the event in parallel, I have to use locking. Example: Let's say there's one ticket left to register for. Now, to people are on my website and click "Register" simultaneously. Under unforunate circumstances, it could happen that both requests are valid and now I have more registrations than capacity. I'm relatively new to Django, but reading through the docs, I thought that select_for_update() should be the solution, am I right here (I use PostgreSQL, so that should be supported)? However, the docs also say that using select_for_update() is only valid within a transcation. Evaluating a queryset with select_for_update() in autocommit mode on backends which support SELECT ... FOR … -
how to Create Nested router urs in rest_framework?
i have created a url using NestedSimpleRouter. And the url that i have created is that : http://localhost:8000/api/category/1/subcategory/ And In above url 1 in the id of category .And my problem is that i want to create the url like this http://localhost:8000/api/category/1/subcategory/1/interest this 1 is subcategory_id So How can i define Nested url for this url .My urls.py is given below: urls.py: from django.urls import path,include from rest_framework_nested import routers from campaignapp import views router = routers.DefaultRouter() router.register('campaign',views.CampaignViewSet) router.register('interestbundle',views.InterestBundleViewSet) router.register('category',views.CategoryViewSet,'category') category_router = routers.NestedSimpleRouter(router, r'category', lookup='category') category_router.register(r'subcategory', views.SubcategoryViewSet, base_name='category-subcategory') urlpatterns = [ path('',include(router.urls)), path('',include(category_router.urls)) ] -
Django rewrite forget password template
This is my urls.py url(r'^password_reset/$', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset.html'), name='password_reset'), url(r'^password_reset/done/$', auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'), name='password_reset_done'), This is my password_reset.html: <form method="post"> {% csrf_token %} <div class="body "> <div class="form-group"> <input type="email" name="email" required class="form-control" placeholder="Email*"/> </div> <div class="footer"> <button type="submit" class="btn btn-success btn-sm btn-block ">Restore</button> </div> </form> settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' # mail service smtp EMAIL_HOST_USER = 'sdfrsfr' # email id EMAIL_HOST_PASSWORD = 'fdsgfd' #password EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'sdfsd@gmail.com' But the email is not sent, but when I use default django templates => everything is ok. What do I do? -
Module 'django.db.models' has no attribute 'FileBrowseField'
I would like to have on my Django 2.1.1 site django-filebrowser-no-grappelli. I've followed this indications but at the end of the procedure, when I restart my server, I've this error: header_image = models.FileBrowseField("Image", max_length=200, directory="images/", extensions=[".jpg"], blank=True) AttributeError: module 'django.db.models' has no attribute 'FileBrowseField' This are the files of my project: MODELS.PY from django.db import models from django.urls import reverse from tinymce import HTMLField from filebrowser.fields import FileBrowseField class Post(models.Model): """definizione delle caratteristiche di un post""" title = models.CharField(max_length=70, help_text="Write post title here. The title must be have max 70 characters", verbose_name="Titolo", unique=True) short_description = models.TextField(max_length=200, help_text="Write a post short description here. The description must be have max 200 characters", verbose_name="Breve descrizione dell'articolo") contents = HTMLField(help_text="Write your post here", verbose_name="Contenuti") publishing_date = models.DateTimeField(verbose_name="Data di pubblicazione") updating_date = models.DateTimeField(auto_now=True, verbose_name="Data di aggiornamento") header_image = models.FileBrowseField("Image", max_length=200, directory="images/", extensions=[".jpg"], blank=True) slug = models.SlugField(verbose_name="Slug", unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents") def __str__(self): return self.title def get_absolute_url(self): return reverse("singlearticleView", kwargs={"slug": self.slug}) class Meta: verbose_name = "Articolo" verbose_name_plural = "Articoli" VIEWS.PY from django.shortcuts import render from .models import Post from django.views.generic.detail import DetailView from django.views.generic.list import ListView class SingleArticle(DetailView): model = Post template_name = … -
Elasticbeanstalk; One of pages on my website shows `Not secure` on https
I forwarded my website from http to https. But one of my pages on the website shows like this picture. Actually only the page shows like this. The weird thing is even on the same domain name, only one page shows warning. The page shows user's profile. Currently it shows just default photo. First how can I check the cause? I have no idea where I should check. I used Amazon Certificate Manager to issue certificate and configure domain with Route53.