Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket close with 200 status
I have setup websocket using nginx and daphne. I am also using gunicorn for handling http request. I apply the same setting in previous server it works fine now in the new server with the same setting the websocket is returning 200 satus and not connecting. Console log: WebSocket connection to 'wss://ubl.mn/ws/2/' failed: Error during WebSocket handshake: Unexpectedresponse code: 200 Daphne log: 127.0.0.1:25894 - - [22/Nov/2020:18:35:51] "GET /ws/2/" 200 3146 127.0.0.1:25900 - - [22/Nov/2020:18:36:02] "GET /ws/2/" 200 3146 The log of where the websocket is working is: 127.0.0.1:9596 - - [22/Nov/2020:18:49:09] "WSCONNECT /ws/6512/" - - 127.0.0.1:9596 - - [22/Nov/2020:18:49:54] "WSDISCONNECT /ws/6512/" - - So it seems the difference between working and not working server is in daphne log one has GET and another request has WSCONNECT like that. I don't want to post all code here at first, can someone please point to me where I may have made the mistake I can provide further info about it. -
How could I save multiple users by using a checkbox with a ManyToMany relationship?
I already did create 4 objects in Role table which refers to the role of users in website. the Role was a list but I created it in User model as a checkbox input to allow the user to choose what he wants among roles but I can't save my data that comes through cleaned_data which refers to roles data, I get the following error: 'RegisterForm' object has no attribute 'roles' in forms.py file what I miss here? here is my code: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from .models import User, Profile, Role class RegisterForm(UserCreationForm): password1 = forms.CharField(min_length=4, widget=forms.PasswordInput(attrs={ 'placeholder': 'Password' }), label='password') password2 = forms.CharField(min_length=4, widget=forms.PasswordInput(attrs={ 'placeholder': 'Confirm Password' }), label='Confirm Password') class Meta: model = User fields = ['email', 'first_name', 'last_name', 'roles', 'password1'] widgets = { 'roles': forms.CheckboxSelectMultiple() } def clean_password2(self): password = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password and password2 and password != password2: raise forms.ValidationError("password and confirm password is not same") if len(password) < 4: raise forms.ValidationError('Password is very weak please enter 4 words at least') return password def save(self, commit=True): user = super().save(commit=False) if commit: user.staff = True user.set_password(self.cleaned_data['password1']) self.roles.add(self.cleaned_data['roles']) user.save() return user models.py from django.db import models from django.contrib.auth.models import … -
getting unexpected/unwanted url path when clicking on an href link in django
so, here are all the urls i defined: path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("new", views.new.as_view(), name="new"), path("<int:user>/watchlist", views.watchlist, name="watchlist"), path("<int:user>/<str:name>", views.name, name="name"), path("<str:user>/<str:name>/watchlist/remove", views.remove, name="remove-from-watchlist"), path("<int:user>/<str:name>/watchlist/add", views.add, name="add-to-watchlist"), path("<str:user>/<str:name>/bid", views.bid, name="bid"), path("<str:user>/<str:name>/close", views.close, name="close-bid"), path("<str:user>/<str:name>/comment", views.comment, name="comment"), path("add-category", views.addC, name="add-Category"), path("categories", views.categories, name="categories"), path("<str:cat>/category", views.cat, name="category-page") From experience, the problem is with all the 'watchlist' related URLs. For example, when i am on index view, the path to path("<int:user>/watchlist", views.watchlist, name="watchlist"), is <a class="nav-link" href="{{ user.id }}/watchlist">Watchlist</a> and the url path shows the same - http://127.0.0.1:8000/2/watchlist where 2 is the user id. Then when i go to a url <a class="nav-link" href="categories">Categories</a> the url path followed is http://127.0.0.1:8000/2/categories the '2' should not be there! I specifically hard coded the path in the anchor tag I am facing another problem: when i am at the index view and i click on the anchor tag containing <a href=/{{ user.id }}/{{ item.Title }} where item.Title is say "Magic Broom", the url path i am getting is http://127.0.0.1:8000/2/Magic while it should have been http://127.0.0.1:8000/2/Magic Broom Can someone please explain what's going on here... -
Django: problem to create nested serializers
I'm trying to create a nested serializers but I'm getting this error: raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Pessoa() got an unexpected keyword argument 'endereco_pessoa' This is my serializers.py: class EnderecoSerializer(serializers.ModelSerializer): class Meta: model = Endereco exclude = ('id_endereco', 'id_pessoa',) # id_endereco is pk and id_pessoa because we'll create one while sending the post request class PessoaSerializer(serializers.ModelSerializer): endereco_pessoa = EnderecoSerializer() class Meta: model = Pessoa fields = ('cpf', 'nome', 'nome_social', 'sexo', 'data_nascimento', 'cor_raca', 'estado_civil', 'municipio_naturalidade', 'uf_naturalidade', 'pais_nascimento', 'endereco_pessoa', ) def create(self, validated_data): enderecos_data = validated_data.pop('endereco_pessoa') endereco = Endereco.objects.create(**enderecos_data) pessoa = Pessoa.objects.create(endereco_pessoa=endereco, **validated_data) return pessoa What am I doing wrong here? I really appreciate any help. I've seen a lot of similar questions like mine, but all solutions not worked for me. -
Save data to database from Django Channels consumer
I'm having an hard time editing a database entry from a Django channels consumer, here is the piece of code involved: class TestConsumer(AsyncJsonWebsocketConsumer): async def websocket_connect(self, event): ... key_query.active_connections = 2 key_query.save() ... Since i'm using an asynchronous consumer, this will give me the following error: You cannot call this from an async context - use a thread or sync_to_async. How can i perform this action from an async consumer? Maybe using @database_sync_to_async?Any advice is appreciated! -
Django REST Framework - Adding 2 PKs in URL using Generic API Views
I am designing a REST API for an application that has Teams (Groups) and Members.This leads to the following API structure: /teams/api/ - Can GET, POST. (Done) /teams// - Can GET, POST, PUT, PATCH, DELETE. (Done) /teams/<teams_pk>/join/ - Can POST (Current Login User added in the Team). (Done) /teams/<teams_pk>/leave/ - Can DELETE.(Current User can leave the Team) (Remaining) /teams/<teams_pk>/leave/<member_pk>/ Can DELETE - (Admin Member Can Remove the Member) (Remaining) views.py class TeamMemberDestroyAPIView(generics.DestroyAPIView): queryset = TeamMember.objects.all() serializer_class = TeamMemberSerializer permission_classes = [IsAuthenticatedOrReadOnly] def perform_destroy(self, instance): team_pk = self.kwargs.get("team_pk") team = get_object_or_404(Team, pk=team_pk) joining_member = self.request.user.profile TeamMember.objects.filter(team=team, user=joining_member).delete() urls.py urlpatterns = [ path('api/', TeamListCreateAPIView.as_view()), path('api/<int:pk>/', TeamDetailAPIView.as_view()), path('api/<int:team_pk>/join/', TeamMemberCreateAPIView.as_view()), path('api/<int:team_pk>/leave/',TeamMemberDestroyAPIView.as_view()), ] serializers.py class TeamMemberSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) class Meta: model = TeamMember # fields = '__all__' exclude = ("team",) class TeamSerializer(serializers.ModelSerializer): admin = serializers.StringRelatedField(read_only=True) member = TeamMemberSerializer(many=True, read_only=True) class Meta: model = Team fields = '__all__' models.py class Team(models.Model): options = ( ('public', 'Public'), ('private', 'Private') ) admin = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name='team_admin') name = models.CharField(max_length=300) description = models.CharField(max_length=300, blank=True) privacy = models.CharField( max_length=240, choices=options, default="private") member = models.ManyToManyField( Profile, through='TeamMember', related_name='team_members') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: ordering = ['-created_at'] class TeamMember(models.Model): team = models.ForeignKey( Team, … -
Why is Django LoginView login not working?
I made a login form using Django ready LoginVew class, but idk why it isnot working. Here is the code views.py from django.shortcuts import render, redirect from django.contrib.auth import views as auth_views from django.contrib.auth.forms import AuthenticationForm def main(request): if request.method == 'POST': loginform = auth_views.LoginView.as_view(template_name='main/index.html') loginform(request) return redirect('signup') loginform = AuthenticationForm(request) return render(request, 'main/index.html', {'loginform': loginform}) urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.main, name='main'), path('signup/', include('signup.urls')), path('admin/', admin.site.urls), ] HTML <div class="log-outside"> <div class="log-inside"> {% csrf_token %} {{ loginform }} <button type="subbmit">Log in</button> </div> </div> -
How to refresh the form fields and view after a different app update's the database? Django, Python
I have 2 apps, 2 forms, the checkboxes in form 1 depend on the values stored in Model 2 (by form2). The problem is, when I add a new object in Model 2 (form 2), and go to Form 1, the checkboxes do not update. I've tried all i could, please let me know what I'm doing wrong, and if there's a way to achieve this. This if form-1, where the form fields depend on the distinct values of 'queue_names' present in the QueueStatusModel (a different app) class NewInvestigatorForm(forms.ModelForm): queues_queryset = QueueStatusModel.objects.order_by().values('queue_name').distinct() queue_name_list = [] for i in queues_queryset: x = i.get("queue_name") queue_name_list.append( (x,x) ) active_qs = forms.MultipleChoiceField( choices = queue_name_list, widget = forms.CheckboxSelectMultiple, ) class Meta: model = PriorityModel fields = [ 'login', 'core', 'active_qs', 'priority' ] This is form-2, where I add a new 'queue_name': class AddNewQueue(forms.ModelForm): queue_name = forms.CharField(widget=forms.TextInput(attrs={"placeholder":"Queue Name", "size":60})) class Meta: model = QueueStatusModel fields = [ 'queue_name' ] def clean_queue_name(self, *args, **kwargs): queue_name = self.cleaned_data.get("queue_name") if " " in queue_name: raise forms.ValidationError("Queue names cannot contain space") else: return queue_name Queue Status Model, where the queue related info is stored: class QueueStatusModel(models.Model): queue_name = models.CharField(max_length=100) volume = models.IntegerField() active_investigators = models.IntegerField() New Investigator related Model: … -
After upgrading to PostgreSQL default value for ImageField does not work (Django)
Since shifting to PostgreSQL (from SQLite) the default value for ImageField does not work. If I select and upload the image manually everything is fine. Also other fields default values work fine as well. This is done from admin while adding a new post. models.py: preview_content = models.TextField(max_length=150, default="This is the default preview") preview_image = models.ImageField(default="img/blog/default_preview.jpg", upload_to="img/blog") First one works fine, second one does not. Does anyone know what the problem is? -
Django: Show downloadable custom log file
I have a small Django Project, where the user can uplaod a csv file which is parsed to the Database. If there are some formating issues detected during the processing I write them into a pd.DataFrame and want to show them to the user afterwards, so they know which lines of the csv could not be processed correctly. I thought about a few ways to do this. I could create a custom model only for the log, but I want the user to be able to download the log, which is why I would prefer to save the Log to a csv and show a download Link as well as the content of the Log, but I don't know how to do it or if there is a better way? My Code looks something like this: class ListVerifyView(ListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... return context def post(self, request, *args, **kwargs): for k, v in request.POST.items(): try: col_dict[v] = int(k) except ValueError: pass ... error_log = pd.DataFrame(columns=['Chemical', 'Error']) ... if not error_log.empty: messages.add_message(self.request, messages.WARNING, 'Some ERRORS occurred during import!') return HttpResponseRedirect(reverse_lazy('show_error')) return HttpResponseRedirect(reverse_lazy('home')) I thought about saving the Log as a models.FileField and pass the pk to reverse_lazy('show_error') but … -
Render include tag with conditional variable
I have a sub-template that renders a typical table, based on a variable transaction_items, as following: <table id="order-list" class="order-list order-list-hoverable"> <thead> <tr class="w3-light-grey"> <th>Item</th> <th>Qty</th> <th>Total</th> </tr> </thead> <tbody> {% for transaction_item in transaction_items %} <tr id="order{{forloop.counter}}{{transaction_item.name}}" data-order_modal="{{transaction_item.name}}order{{forloop.counter}}"> <td>{{transaction_item.name}}</td> <td>{{transaction_item.quantity}}</td> <td>{{transaction_item.get_total_cost}}</td> </tr> {% endfor %} </tbody> </table> In a parent template, I would like to use include tag to call this template as following: {% include "order_summary.html" with transaction_items=transaction_items_N %} Suppose I have N buttons that, when clicked, return a variable transaction_items_N. I would like to immediately re-render the above table with the new transaction_items_N. How do I make the include tag accept this kind of dynamic variable-parsing in the template? Or mus this be done with JavaScript? Thanks. -
modify the value of paginate_by for all pages
I have a follow-up question on the answer to Change value for paginate_by on the fly I added the following in the HTML <form method="GET"> <select name="paginate_by" id=""> <option value="5">5</option> <option value="10">10</option> <option value="20">20</option> <option value="50">50</option> </select> <input type="submit" value="Paginate"> </form> and this function in my ListView class class ReviewPostListView(ListView): model = Reviews template_name = 'reviews/reviews.html' context_object_name = 'rows' ordering = ['id'] paginate_by = 5 def get_paginate_by(self, queryset): return self.request.GET.get("paginate_by", self.paginate_by) it is working great, and the paginate_by is added to the URL. My problem is when I click on the second page it goes back to 5. This is my pagination HTML {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{num}}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{num}}</a> {% endif %} {% endfor %} {%if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{page_obj.next_page_number}}">Next</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a> {% endif %} {% endif %} What is the pythonic of keeping the paginate_by (if exists) parameter … -
Django app working on my system but not working on repl.it
So I created Django app: https://github.com/Paresh-Wadhwani/toDo_Django Then I imported the above repo to repl.it: https://repl.it/@pareshwadhwani/toDoDjango#README.md It is working perfectly fine on my system but on repl.it it is just showing a blank page. Here's what I did: Imported the codebase from Github into repl.it. Added the repl link to ALLOWED_HOSTS in settings.py. Executed the command "python manage.py migrate". Clicked Run [It executes the command "python manage.py runserver 0.0.0.0:3000"] Now on repl, it is just showing this blank page. ScreenShot I am new to Django and to Web Development. Any help would be appreciated. -
Unable to make a field optional in Django
I have updated my Address model to make the "State" field optional by adding blank=True and null=True. I now have the following: state = models.CharField(max_length=12, blank=True, null=True) I ran a migration for this as well, but I am still getting the following error when the form is submitted: {"errors": {"state": "This field is required."}} Where else would it be marked as being a required field? -
Initializing foriegnkey in CRUD operation
i am working on a project to manage animal farm. The backend is with django and the frot end is with bootstrap. The project has several apps as in django documentation. views.py from django.shortcuts import render,redirect, get_object_or_404 from django.http import JsonResponse from django.template.loader import render_to_string from django.urls import reverse_lazy from livestockrecords.models import * from .models import * from .forms import * from .models import * from .forms import * # Create your views here. def daily_home(request): context =() template = 'dailyrecords/daily_home.html' return render(request, template, context) > def save_feedin_form(request, form, template_name): > data = dict() > if request.method == 'POST': > if form.is_valid(): > form.save() > data['form_is_valid'] = True > livestocks = Livestock.objects.all() > context ={ > 'livestocks': livestocks > } > data['html_livestock_list'] = render_to_string('includes/_list_feeding.html', context) > else: > data['form_is_valid'] = False > context = {'form': form} > data['html_form'] = render_to_string(template_name, context, request=request) > return JsonResponse(data) def feeding_add(request, pk): livestocks = get_object_or_404(Livestock, pk=pk) data = dict() if request.method == 'POST': form = FeedingForm(request.POST , initial={'livestock': pk}) else: form = FeedingForm(initial={'livestock': livestocks}) return save_feedin_form(request, form, 'includes/_add_feeding.html') models.py from django.db import models from livestockrecords.models import Livestock # Create your models here. class Addmedication(models.Model): MEDICATIONTYPE = ( ('Drugs', 'Drugs'), ('Vaccination', 'Vaccination'), ) name = … -
how to start project with Django in powershell
I am new to web development with Python and after installing django I typed a command on powershell (on Windows): django-admin startproject mysite and it didn't work. I took this command from the Django site documentation -
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) …