Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Shared Django field across model instances
I'm new to Django, and need help with something quite basic. Suppose we created a model representing a worker, and we wanted to create a function to calculate how much each worker made after taxes. For simplicity, a worker has a take-home pay of their gross income times their tax rate, and the tax rate is a variable that all workers share. class Worker(models.Model): gross_income = models.FloatField(null=True, blank=True) def take_home_pay(self): return self.gross_income * tax_rate I know how to store each worker's gross income in the database. I did it using models.FloatField. Here's my questoin: how would I store the tax rate, which is shared across workers, in the database? -
Static files 404 in production
None of my static files are loading after deploying my app. When I check in the dev tools they're all 404. I ran python3 manage.py collectstatic My static folder has the following permissions and ownership: drwxr-xr-x 8 root root 4096 Nov 17 23:28 static My /etc/apache2/sites-enabled/example.conf: <VirtualHost *:80> ErrorLog ${APACHE_LOG_DIR}/example-error.log CustomLog ${APACHE_LOG_DIR}/example-access.log combined WSGIDaemonProcess example processes=2 threads=25 python-ho> WSGIProcessGroup example WSGIScriptAlias / /srv/example/example/wsgi.py Alias /robots.txt /srv/example/static/robots.txt Alias /favicon.ico /srv/example/static/favicon.ico Alias /static /srv/example/static/ Alias /media /srv/example/media/ <Directory /srv/example/example> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /srv/example/static> Require all granted </Directory> <Directory /srv/example/media> Require all granted </Directory> </VirtualHost> -
How to add Conditionals for a Notifications System in a Django Project
I have set a Notification system for my Django project when a user likes or comments on a post the Author received a notifications of this activity. I am trying to add an option so that the Author of the Post can receive a Notification also when the num_likes reaches a certain no. So, here is what I have tried but nothing happened. Here is the models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') likes = models.ManyToManyField(User, related_name='liked', blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'Blog Posts' #---------------------------My trial------------------------------------------ def like_progress(sender, instance, *args, **kwargs): post = instance if post.num_likes == 1: notify = Notification(post=post, user=post.author, notification_type=3) notify.save() # num_likes post_save.connect(Post.like_progress, sender=Post) #---------------------------My trial------------------------------------------ Here is the notifications model.py class Notification(models.Model): NOTIFICATION_TYPES=((1,'Like'),(2,'Comment'),(3,'Admin')) post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name="noti_post", blank=True, null=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="noti_to_user") notification_type= models.IntegerField(choices=NOTIFICATION_TYPES) text_preview= models.CharField(max_length=90,blank=True) date=models.DateTimeField(auto_now=True) is_seen=models.BooleanField(default=False) def __str__(self): return self.notification_type here is the notifications app views.py def ShowNotifications(request, *args, **kwargs): user=request.user notifications= Notification.objects.filter(user=user).order_by('-date') Notification.objects.filter(user=user, is_seen=False).update(is_seen=True) template= loader.get_template('notifications/notifications.html') context = { 'notifications': notifications, } return HttpResponse(template.render(context, request)) here is … -
Docker "Error During Connect" (Duplicate)
This is a duplicate but I decided to post because the version for other posts are not on the same version as mine and not on the same OS So I am running on windows 10 and docker version 19. I have this issue where when I run some commands such as docker version or docker run , it throws an error with something like: error during connect ..... this suggest docker daemon might not be running So I decided to check if docker daemon is running, I opened Docker Destop but the setting run when log in is checked and I looked in task manager and it shows a process called docker service is running in the background so meaning that it should be running (right?) So I decided this might be another problem, does anyone have suggestions on what I should try to resolve the problem? Thanks -
How to get data from the following form?
What's the right way to get data from the following form? I would like to get it into a Django view or just JQuery and make ajax call to Django. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/css-toggle-switch@latest/dist/toggle-switch.css" rel="stylesheet"/> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <fieldset> <legend>View</legend> <div class="switch-toggle alert alert-light"> <input id="week" name="view" type="radio" checked> <label for="week" onclick="">Week</label> <input id="month" name="view" type="radio"> <label for="month" onclick="">Month</label> <a class="btn btn-primary"></a> </div> </fieldset> -
How to display data in a given time range in Django?
Sort films by number of comments topMovie = Movie.objects.annotate( num_comments=Count('Comments')).order_by('-num_comments') model.py: class Movie(models.Model): Title = models.CharField(max_length=200) Year = models.CharField(max_length=25, blank=True) Rated = models.CharField(max_length=10, blank=True) class Comment(models.Model): comment_text = models.CharField(max_length=200) movie_id = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name='Comments') pub_date = models.DateTimeField(blank =True,default = now) how to transfer the time frame to display this field topMovie = Movie.objects.annotate( num_comments=Count('Comments')).order_by('-num_comments') within the specified time frames -
Wagtail and Django-Tenants, does it work together?
Does anyone have experience in this topic? Is it fully incompatible or might it be possible to customize certain parts of the app to make it work. -
Date filters fail in django
I have a function: def update_coins_table(): # Check if the currency has been updated in the last hour up_to_date_currency = Currency.objects.filter( currency_value_in_dollars_date= [datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)] if up_to_date_currency.exists(): # Return if it is return if not do_greeting(): print("Gecko crypto board not reachable. Db setup") return crypto_coins_prices = cg.get_price(ids=coins_ids_str, vs_currencies='usd') datetime_now = datetime.now() for coin_key in crypto_coins_prices: coin = Currency( currency_name=coin_key, currency_value_in_dollars=crypto_coins_prices[coin_key]['usd'], currency_value_in_dollars_date=datetime_now) coin.save() and get the following error on executing filter(), up_to_date_currency = Currency.objects.filter( currency_value_in_dollars_date= [datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)] Error message: Internal Server Error: /get_currency/ Traceback (most recent call last): File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\views.py", line 21, in get_latest_currency update_coins_table() File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\get_coins_scheduler.py", line 38, in update_coins_table up_to_date_currency = Currency.objects.filter( File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup lookup = lookup_class(lhs, … -
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!