Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i send alert email in django?
I want to create a property rental app where users can search property by location. If the property is not found in the particaular time, the user is notified via email when the property in that particular location is added. so how can i solve this problem?` -
Check if the /profile page is redirecting to /login page and add a warning message
Just an FYI that I'm currently at day 4 learning Django (Thanks to Corey Schafer's amazing playlist) I just completed creating the Login-logout system and was trying to add a warning message when a user tries to access the /profile without being logged in which successfully redirects to the /login page . And since the @login_required decorator doesn't have that built-in, I was trying to think of a logic which would check, if the /profile page redirects to the /login page > add a warning message. (I tried creating my own decorator but the messages.warning fxn would require a user request which would throw an error) Kinda like this noob-ey code I tried : @login_required def profile(request): if LOGIN_URL == 'login': messages.warning(request, 'You need to login in order to access this page.') return render(request, 'users/profile.html') -
Django Rest pass variable not in model for logic in overridden save method
In DRF how can I pass for example a boolean which isn't in my model from ModelViewSet so it can be used in a overridden save method for some logic? I know with a model instance you can just assign it, but I'm unsure if this is possible from ModelViewSet or goes against the general flow of DRF. -
How to shift time during django-tests
Hello I wonder is there a way to shift time during tests, globally. during tests when I call django.utils.timezone.now() to return shifted time, I need it because the software I am testing is pretty complex and if I could shift times just to be sure if all tasks and api calls are doing their jobs. For testing I am using django.tests.TestCase Thank you any help will be apprecated! -
Django views confusion, two views show same content
I have a python django application. I had a view, which I duplicated and changed slightly to create a second view. But they seem to be hooked together and duplicate the page content, when they should be different. Here is my urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView from . import views app_name = 'app' urlpatterns = [ # Journals by Discipline path('journals-by-discipline/', views.journals_by_discipline, name='journalsByDiscipline'), path('journals-by-discipline/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data), path('journals-by-discipline/journals-and-disciplines-map/', views.get_journals_and_disciplines_map), path('journals-by-discipline/disciplines-list/', views.disciplines_list), # Journals By Discipline (Elsevier) path('journals-by-discipline-elsevier/', views.journals_by_discipline_elsevier, name='journalsByDisciplineElsevier'), path('journals-by-discipline/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data_elsevier), path('journals-by-discipline/journals-and-disciplines-map/', views.get_journals_and_disciplines_map), path('journals-by-discipline/disciplines-list/', views.disciplines_list), ] I have two views, journals_by_discipline and journals_by_discipline_elsevier Here is my views.py from django.shortcuts import get_object_or_404, render from django.contrib.auth.decorators import login_required from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response import datetime as datetime from dateutil.relativedelta import relativedelta from urllib.parse import unquote import json from .onefigr_analysis import Data # Instantiate Data object to fetch data across all views data = Data() # Journals by Discipline Page def journals_by_discipline(request): template_name = 'app/journals-by-discipline.html' return render(request, template_name) @api_view(['GET']) def disciplines_list(request): if request.method == 'GET': return Response(data.get_disciplines_list()) @api_view(['GET']) def journals_by_discipline_chart_data(request, discipline): if request.method == 'GET': query_discipline = unquote(discipline) return Response(data.journals_by_discipline_chart_data(discipline)) @api_view(['GET']) def get_journals_and_disciplines_map(request): if request.method == 'GET': … -
Django - saving model via a form is not working
I'm having a little problem with the .save() method in Django. For 1 form it works, for the other it doesn't. And I can't find the problem. views.py @login_required def stock_add(request, portfolio_id): if request.method == 'POST': print('request.method is ok') form = StockForm(request.POST) print('form is ok') if form.is_valid(): print('form is valid') stock = form.save(commit=False) stock.created_by = request.user stock.portfolio_id = portfolio_id stock.save() return redirect('portfolio-overview') else: print("nope") else: print('else form statement') form = StockForm() context = { 'form':form } return render(request, 'portfolios/stock-add.html', context) forms.py class StockForm(ModelForm): class Meta: model = Stock fields = ['quote', 'amount'] html {% extends 'core/base.html' %} {% block content %} <div class="container"> <h1 class="title">Add Stock</h1> <form method="POST" action="."> {% csrf_token %} {{ form.as_p }} <button type="submit" class="button is-primary">Submit</button> </form> </div> {% endblock %} models from django.db import models from django.contrib.auth.models import User # Create your models here. class Portfolio(models.Model): title = models.CharField(max_length=56) description = models.TextField(blank=True, null=True, max_length=112) created_by = models.ForeignKey(User, related_name='portfolios', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Portfolio' def __str__(self): return self.title class Stock(models.Model): Portfolio = models.ForeignKey(Portfolio, related_name='stocks', on_delete=models.CASCADE) quote = models.CharField(max_length=10) amount = models.IntegerField() created_by = models.ForeignKey(User, related_name='stocks', on_delete=models.CASCADE) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.quote If you look at the views.py file, when I submit … -
Django HttpResponse "expected a bytes-like object, str found"
I'm getting the above TypeError from a healthcheck route on Django 3.1.2 on python 3.6. The full error logged is: ERROR 2020-11-02 16:09:50,154 /home/centos/venv/lib/python3.6/site-packages/django/utils/log.py log_response Internal Server Error: /healthcheck/ Traceback (most recent call last): File "/home/centos/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/centos/venv/lib/python3.6/site-packages/sentry_sdk/integrations/django/middleware.py", line 134, in __call__ return f(*args, **kwargs) File "/home/centos/venv/lib/python3.6/site-packages/sentry_sdk/integrations/django/middleware.py", line 90, in sentry_wrapped_method return old_method(*args, **kwargs) File "/home/centos/venv/lib/python3.6/site-packages/django/utils/deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "/home/centos/venv/lib/python3.6/site-packages/django/middleware/common.py", line 113, in process_response response['Content-Length'] = str(len(response.content)) File "/home/centos/venv/lib/python3.6/site-packages/django/http/response.py", line 315, in content return b''.join(self._container) TypeError: sequence item 0: expected a bytes-like object, str found That error is raised every time the route is requested. The full view definition is: def healthcheck_view(request): response = HttpResponse("OK", content_type="text/plain") return response What on earth have I done?? -
How to get data from a form written directly in the template not in forms.py?
I have a page with images and I want to be able to delete some of them so I wrote this form: <form method="post"> {% for img in images %} <img src={{img.image.url}}> <input type="checkbox" id={{img.id}} value={{img.id}}> {% endfor %} <button type="submit">DELETE</button> </form> and this the views.py: def lemqes(request, iid): images = IMAGE.objects.filter(id=iid) if request.method == 'POST': #how can I continue to delete multiple images return render(request, 'del.html', {'images' : images}) -
When I send message using WebSocket to the group, single user receives all the message instances
When some user send a message to some Group, only one (last connected) user receives all the message instances, but others receive nothing. A sends Message to Group with users A,B,C: C gets 3 message instances A gets nothing B gets nothing How can I solve this problem? #consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): room_id = int(self.scope['url_route']['kwargs']['room_id']) room = get_room(room_id) self.chat = get_chat(room) chat_name = str(self.chat.id) self.chat_group_name = 'chat_%s' % chat_name self.user = self.scope['user'] if room_id == 19 or is_user_in_room(self.user, room): # Join room group async_to_sync(self.channel_layer.group_add)( self.chat_group_name, self.channel_name ) self.accept() else: self.close() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.chat_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] message = save_message(self.user, self.chat, message) async_to_sync(self.channel_layer.group_send)( self.chat_group_name, { 'type': 'chat.message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] print(self.user, self.channel_name) # prints different users, different channel names # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) var ws = new WebSocket("ws://localhost:8000/ws/room_chat/19/"); ws.send(JSON.stringify({ message: this.state.struct })); -
Meaning of 'part%04d' in python
hello I am using python but I am Stuckenter image description hereat this point. where I don't know the meaning of this word "part%04d" in python. that's why I am asking you what is the meaning of this 'part%04d' in python? if you know then plz help me thank you! -
How to use the same connection for two differents consummers in Django Channels?
I use the last version of django channels(V3) and i have two consummers. This is my routing.py application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ url(r"^ws/user/(?P<user_id>\d+)/$", consumers.UserConsumer), url(r"^ws/notification/(?P<room_name>\w+)/$", con.NotificationConsumer), ]) ), }) My first app.consummes.py class UserConsumer(WebsocketConsumer): user_number = 0 def connect(self): self.room_name = self.scope['url_route']['kwargs']['user_id'] self.room_group_name = self.room_name print("connected", self.room_group_name) self.user_number+= 1 print("user_number", self.user_number) # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group print("deconnected") async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) proposal_identifiant = text_data_json['proposal_identifiant'] sender = text_data_json['sender'] messages = text_data_json['messages'] owner = text_data_json['owner'] conversator = text_data_json['conversator'] last_sender = text_data_json['last_sender'] type_ad = text_data_json['type_ad'] ad_id = text_data_json['ad_id'] price = text_data_json['price'] sending_by = text_data_json['sending_by'] price_is_changed = text_data_json['price_is_changed'] accepted = text_data_json['accepted'] from_send_message = text_data_json['from_send_message'] users_id = [] users_id.append(owner) users_id.append(conversator) winner_or_looser = text_data_json['winner_or_looser'] try: try: if proposal_identifiant and get_current_proposal(proposal_identifiant): # we create message if proposal exist if accepted == False: update_proposal(proposal_identifiant, last_sender, price, price_is_changed, accepted) create_new_message(proposal_identifiant, sender, messages) else: if from_send_message == True: update_proposal(proposal_identifiant, last_sender, price, price_is_changed, accepted) create_new_message(proposal_identifiant, sender, messages) else: try: create_new_delivery( owner, conversator, proposal_identifiant, type_ad, ad_id, price, accepted, ) create_new_message(proposal_identifiant, sender, messages) winner_or_looser = True except IntegrityError: print("error") return self.send(text_data=json.dumps({ 'error': "IntergyError" })) else: # we create at first … -
Serialize a M-2-M relation with grouping in Django REST framework
I have two models, linked through a separate model as follow: class Project(models.Model): name = models.CharField(max_length=50, unique=True) class Employee(models.Model): name = models.CharField(max_length=50, unique=True) project = models.ManyToManyField( Project, through='Schedule' ) def __str__(self): return self.name class Schedule(models.Model): employee = models.ForeignKey(Employee, on_delete=models.PROTECT) project = models.ForeignKey(Project, on_delete=models.PROTECT) date = models.DateField(null=False) hours = models.IntegerField() Serialized is pretty straight forward: class EmployeeScheduleSerializer(serializers.ModelSerializer): month = serializers.DateField() booked = serializers.IntegerField() class Meta: model = Staff fields = ['id', 'name', 'month', 'booked'] A viewset returns the total number of houses assigned to each employee for different projects, summed over dates: class ScheduleViewSet(viewsets.ReadOnlyModelViewSet): queryset = Employee.objects.all() serializer_class = EmployeeScheduleSerializer lookup_field = 'staff' def get_queryset(self): qs = Employee.objects.values( 'name', month=F('schedule__date') ).annotate( booked=Sum('schedule__hours', distinct=True) ) if self.request.query_params.get('id') is not None: qs = qs.filter(id=self.request.query_params.get('id')) return qs def retrieve(self, request, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), many=True) return Response(data=serializer.data) In the output we have multiple records for each employee: [ { "name": "John Doe", "month": "10/01/2020", "booked": 100 }, { "name": "John Doe", "month": "11/01/2020", "booked": 120 }, ... ] I want to convert it to a nested list so that the booked hours show up as a list for each employee. I checked multiple threads, but couldn't find a reasonable solution. I think it's … -
No Reverse Match at
I try to redirect to question detailView after answer on question but i get NoReverseMatch at /98afdfc7-df41-416c-aaae-c1014bfbf119/answer after entering my answer models class Question(models.Model): id = models.UUIDField(_("ID"), primary_key=True, default=uuid.uuid4, editable=False) question = models.CharField(_("Question"), max_length=300) def get_absolute_url(self): return reverse('question_detail', args=[str(self.id)]) class Answer(models.Model): question = models.ForeignKey(Question, verbose_name=_( "Answer"), on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=255) def get_absolute_url(self): return reverse('question_detail', args=[str(self.id)]) Urls urlpatterns = [ path('<uuid:pk>/answer', AnswerQuestionView.as_view(), name='answer'), path('questions/<uuid:pk>', QuestionDetailView.as_view(), name='question_detail'), ] Views class AnswerQuestionView(CreateView): model = Answer context_object_name = 'answer' fields = ['answer', 'question'] template_name = "forms/answer.html" class QuestionDetailView(DetailView): model = Question context_object_name = 'question' template_name = "question_detail.html" HTML form <form method="post"> {% csrf_token %} {{form.as_p}} <button value="submit">Post</button> </form> -
django: set default locale for language?
I'm building a multilanguage site using modeltranslate, I can switch between languages no problem. The problem comes with 'en' always being interpreted as 'en-us' which messes up the dates everywhere. It's a European site, I want 'en' to be interpreted as international English, or en-gb at least. I've looked all over but can't see a way to do this. Is there any way to set a default locale for a language in Django? Do I need to set language to en-GB and have en-gb in the url? I really don't want to have to do a lot of coding on every template just to override the US date formatting .... LANGUAGE_CODE = 'en-GB' LANGUAGES = ( ('es', _('Spanish')), ('ca', _('Catalan')), ('en', _('English')), ('fr', _('French')), ) Thanks in advance for your help. -
Create userlist page using Django formsets and display profile image in userlist page
I am just beginner to python and Django Trying to create userlist page using Django formsets and display profile image in userlist page. Not seeing image field in my formset. Models – User (from django.contrib.auth.models) models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' # def save(self): def save(self, *args, **kwargs): # super().save() super(Profile,self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (200,200) img.thumbnail(output_size) img.save(self.image.path) forms.py class UserListForm(forms.ModelForm): image = forms.ImageField() class Meta: model = User fields = ['image','username', 'first_name', 'last_name', 'email', 'is_staff', 'is_active', 'is_superuser', 'date_joined'] def __init__(self, *args, **kwargs): super(UserListForm, self).__init__(*args, **kwargs) Views.py def userlist(request): UserFormSet = modelformset_factory(User,form=UserListForm, extra = 0) userlist_form = UserFormSet(queryset=User.objects.select_related('profile')) context = {'userlist_form': userlist_form} return render(request, 'webapp/user_list.html', context) user_list.html {% load crispy_forms_tags %} {% block content %} <div class = "content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom, mb-1 ">User Info</legend> <table id = "usertab" > {% for form in userlist_form %} {% if forloop.first %} <thead> <tr> <th> <label for="id_image"> Image </label> </th> <th> <label for="id_username"> User Name </label> </th> <th> <label for="id_first_name"> First Name </label></th> <th> <label for="id_last_name"> Last Name </label></th> <th> <label for="id_email"> Email Address </label></th> <th> … -
Slack blocks + sending response doesn't work in python, not even when async
Sending block to Slack - it shows on slack correctly. Button is clicked, I am getting the interactive event webhook. webhook returns 200 OK to slack, not before scheduling an async POST to the response_url the return message is posted to response_url AFTER the 200 ack is returned from the webhook function Slack responds 404 to the response_url that same response URL works when curled outside of python.... I don't get why slack rejects the posted return message with 404 when the very same response_url works when used in curl outside of python. my webhook processor: def slack_webhook(request): json_dict = json.loads(request.body.decode('utf-8')) token = json_dict['token'] if 'token' in json_dict else None message = json_dict['message'] if 'message' in json_dict else None trigger_id = json_dict['trigger_id'] if 'trigger_id' in json_dict else None response_url = json_dict['response_url'] if 'response_url' in json_dict else None actions = json_dict['actions'] if 'actions' in json_dict else None for action in actions: print(f"** received action {action['action_id']}") print(f"** response_url: {response_url}") print(f"** trigger_id: {trigger_id}") payload = { "replace_original": True, "text": "Success!", } # async via Celery... send_slack_interactive_response.delay(response_url, payload, trigger_id) return HttpResponse(status=200) the async celery task which sends the @app.task(bind=True, retry_kwargs={'max_retries': 10, 'countdown': 5}) def send_slack_interactive_response(self, response_url, payload, trigger_id): print(f"** -> response_url: {response_url}") print(f"** -> … -
Dynamic choices in model CharField choices
This document shows an example of how to declare a model CharField with choices here class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' YEAR_IN_SCHOOL_CHOICES = [ (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), (GRADUATE, 'Graduate'), ] year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) The list YEAR_IN_SCHOOL_CHOICES is part of the class Student. Does it mean this list is stored somewhere in the database? If so, can it be accessed and modified during runtime? Suppose I need to make this list dynamic depending on another model class. For eg: class Edu_Level(models.Model) level = models.CharField(max_length = 200) Each time my app creates a new Edu_Level, I want to add that level to the choice list in the other Student model. Assuming that they are both in the same app, is this possible? Thanks. -
can't fix: does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import
I am learning django and i was using a video which guides me what to do. I wrote the same code before ,and it worked but now I'm getting this error: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'blog.urls' from 'D:\\python\\pishrafte\\twiter\\twiter\\blog\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. and in urls.py in blog app, I wrote the code: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] What should I do? -
with python django how can i goup by non overlaping 24hour periods starting at first record, where the first record is at least 24huors from the last?
So i am using django and i have Questionnaires, Questions and Responses i need to sort the responses into groups where the session length is up to 24hours (and people are not allowed to answer a question again in 24hours since they started it) I would like response q1 - score 4 - datetime 1/1/20 04:23 response q2 - score 4 response q3 - score 5 - datetime not more than 2/1/20 4:22 then the same questions with a different score at a different time response q1 - score 6 - datetime not before 2/1/20 4:23 response q2 - score 4 response q3 - score 6 - datetiem not more than 24h from first response of second set. -
Django PointField with geography=True can't save data: SQL function error
I have a Django 3.1.2 with GIS extension installed, PostgreSQL 12 and PostGIS 3. In my model I'm trying to use a PointField with geography=True to store real-world coordinates: location = models.PointField(geography=True, srid=4326, blank=False, null=False, verbose_name=_("Lat/Lon coordinates")) In the admin menu I'm using the OSMWidget to enter coordinates: location = forms.PointField(widget=forms.OSMWidget(attrs={'map_width': 800, 'map_height': 500, 'default_zoom': 15})) When this is saved Django runs into the following SQL error: INSERT INTO "challenges_point" ("track_id", "sortkey", "name", "location") VALUES (15, 10, 'Start', ST_Transform(ST_GeogFromWKB('\x...'::bytea), 4326)) RETURNING "challenges_point"."id"; ERROR: function st_transform(geography, integer) does not exist LINE 1: ...", "location") VALUES (15, 10, 'Start', ST_Transfo... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. ST_Transform() is used to transform geometry points (which is used as data type if geography=False is used for the PointField). But I'm not sure what's required to make it work with geography. -
Changing the Default Frontend for Django_filters
I was following through the Dennis Ivy Youtube Django Tutorials and came across a question (https://www.youtube.com/watch?v=G-Rct7Na0UQ&list=PL-51WBLyFTg2vW-_6XBoUpE7vpmoR3ztO&index=13) So the views.py is like this: def customer(request, pk_customer): customer = Customer.objects.get(id=pk_customer) orders = customer.order_set.all() order_count = orders.count() myFilter = OrderFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'customer': customer, 'orders':orders, 'order_count':order_count, 'myFilter':myFilter} return render(request, 'accounts/customer.html', context) and the filters.py is like this: import django_filters from django_filters import DateFilter, CharFilter from .models import * class OrderFilter(django_filters.FilterSet): start_date = DateFilter(field_name='date_created', lookup_expr='gte') end_date = DateFilter(field_name='date_created', lookup_expr='lte') class Meta: model = Order fields = "__all__" exclude = ['customer', 'products'] and lastly the template that shows this part has this line of html code: ... <div class="card card-body"> <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> </div> </div> but what I don't really get is that in the frontend: I don't want the "Date created is greater than or equal to" or "Date created is less than or equal to" to show it like that but maybe change it to a different wording, something like for example just GTE or LTE or stuff like that I couldn't seem to find a way, and is there a way?? -
how to loop through django form errors after getting them as json with ajax
my signup form works fine when there are no errors and saves users correctly but i couldn't display errors when there are form field errors after getting them with form.errors.as_json here is the view of the form: if request.is_ajax(): signup_form = SignupForm(request.POST) if signup_form.is_valid(): signup_form.save() full_name = signup_form.cleaned_data.get('full_name') email = signup_form.cleaned_data.get('email') raw_password = signup_form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return JsonResponse({"success" : True}, status=200) else: return JsonResponse({'success': False},signup_form.errors.as_json() , status=400) here are the ajax stuff in my javascript file: var $signupForm = $('#form-signup'); $signupForm.submit(function (event) { event.preventDefault(); var $signupData = $signupForm.serialize(); $.ajax({ url: "http://localhost:8000", method: 'POST', data: $signupData, success: function() { location.reload() }, error: function () { // display form errors in a div or console.log them // by looping through them }, }); }); with this code when there are field inputs errors like "pasword is too short" or somthing like that i get error status code 500 and: 'str' object is not callable in my django server terminal i checked many question about this but none of them helped and most of them were outdated -
How do i add a photo to a template using the admin panel?
consider this my models.py file. from django.db import models class alldets(models.Model): first_name = models.CharField(max_length=50, default ='first name') second_name = models.CharField(max_length=50, default='second name') school = models.CharField(max_length=50, default='school name') county = models.CharField(max_length=50, default='where from') phone = models.CharField(max_length=20, default='phone number') age = models.IntegerField(default='254') def __str__(self): return self.first_name How do i add a photo just to it then parse it to the views.py and then to the template? -
sqlite3.IntegrityError: NOT NULL constraint failed: store_comment.post_id(Implementing Comment functionality.)
I am getting sqlite3.IntegrityError: NOT NULL constraint failed: store_comment.post_id.Please find the below error details. Django version 3.0.2, using settings 'ShaileshShop.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Checking comment post is happening or not:YES Product in comment post: Black Skater Dress Check Check Check Internal Server Error: /details/3 Traceback (most recent call last): File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: store_comment.post_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Users/shaileshyadaav/djangoshaileshdurga/ShaileshEcomm/store/views.py", line 295, in post new_comment.save() File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save force_update=force_update, update_fields=update_fields) File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/db/models/base.py", line 784, in save_base force_update, using, update_fields, File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/db/models/base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_insert using=using, raw=raw, File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), … -
Page not found error on django when try to upload image
In my Django project, I am trying to register a student. When I submit the registration form on the live server I got a Page not found (404) error. But it working perfectly on my local server. I think I got this problem for upload image because when I try to submit another form without any image it saves on the database perfectly. This is the exact error I got. Page not found (404) Request Method: POST Request URL: https://xxxxx.com/accounts/registration/student/ Raised by: accounts.views.register_student Using the URLconf defined in coaching.urls, Django tried these URL patterns, in this order: ad/ accounts/ students/ teachers/ admin/ vedios/ [name='landingpage'] error [name='error_page'] ^media\/(?P<path>.*)$ The current path, registration/student/, didn't match any of these. This is the URL patterns related to this problem from django.urls import path,include from accounts import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('registration/student/', views.register_student, name='student_registration'), path('registration/teacher/', views.register_teacher, name='teacher_registration'), path('login/', views.login_view, name='login'), path('logout/',views.logout_view,name="logout") ] And this the view's method for that I got this error. def register_student(request): context={} if request.POST: form = RegistrationForm(request.POST,request.FILES) if form.is_valid(): user = form.save(commit=False) user.is_student = True user.save() # login(self.request, user) return redirect('login') else: context['form'] = form else: form = RegistrationForm() context['form'] = form return …