Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hi everybody. I'm making a shop with django and i have a problem with custom User
When I'm trying to delete my ShopUser i have this exception I have not found a solution to this problem on the internet Exception Type: OperationalError Exception Value: no such table: account_shopuser_groups Also this exception resises when I want to migrate. How can i solve this problem? My CustomUserModel: class ShopUser(AbstractUser): username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), error_messages={ 'unique': _("A user with that username already exists."), }, ) email = models.EmailField(_('email address'), unique=True) EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] is_superuser = models.BooleanField( _('superuser status'), default=False, help_text=_( 'Designates that this user has all permissions without ' 'explicitly assigning them.' ), ) objects = CustomUserManager() date_joined = models.DateTimeField(_('date joined'), default=timezone.now) def has_perm(self, perm, obj=None): return True def __str__(self): return self.username my CustomUserAdmin class ShopUserAdmin(UserAdmin): add_form = ShopUserCreationForm form = ShopUserChangeForm model = ShopUser list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( (None, {'fields': ('email', 'password',)}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active')} ), ) search_fields = ('email',) ordering = ('email',) admin.site.register(ShopUser, ShopUserAdmin) Thank you for help! -
How to display just the tags in form instead of all the list elements in Django?
I have a form used to create and edit an object on Django, and I'm trying to implement tags with django-taggit and Crispy Forms. Currently it's working great to create the tags, and it creates a list of tags for the field. When I want to edit the object I get the field pre-populated with those tags, but they are not 'flattened', so the tags show as: [<Tag:Tag1> <Tag:Tag2> <Tag:Tag3>] rather than just Tag1 Tag2 Tag3 And if the object contains no tags there is [] in the form field. My view to edit the objects is: def edit_recipe(request, recipe_id): """Edit an existing recipe""" recipe = get_object_or_404(Recipe, pk=recipe_id) if request.method == "POST": form = RecipeForm(request.POST, request.FILES, instance=recipe) if form.is_valid(): form.save() messages.success(request, "Successfully updated recipe.") return redirect(reverse("recipes")) else: messages.error(request, "Failed to update. Please check the form.") else: form = RecipeForm(instance=recipe) template = "recipes/edit_recipe.html" context = {"form": form, "recipe": recipe} return render(request, template, context) My model includes the field tags as so: tags = TaggableManager(blank=True) And my form is: class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ( ... "tags", ) widgets = {"tags": forms.TextInput(attrs={"data-role": "tagsinput"})} What do I need to do to populate the form to edit an already existing … -
How to create a table with django models inside the app?
my_api ├── admin.py ├── apps.py ├── heroes │ ├── admin.py │ ├── __init__.py`enter code here` │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-38.pyc │ │ ├── __init__.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── serializers.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── serializers.py │ └── views.py ├── __init__.py ├── migrations │ ├── __init__.py │ └── __pycache__ │ └── __init__.cpython-38.pyc ├── models.py ├── __pycache__ │ ├── admin.cpython-38.pyc │ ├── apps.cpython-38.pyc │ ├── __init__.cpython-38.pyc │ ├── models.cpython-38.pyc │ ├── urls.cpython-38.pyc │ └── views.cpython-38.pyc ├── tests.py ├── urls.py ├── views.py I am trying to build a simple rest api with drf. created a directory heroes inside the my_api and created a new class. now my_api/heroes/models.py looks like this: class Hero(models.Model): name = models.CharField(max_length=50) power = models.CharField(max_length=100) my_fav = models.BooleanField() def __str__(self): return self.name The problem is, whenever I try to migrate this table doesn't get created. What should I change to make it work? -
Django blog app with comments using class views
I' wanted to try Django framework and i tried the blog app tutorial. i tried to add a comment feature. i know these questions have been asked several times but couldn't find a solution to my problem. i got 'No Post matches the given query' error. Thanks for your help. Here are the Model and all: urls.py : path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>/', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('post/<int:pk>/comment/', PostCommentView.as_view(), name='post-comment'), path('about/', views.about, name='blog-about'), ] models.py: class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) # many to one relation use foreign key def __str__(self): return self.title @property def get_comments(self): return self.comment_content.all() # return the url as string def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='comment_content', on_delete=models.CASCADE) def __str__(self): return self.content def get_absolute_url(self): return reverse('comment-create', kwargs={'pk': self.pk}) forms.py: class CommentForm(forms.ModelForm): content=forms.Textarea() class Meta: model = Comment fields=['content'] views.py: class PostCommentView(LoginRequiredMixin, CreateView): model = Comment fields = ['content'] template_name = 'blog/comment_form.html' success_url = '/' def form_valid(self, form): post = get_object_or_404(Post, id=self.kwargs.get('id')) print(post.id) form.instance.author = self.request.user form.instance.post = post return super().form_valid(form) comment_form.htlm: {% extends … -
Can't login to django admin with correct credentials
I can't login to my django admin side even after puting correct credentials. It gives me the error... "Please enter the correct email and password of a staff account. Note that both fields may be case sensitive." And yes, the credentials is a superuser, a staff and active. I use a custom authentication backend and my version is Django 2.2 -
How to create relative entry in mongoldb using Django?
I have following Person document model. from djongo import models from django.contrib.postgres.fields import ArrayField class Person(models.Model): id = models.ObjectIdField() name = models.CharField(max_length=255) city = models.CharField(max_length=255) status = models.CharField(max_length=20) phone_number = models.CharField(max_length=20) objects = models.DjongoManager() And the following Comment model class Comment: id = models.OneToOneField( Person, on_delete=models.CASCADE, primary_key=True, ) comments = ArrayField(models.CharField()) objects = models.DjongoManager() When I create a document in Person object, I want mongo automatically create a document in Comment model with the same id but empty comments. I thought declaring OneToOneField filed will do it, but it didn't. What should I do? -
Get env variable from heroku
I have django project on heroku. On my Procfile i use 'release: bach./releast-tasks.sh' that will generate new env variable. web: gunicorn billions.wsgi --log-file - release: bash ./release-tasks.sh Here my release-tasks.sh: #!/bin/sh electrum daemon -d electrum setconfig rpcport 7777 pass=$(electrum getconfig rpcpassword) echo $pass export RPCPASSWORD=$pass The deploy (git push heroku master) is working fine and perfectly. I do not get any error. But now on my code i try to get "RPCPASSWORD" env variable like that : logger.info(os.environ.get('RPCPASSWORD', 'None')) It's alaways returning None. So 2 problems : I am not sure the env variable is really set with release-tasks.sh If it's correctly set, why i can't grab it with my django code :/ ? Thank for your help ! -
Add CSS to form field in django template
I want to use bootstrap on django form. To do so I need to add .form-control class to each field. My workaround is: def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = { 'class': 'form-control' } {% for field in form %} <div class="form-group"> {{ field.label_tag }} {{ field }} </div> {% endfor %} But I believe it's wrong to put CSS in python code (if I would want to use another CSS framework, I would have to change form class). How can I move the class to template? I would not like to use crispy not to be bound to bootstrap. -
TinyMCE with DigitalOcean Space in Django
I am currently working on building blog site using django and DigitalOcean Space. I've connected everything so static and media files automatically get saved to DigitalOcean space. However, I've been trying to get images in content (TinyMCE HTMLField()) get saved to DigitalOcean Space but seems to be not working. If I drag and drop the image to TinyMCE richtext area, it gets img src from my local path. If I do Upload, Source address seems to be generated with right path, but it's not saving the images to Space. I currently have In settings.py, TINYMCE_DEFAULT_CONFIG 'images_upload_url': '/upload_image/' In views.py, @csrf_exempt def upload_image(request): if request.method == "POST": file_obj = request.FILES['file'] file_name_suffix = file_obj.name.split(".")[-1] if file_name_suffix not in ["jpg", "png", "gif", "jpeg", ]: return JsonResponse({"message": "Wrong file format"}) upload_time = timezone.now() path = os.path.join( settings.MEDIA_ROOT, 'tinymce', str(upload_time.year), str(upload_time.month), str(upload_time.day) ) # If there is no such path, create if not os.path.exists(path): os.makedirs(path) file_path = os.path.join(path, file_obj.name) file_url = f'{settings.MEDIA_URL}tinymce/{upload_time.year}/{upload_time.month}/{upload_time.day}/{file_obj.name}' client.upload_file('file_obj', 'blmakerspace-spaces', 'file_url') if os.path.exists(file_path): return JsonResponse({ "message": "file already exist", 'location': file_url }) with open(file_path, 'wb+') as f: for chunk in file_obj.chunks(): f.write(chunk) return JsonResponse({ 'message': 'Image uploaded successfully', 'location': file_url }) return JsonResponse({'detail': "Wrong request"}) and urls.py set to path('upload_image/', upload_image) … -
I feel lost with Django in every possible way
I am new to stack overflow so feel free to criticise if this ain't the kind of post to put on here, but I really don't know where else to ask then here where population is so big. I don't know how to start django project of my own.Yes I watched tutorials, got myself cheat sheets for django and html and am currently doing guide which explains things step by step and am doing and trying to understand as much as possible. The problem is even with all this, I've got only as far as navigating and making new directory with command prompt, loading virtual environment, running server and opening shell. I get the idea behind all the code in the guide that was written and what each line does but if you asked me to make a basic website on my own I wouldn't be able to do anything besides setting up the environment. Is there like a pattern to follow when making shit from scratch and do beginners like me even do anything from scratch or what? I have some great ideas, and while I do love coding, I am learning django for purpose of making my own … -
Custom Form Field Naming Within Loop
I'm trying to specify field names within a loop on a form, so that the fields do not overwrite themselves. Right now I'm using this in my form: class TicketForm(forms.ModelForm): class Meta: model = Ticket exclude = ['products'] class ProductForm(forms.Form): product_id = forms.IntegerField() count = forms.IntegerField() class TicketProductForm(forms.ModelForm): class Meta: model = Ticket exclude = [] for Product in Product.objects.all(): product_id = forms.IntegerField(initial=Product.product_id) count = forms.IntegerField(initial=0) The for loop within TicketProductForm currently only displays one set of fields, as product_id and count overwrite the fields over and over, only displaying for the last entry in the set of Product. Is there a way to customize field names so that I can name them, preferably with a way I can set a specifier to allow easier lookup later? -
Django admin panel does not display correctly
Good evening, I taught the django framework at the rate. Before that, the admin panel was displayed correctly, now for some reason it is displayed as I understood without css styles Default django server, writing code in pycharm And before it was displayed like this settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*ky(o6p+iw1(8u4fx$^fwnpdqt337(yw3*uk%g02b3*8(x-av$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'news.apps.NewsConfig', ] 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', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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 = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': … -
How to run Django and Celery in separated Docker container?
I want to have two containers - one for my Django app and one for the Celery that the Django app uses. Those two containers have the same code. In my tasks.py file I have: app = Celery('myapp', broker=settings.CELERY_BROKER, backend=settings.CELERY_BACKEND) Where broker is a URL to redis. The way I start my celery app: docker build -f Dockerfile.celery -t celery_app . docker run -d -p 80002:8000 celery_app The way I start my django app: docker build -f Dockerfile.django -t django_app . docker run -d -p 8000:8000 django_app What should be CELERY_BACKEND to make it work? -
Django - Show message only when form has changed
I have a form and every time the form is updated a message is displayed "Your profile has been updated". This message is shown even if no changes has been performed in the form. How can i prevent the form to show message only when changes has been performed? views.py @login_required(login_url='login') def profilePage(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Your account {} has been updated'.format(request.user.username)) return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'members/profile.html', context) forms.py class ProfileUpdateForm(forms.ModelForm): phone_number = PhoneNumberField(label=False, widget=forms.TextInput(attrs={'placeholder': 'Phone Number'})) image = forms.ImageField(label=False) class Meta: model = Profile fields = ['phone_number', 'image', ] Thank you for help! -
How to include Selenium tests in Github Actions?
I have a basic test like this: When I locally do: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.webdriver.chrome.webdriver import WebDriver from selenium import webdriver class TestKundeSeite(StaticLiveServerTestCase): @classmethod def setUp(cls): cls.browser = webdriver.Chrome(r'crm\tests\chromedriver.exe') @classmethod def tearDownClass(cls): cls.browser.quit() super().tearDownClass() def test_kunde_anlegen(self): self.browser.get('%s%s' % (self.live_server_url, '/crm/kunde_anlegen')) vorname_input = self.browser.find_element_by_name("vorname") vorname_input.send_keys('Max') nachname_input = self.browser.find_element_by_name("nachname") nachname_input.send_keys('Mustermann') email_input = self.browser.find_element_by_name("email") email_input.send_keys('max@hotmail.de') telefon_input = self.browser.find_element_by_name("telefon") telefon_input.send_keys('+4917666994073') web_input = self.browser.find_element_by_name("web") web_input.send_keys('max.de') notiz_input = self.browser.find_element_by_name("notiz") notiz_input.send_keys('Beispielnotiz') self.browser.find_element_by_xpath('//input[@value="Speichern"]').click() when I do: python manage.py test it works fine. But when I push it to Github, I get the following error in Github Actions selenium.common.exceptions.WebDriverException: Message: 'crm\tests\chromedriver.exe' executable needs to be in PATH. How can I overcome this problem? I don't know how to set up a environment for Selenium Tests in Github Actions -
How can I user Django ready LoginView view in my own view?
I mean I want to use LoginView, but inside my own view function. And I want to know that how to write code of that function, that user can Login. -
Django. Url cant find view
I need help with {% url (url to template) %} when i try to open another view i see a NoRewerseMatch error. here is my html file: {% load static %} <head> <link href='{% static "navbar_style.css" %}' rel="stylesheet", type="text/css"> </head> <header> <nav class="headlist"> ---> <a href='{% url "home" %}'><img id = "img1" src="{% static 'logo.png' %}" alt="logo"></a> <ul> <li><a href="#">O nas</a></li> <li><a href="#">Kontakt</a></li> <li><a>Zajęcia</a></li> </ul> </nav> </header> my app(pages)/urls.py from django.contrib import admin from django.urls import path from . import views app_name = 'pages' urlpatterns = [ path('', views.home_view, name='home_view'), path('index/', views.index_view, name='index_view'), ] views.py import... # Create your views here. def home_view(request): listoftexts = Text.objects.order_by('-pub_date') context = { 'listoftexts': listoftexts } return render(request, 'pages/home.html', context) def index_view(request): listoftexts = Text.objects.order_by('-pub_date') context = { 'listoftexts': listoftexts } return render(request, 'pages/index.html', context) -
How to create separate model(table) for Admin User and Normal User in Django
I just want separate table for Normal User and Admin User. -
ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools
Here is the complete error i am getting while uploading on Heroku. ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xjv_7ys0/dbus-python/setup.py'"'"'; file='"'"'/tmp/pip-install-xjv_7ys0/dbus-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-t7juccst/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.6m/dbus-python Check the logs for full command output. -
How can I fix? while (interp->next) ^~ error: command 'gcc' failed with exit status 1
I'm trying to deploy my Django app to Heroku. So I ran into the error like: while (interp->next) ^~ error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-l9i4zubq/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-l9i4zubq/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-vgdty8_x/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.8/psycopg2 Check the logs for full command output. I don't really understand, what the problem is. -
How best to implement the logic for determining the post rank in serializer?
Now I have the serializer like: class PostTopSerializator(serializers.ModelSerializer): id_post = serializers.IntegerField(source='id') comment_count = serializers.SerializerMethodField('get_count_comment') rank = serializers.SerializerMethodField('get_rank') class Meta: model = Movie fields = ['id_post', 'comment_count', 'rank'] def get_count_comment(self, object_id): total_comments = Comment.objects.filter(movie_id=object_id).count() return total_comments def get_rank(self, object_id): return object_id.id the Post with the most comments gets rank 1, second place rank 2, and so on... And I get answer like: [ { "id_movie": 2, "comment_count": 5, "rank": 2 }, { "id_movie": 1, "comment_count": 4, "rank": 1 }, { "id_movie": 3, "comment_count": 4, "rank": 3 } ] how to implement the logic of the methoв: def get_rank(self, object_id): return object_id.id to get the same rank with the same number of comments and the output will be: [ { "id_post": 2, "comment_count": 5, "rank": 1 }, { "id_movie": 1, "comment_count": 4, "rank": 2 }, { "id_post": 3, "comment_count": 4, "rank": 2 } ] -
django HttpResponse Location redirect
I am trying to redirect to another page when http response is True I have added response['Location'] = 'login.html' but it's not working, I am getting a page with True written but not the login page. Can you help me I am new to django. I have written this code if user_obj: response = HttpResponse(True) response['Location'] = 'login.html' return response else: return HttpResponse(False) -
Python Django giving me Forbidden (403) CSRF verification failed. Request aborted
I have added {% csrf_token %} inside all my form tags like this: {% extends 'base.html' %} {% block content %} <form method="post"> {% csrf_token %} #-------------> here it is {% for field in login_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} {field.help_text}} {% endif %} </p> {% endfor %} {% for field in login_form %} {% for error in field.errors %} <p>{{error}}</p> {% endfor %} {% endfor %} {% if login_form.non_field_errors %} <p>{{login_form.non_field_errors}}</p> {% endif %} <input type="submit" value="Login"> </form> {% endblock content %} But when I actually try to login using that form and click the submit button, it should then redirect me to the home page. However, instead it is giving me the below error message: *Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that … -
js saving data entered in forms to models
i'm using the following jquery calendar to add events https://codepen.io/charlie7587/pen/eWLKaZ and i'm wondering how can i add the data entered to my models class Event(models.Model): eventName = models.TextField() NumberofPeopleInvited = models.TextField() class Meta: verbose_name = u'Event' verbose_name_plural = u'Events' -
in Django, multiple select input just returns a single value?
I have a very simple form with a "select" field. For each user in the app it creates an option field, that works fine: <select name="users" id="users" multiple> <option value="{{admin.id}}" selected>{{ admin.username }}</option> <!-- can I delete the admin from this list? --> {% for user in users %} <option value="{{user.id}}">{{ user.username }}</option> {% endfor %} </select> Now when I try to retrieve the values of "users", even if they are all selected I always just get a single value...: if request.method == "POST": title = request.POST["title"] admin = request.user project_users = request.POST["users"] print(project_users) I just get "1" or "2" but not a list? How can I retrieve all of the values from this multiple select?