Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compare field in the table and calculated field in django-orm
I calculated one variable using the annotate and now i want to compare it with the existing field. So how can I do that? -
How we will count the User?
class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile_number = models.IntegerField() cnic = models.CharField(max_length=13) blood_group = models.CharField(max_length=10) last_donation = models.DateTimeField(auto_now_add=True) class Donation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'donation') donation_count = models.IntegerField(default= 1) First time user will come and donate blood Ok but now the condition is that existing user can donate Blood after 3 months. Now I have to check that which user donate blood how many times How I can Count the user I searched too much but didn't find anything related to this Can anyone help me I have Two models. Thanks in advance -
Spanning multi-valued relationship
Spanning multi-valued relationships When spanning a ManyToManyField or a reverse ForeignKey (such as from Blog to Entry), filtering on multiple attributes raises the question of whether to require each attribute to coincide in the same related object. We might seek blogs that have an entry from 2008 with “Lennon” in its headline, or we might seek blogs that merely have any entry from 2008 as well as some newer or older entry with “Lennon” in its headline. To select all blogs containing at least one entry from 2008 having “Lennon” in its headline (the same entry satisfying both conditions), we would write: Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008) Otherwise, to perform a more permissive query selecting any blogs with merely some entry with “Lennon” in its headline and some entry from 2008, we would write: Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008) Suppose there is only one blog that has both entries containing “Lennon” and entries from 2008, but that none of the entries from 2008 contained “Lennon”. The first query would not return any blogs, but the second query would return that one blog. (This is because the entries selected by the second filter may or may not be the same as the entries in the first filter. We … -
How to provide seekable/scrubbable audio to frontend using Django
I'm trying to provide audio to the HTML Django template, originally I tried like this: <audio id="audio" src="{{audio_path}}" controls></audio> This was sufficient to get audio playing on the website with pause/play, speed up/down, volume up/down but the user was not able to move the progress bar at all, it either froze, or returned to the starting position. I did lots of searching and found many things that claimed to enable seeking/scrubbing, but none of them have worked. Currently my code is as follows, first the audio API view: class AudioFetchView(View): def get(self, request, audio_id, *args, **kwargs): audio_file = UploadAudio.objects.get(pk=audio_id) response = StreamingHttpResponse(content_type='audio/mpeg') response['Content-Disposition'] = 'attachment; filename=%s' % audio_file.path response['Accept-Ranges'] = 'bytes' response['X-Sendfile'] = audio_file.path return response audio_fetch = AudioFetchView.as_view() Then the HTML: <audio id="audio" crossOrigin="anonymous" preload="auto" src="{{audio_fetch_url}}"></audio> Now the audio is not able to be played at all, the error message is: "Uncaught (in promise) DOMException: The element has no supported sources." Does anyone know how to correctly provide an .mp3 file to the frontend in a way that allows scrubbing/seeking? -
How to register a device on FCMDevice of fcm-django?
I'm a beginner at Django. Referring to this link, I installed fcm-django and finished setting. fcm-django doc Install fcm-djagno. pip install fcm-django Setting fcm-django on settings.py. import firebase_admin from firebase_admin import credentials cred_path = os.path.join(BASE_DIR, "serviceAccountKey.json") cred = credentials.Certificate(cred_path) firebase_admin.initialize_app(cred) ... INSTALLED_APPS = [ ... 'fcm_django', ] ... FCM_DJANGO_SETTINGS = { # default: _('FCM Django') "APP_VERBOSE_NAME": "django_fcm", # Your firebase API KEY "FCM_SERVER_KEY": "AAAAsM1f8bU:APA91bELsdJ8WaSy...", # true if you want to have only one active device per registered user at a time # default: False "ONE_DEVICE_PER_USER": False, # devices to which notifications cannot be sent, # are deleted upon receiving error response from FCM # default: False "DELETE_INACTIVE_DEVICES": True, } And, when I post notice, if push is active, I try to send push notifications to all devices. from firebase_admin.messaging import Message, Notification from fcm_django.models import FCMDevice class noticeCreateView(View): def post(self, request, *args, **kwargs): title = request.POST.get('title') content = request.POST.get('content') push = request.POST.get('push') if push: message = Message( notification=Notification( title=title, body=sentence, ), ) try: devices = FCMDevice.objects.all() devices.send_message(message) except Exception as e: print('Push notification failed.', e) return HttpResponseRedirect(reverse('notice_list')) What I am curious about is whether data is automatically added in the FCMDevice model when the user installs this app. If I … -
Django - advanced search
I need to apply advanced search filters to my database to search effectively. I use Django and PostgreSQL. Some things in my list of "advanced search filters": In default behaviour, it's going to ignore stop words, such as "a", "the", and "is" Searching for exact phrases by enclosing text in "" Since this is a website where books are uploaded, books written by a specific author Books for a certain age group Books in a certain genre If I get all of these from within regular expressions, how am I supposed to search for them? I think I can think of how to do all of these, but I just wanted to know of a way to do it without using a list of stop words and try not to consider them or something like that. Is there any feature in Django that can help me to these effectively and with relatively less effort? -
Sum of field in a consecutive period based on a condition
I did this without complicated query and with Python. But I'm looking for a way to do this with Django ORM. I have a table as follows: user date point Mary 2022/01/04 13 John 2022/01/04 10 Mary 2022/01/03 0 John 2022/01/03 5 Mary 2022/01/01 1 John 2022/01/01 1 Mary 2021/12/31 5 I want to calculate the Sum of points from now() to the date when the point value is greater than one. Desired Output: user sum Mary 14 13+1 John 10 10 -
Not able to post data in database through django model forms
I have been trying to create a contact us form and not been able to post data to the database . I have tried the print function and that gives all the inputs. I have tried almost everything around but not able to solve this. After clicking submit, the page just refreshes but nothing is added in the database. Please help!!! Models.Py from django.db import models from datetime import datetime # Create your models here. class Contact(models.Model): name = models.CharField(max_length=200) email = models.EmailField(max_length=255) subject = models.CharField(max_length=200) message = models.TextField(max_length=1000) contact_date = models.DateTimeField(auto_now=True) def __str__(self): return self.name Forms.py from django import forms from .models import Contact class ContactUsForm(forms.ModelForm): class Meta: model = Contact fields = ['name','email','subject','message'] widgets= { 'name': forms.TextInput(attrs={'class': 'form-control form-control-light',}), 'email': forms.EmailInput(attrs={'class': 'form-control form-control-light',}), 'subject': forms.TextInput(attrs={'class': 'form-control form-control-light',}), 'message': forms.Textarea(attrs={'class': 'form-control form-control-light',}), } Views.py from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponse, HttpResponseRedirect from .forms import ContactUsForm from .models import Contact # Create your views here. def index(request): if request.method == 'POST': form = ContactUsForm(request.POST) if form.is_valid(): form.save messages.success(request,"Plan created successfully.") return redirect(request.path) return render(request, 'pages/index.html',{'form':form}) else: form = ContactUsForm() return render(request, 'pages/index.html', {"form":form}) HTML <div class="col-md-8"> <form action="." method="POST"> {% csrf_token %} <div … -
wagtail upload file - InMemoryUploadedFile
I'm using wagtail form to save form data but when I upload file I get message error : Object of type 'InMemoryUploadedFile' is not JSON serializable the def of save I'm using is def serve(self, request, *args, **kwargs): if request.method == 'POST': recaptcha_response = google_captcha_validate(request) form = self.get_form(request.POST, request.FILES, page=self, user=request.user) if form.is_valid() and recaptcha_response.get('status'): if request.FILES['uploadcv']: myfile = request.FILES['uploadfile'] fs = FileSystemStorage(location='media/documents') filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) print(form) form_submission = self.process_form_submission(form) return JsonResponse({'success': True}) -
Multi Algoritms Precentage
I am making heart-disease-system. My question is how to improve my code, and show not only 0 - for none-risk and 1 - for having heart disease. Here is my view.py if form.is_valid(): features = [[ form.cleaned_data['age'], form.cleaned_data['sex'], form.cleaned_data['cp'], form.cleaned_data['resting_bp'], form.cleaned_data['serum_cholesterol'], form.cleaned_data['fasting_blood_sugar'], form.cleaned_data['resting_ecg'], form.cleaned_data['max_heart_rate'], form.cleaned_data['exercise_induced_angina'], form.cleaned_data['st_depression'], form.cleaned_data['st_slope'], form.cleaned_data['number_of_vessels'], form.cleaned_data['thallium_scan_results']]] standard_scalar = GetStandardScalarForHeart() features = standard_scalar.transform(features) SVCClassifier,LogisticRegressionClassifier,NaiveBayesClassifier,DecisionTreeClassifier=GetAllClassifiersForHeart() predictions = {'SVC': str(SVCClassifier.predict(features)[0]), 'LogisticRegression': str(LogisticRegressionClassifier.predict(features)[0]), 'NaiveBayes': str(NaiveBayesClassifier.predict(features)[0]), 'DecisionTree': str(DecisionTreeClassifier.predict(features)[0]), } pred = form.save(commit=False) l=[predictions['SVC'],predictions['LogisticRegression'],predictions['NaiveBayes'],predictions['DecisionTree']] count=l.count('1') result=False if count>=2: result=True pred.num=1 else: pred.num=0 pred.profile = profile pred.save() predicted = True colors={} if predictions['SVC']=='0': colors['SVC']="table-success" elif predictions['SVC']=='1': colors['SVC']="table-danger" if predictions['LogisticRegression']=='0': colors['LR']="table-success" else: colors['LR']="table-danger" if predictions['NaiveBayes']=='0': colors['NB']="table-success" else: colors['NB']="table-danger" if predictions['DecisionTree']=='0': colors['DT']="table-success" else: colors['DT']="table-danger" if predicted: return render(request, 'predict.html', {'form': form,'predicted': predicted,'user_id':u_id,'predictions':predictions,'result':result,'colors':colors}) else: form = Predict_Form() return render(request, 'predict.html', {'form': form,'predicted': predicted,'user_id':u_id,'predictions':predictions}) ipynb of all algorithms shows accuracy in precentage, but when i am making predict it shows 1 or 0, I need to show accuraccy like for example: Linear Regression: 75% (if more than 70% it is red, else green) -
Installing psycopg2 on M1
First of all, I know there are many similar questions already out there on SO. But none of them are working for me. I'm using a 2020 Macbook Air with an Apple M1 chip installed. I need psycopg2 to run my postgres Django database. psycopg2 just isn't installing, how many ever times I install lipq or openssl via homebrew or installing only psycopg2-binary: nothing's working. I'm doing all of this inside my conda virtual environment, if that's going to help you. Do you know what might help me? -
How to retrieve results that match any terms using PostGres SearchQuery in Django 3
I'm using SearchQuery and Search Vector in Django 3 to search for articles that are in a PostGres database. Assume my database has five articles entitled as follows: Eating salmon reduces risk of heart attacks How to avoid the flu Healthy hearts and Cheerios Salmon and cancer Staying warm with scarves If I enter a query of: "salmon to prevent heart disease", I would expect to get search results in the following order: 1 (because both "salmon" and "heart" appear), 4, 3 (though I don't care about whether 4 ranks higher than 3 as long as they both appear), and I would expect 2 and 5 not to appear at all. But with the following code, no results appear. Results would only appear for 1 if I type in "salmon heart", but even 1 doesn't appear if I add any words that don't appear in the title. How can I modify the code so the search results will match my expectations set out above? search_query = "salmon to prevent heart disease" vector = SearchVector('title') query = SearchQuery(search_query, search_type='websearch') search_results = Article.objects.annotate(search=vector).filter(search=query) -
I want to search ip address in data table
I have a data table with columns ipaddress with subnet mask and belongs to project1. I have a data in DB something like this i want to render rows on webpage of given ip address. expected output something like below -
Django how to upload files to different directores based on dropdown list option from templates
I am new to Django,I want to save the uploaded files to directories based on dropdown list values from templates,and my code as below, 1:models.py: def user_directory_path(request,*args,**kwargs): need_selection = request.POST.get('need_selection') return need_selection class Document(models.Model): docfile = models.FileField(upload_to=user_directory_path) 2:home.html: <div class="row" style="top:0;margin-left:50px;right:0;"> <div class="column" style="width:30%;margin-left:200px;border:2px solid red;margin-top:40px;"> <br> <p style="font-size:30px;color:red;margin-left:200px">please uploads files</p> <br> <form method="POST" id="fileupload" enctype="multipart/form-data" style="font-size:30px"> {% csrf_token %} please choose your requirement: <select form='fileupload' name="need_selection" id="need-selection" style="font-size:20px" required> {% for request_item in request_lst %} <option>{{request_item}}</option> {% endfor %} </select> <br> <br> <input form='fileupload' type="file" name="docfile" style="font-size:30px;color:red"> <br> <br> <button type="submit" style="font-size:30px;margin-left:0px">Upload</button> <br> <br> <br> </form> </div> 3:views.py def home(request): if request.method == 'POST': newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return redirect('home') request_lst = ['request1','request2','request3','request4'] context = { 'request_lst': request_lst } return render(request, 'myapp/templates/home.html',context=context) but,it doesn't work. can anyone help me? thanks. -
Django - i always get my profile when i what to view another users profile
Whenever i tried to view other people profile, it always return my own profile again, i don't really know what's wrong and i have tried calling request.user but it seems not to work views.py def UserProfile(request, username): user = get_object_or_404(User, username=username) profile = Profile.objects.get(user=user) url_name = resolve(request.path).url_name context = { 'profile':profile, 'url_name':url_name, } return render(request, 'userauths/profile.html', context) urls.py main project from userauths.views import UserProfile urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('userauths.urls')), path('<username>/', UserProfile, name='profile'), ] index.html {% for creator in creators %} <a href="{% url 'profile' creator.user %}"><img class="avatar-img rounded-circle" src="{{creator.user.profile.image.url}}" alt="creators image" ></a></div> <h5 class="card-title"><a href="{% url 'profile' creator.user %}"> {{creator.user.profile.first_name}} {{creator.user.profile.last_name}} {% if creator.verified %} <i class="bi bi-patch-check-fill text-info smsall" ></i> {% else %}{% endif %} </a></h5> <p class="mb-2">{{creator.user.profile.bio}}</p></div> {% endfor %} -
How to store and retrieve unstructured SQL primitive key value pairs in Python?
I have some unstructured key value pairs I eventually want to store in a PostgreSQL database using the Django framework. The data are typed using primitive SQL types, so this seemingly sounds trivial. For example: data = { "name": "bob", "size": Decimal("173.4"), "logged_in_at": datetime.now() } However, I can not just create a Model and a table for it because the data are unstructured and can have any field name. (I can ensure though that the name adheres to both Python and SQL syntax rules.) I cannot use JSONField or JSON in general because it cannot process datetime and Decimal reliably. I'm could use a BinaryField to store pickle data but dread the security implications. I could dynamically create serializers for Django REST framework and the related models but dread the necessary abstract meta voodoo and how to deal with changes in the underlying data models during runtime. I took a quick look at MessagePack, it seems to have the same issues as JSON. Protocol Buffers at least have a Timestamp type but do not have a decimal type. Applying ye olde "represent decimals as integers" trick would lose type information and make integer indistinguishable from decimals. Because this is only … -
Why am I getting this error when I try to switch HTML pages
I made basic HTML/CSS files, that I'm trying to run through Django, but every time I run it and try to switch pages, I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about.html Using the URLconf defined in test.urls, Django tried these URL patterns, in this order: admin/ [name='main'] add [name='about'] The current path, about.html, didn’t match any of these. Here's what that my .urls file looks like: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('add',views.about,name='main.html'), path('add',views.about,name='about.html') ] Here's my .views file looks like: from django.shortcuts import render def main(request): return render(request,'main.html') def about(request): return render(request, 'about.html') Lastly Here's the section of my Settings file that I modified to find the file: 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, Is there something else I'm supposed to do to make this work? -
Proper setup of Django with sqlAlchemy?
I have been surfing the web for 3-5 days looking for a proper answer to this solution. I see lots of code for Flask but none for Django to answer my question. Perhaps this is because Django has a built-in ORM, and if it would be considered odd to use SqlAlchemy with Django, I'd like to be made aware of that. It would be a high ranking answer for me personally. The question is: what is the best way (or even one way) to set up Django with sqlAlchemy? I want to: House the initialization of the database in one file if and only if that is what you do in sqlAlchemy to avoid bugs. Keep my database models only in one file, exporting them and then importing into the file(s) where I need them. I do not want to use Aldjemy as seen here. I'm doing this to learn Django An example ideal file structure, this is how i think it should look: ..mysite ....someAppName ......db ......-db.py ......-models.py ....__init__.py ....admin.py ....apps.py ....models.py <-- maybe models should go here, but where to export the db connection from? ....tests.py ....urls.py ....views.py Currently in db/db.py I have: from sqlalchemy import Table, Column, … -
CSRF verification failed behind Route 53
I have a dockerized Django app that utilizes Gunicorn and Nginx. When logging in on the admin page using localhost, no CSRF error emerges. When running the docker on Amazon EC2 with Route 53 as the proxy server (https redirects to http), I get the CSRF error on login. I note the following in my settings.py file (I added the SECURE_SSL_REDIRECT = False but it has had no effect): ALLOWED_HOSTS = ['localhost', '.website_name.ca'] SECURE_SSL_REDIRECT = False # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'The6ixDjango.apps.The6IxdjangoConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Given that I have Route 53 on the front-end, is it 'safe' to remove the csrf middleware reference in the MIDDLEWARE list? -
Django how to add many to many with bulk_create
this are my models: class MyShop(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile_shop') company_name = models.CharField(max_length=150) shop_commision = models.IntegerField(default=5) class OrderItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) shop = models.ForeignKey(MyShop, related_name='shop_order', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) size = models.CharField(max_length=5, null=True, blank=True, ) item_comission = models.IntegerField(default=5) class ShopInvoice(models.Model): shop = models.ForeignKey(MyShop, related_name='shop_invoice', on_delete=models.CASCADE) month = models.DateField() year = models.DateField() items = models.ManyToManyField(OrderItem, related_name='items') total = models.DecimalField(max_digits=10, decimal_places=2) this is my function:I use a cron job and this function to create an object for each user shop every month but items are not added to the object class Command(BaseCommand): help = 'Generate invoice monthly for shops' def handle(self, *args, **kwargs): month_inv = MyShop.objects.all() for invoice in month_inv: shop_invoice = invoice.shop_order.all().annotate(year=TruncYear('created'), month=TruncMonth('created')).values( 'month', 'year', 'shop_id' ).annotate(total=Sum(ExpressionWrapper( (F('item_comission') / 100.00) * (F('price') * F('quantity')), output_field=DecimalField())), ).order_by('month') ShopInvoice.objects.bulk_create([ ShopInvoice(**kv) for kv in shop_invoice if not ShopInvoice.objects.filter( shop_id=kv['shop_id'], month=kv['month'], year=kv['year'] ).values_list('shop_id', 'month', 'year').exists() ]) -
Django: Could not find the GDAL library (OSX)
After my old macbook died I am transferring across a Django Webapp I'd been building to my new machine. I am currently in the process of reinstalling the correct packages and extensions for the app. However I am currently getting the following error when I do python3 manage.py runserver: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.3.0", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. The database I created was through a server on Postgres.app which I believe comes packaged up with PostGIS, GDAL etc. I have tried following the geoDjango documentation and I added the following in the terminal: export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/14/bin When I run which psql it returns: /opt/homebrew/bin/psql Is this a conflict between a homebrew and Postgres.app installation or something? I can't figure it out. Full traceback of error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File … -
Instantiating dependencies (e.g. service clients) in Django
A Django API view calls another service. To call that service, the view needs a client. I'd like to initialize globally an instance of the client and pass that instance to the view. Also, for tests, I'd like to be able to easily mock the client. I can do some terrible hacks (hey, with Python everything is possible!) but I'd like to do it in Django-idiomatic way. I tried as_view(**initkwargs) and passing the instance of the client. The drawback is that in tests I need to modify class variable (and not instance variable, which seems more correct), and also I need to instantiate the client in urls.py which doesn't look like a right place to instantiate such clients (dependencies). I considered having a separate Application in INSTALLED_APPS, but it seems like an overuse of what an Application should do. In my case, the App would only run AppConfig.ready() and would initialize the client for later access by a view. A simple Dependency Injection would do, but I don't want to overcomplicate that, if Django supports equivalent functionality. Where should I initialize such dependencies in Django, and how to later mock them in tests? -
Why reply to the comment is not displaying? Python Django
Everything else seems to work but cannot see the reply to the comment. Please help MODELS: class Comment(models.Model): """ comments for Post model """ comment_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comment_for_post', null=True, default='') comment_text = models.TextField(null=True) date_posted = models.DateTimeField(auto_now=True) def get_absolute_url(self): """ Reverse the Comment to the url once action has been taken with primary key to direct back to details page """ return reverse('posts:post_details', kwargs={'pk': self.pk}) def __str__(self): return self.comment_text class Reply(models.Model): """ add reply to commnets """ reply_comment = models.ForeignKey( Comment, on_delete=models.CASCADE, null=True, default='', related_name='comment_reply') reply_text = models.TextField() date_posted = models.DateTimeField(auto_now=True) def __str__(self): return self.reply_text VIEWS: @login_required def reply_to_comment(request, pk): comment = get_object_or_404(models.Comment, pk=pk) if request.method == 'POST': form = forms.ReplyCommentForm(request.POST) if form.is_valid(): reply = form.save(commit=False) reply.reply_comment = comment reply.save() return redirect('posts:post_details', pk=comment.pk) else: form = forms.ReplyCommentForm() return render(request, 'posts/reply_comment_form.html', context={'form': form}) URLS: urlpatterns = [ path('post_list/', views.PostListView.as_view(), name='post_list'), path('user/str:username/', views.UserPostListView.as_view(), name='user_posts'), path('create/', views.PostCreateView.as_view(), name='create'), path('details/int:pk/', views.PostDetailView.as_view(), name='post_details'), path('delete/int:pk/', views.PostDeleteView.as_view(), name='post_delete'), path('update/int:pk/', views.PostUpdateView.as_view(), name='post_update'), path('str:category/', views.CategoryPostListView.as_view(), name='category_posts'), path('posts/int:pk/comment', views.add_comment_to_post, name='post_comment_list'), path('delete_comment/int:pk/', views.CommentDeleteView.as_view(), name='delete_comment'), path('comment/int:pk/reply/', views.reply_to_comment, name='reply'), TEMPLATE: <div class='container'> {% for reply in comment.comment_reply.all %} <br> {% if object.author == user %} <div class=""> <ul> <li> <p >{{reply.reply_text}}</p> <p class='text-capitalize'>From {{user.username}} on {{comment.date_posted|date:'d-M-y'}}.</p> </li> </ul> </div> {%else %} <div class=""> … -
SystemCheckError: System check identified some issues: Django
from mptt.models import MPTTModel, TreeForeignKey from django.contrib.auth.models import User from django.db import models class CategoryTask(MPTTModel): """Модель категорий заданий""" title = models.CharField("Название", max_length=200, unique=True) parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) slug = models.SlugField(max_length=200, unique=True) mastery_need = models.FloatField("Требуется мастерства", default=0) points_need = models.FloatField("Требуется балов", default=0) def __str__(self): return self.title class MPTTMeta: order_insertion_by = ['title'] class Meta: verbose_name = "Категория задания" verbose_name_plural = "Категории заданий" class DCTask(models.Model): category = models.ForeignKey(CategoryTask, verbose_name="Категория", on_delete=models.CASCADE) mastery_need = models.FloatField("Требуется мастерства", default=0) points_need = models.FloatField("Требуется балов", default=0) mastery = models.FloatField("Получит мастерства", default=0) points = models.FloatField("Получит балов", default=0) title = models.CharField("Название", max_length=200) description = models.TextField("Описание") slug = models.SlugField(max_length=200, unique=True) users = models.ManyToManyField(User, verbose_name="Взявшие", blank=True) def __str__(self): return self.title class Meta: verbose_name = "Задание" verbose_name_plural = "Задания" class AnswerDCTask(models.Model): user = models.ForeignKey(User, verbose_name="Пользователь", on_delete=models.CASCADE) task = models.ForeignKey(DCTask, verbose_name="Задание", on_delete=models.CASCADE) answer = models.TextField("Ответ") result = models.BooleanField("Сдано?", default=False) check = models.BooleanField("На проверке", default=False) verifiers_y = models.ManyToManyField( User, verbose_name="Проверяюще за", related_name="users_check_y", blank=True ) verifiers_n = models.ManyToManyField( User, verbose_name="Проверяюще против", related_name="users_check_n", blank=True ) count_check = models.IntegerField("Общее за", default=0) mentor = models.ForeignKey( User, verbose_name="Ментор", on_delete=models.CASCADE, blank=True, null=True, related_name="user_mentor" ) created = models.DateTimeField("Взято", auto_now_add=True) over = models.DateTimeField("Сдано", blank=True, null=True) def __str__(self): return "{} - {}".format(self.user, self.task) class Meta: verbose_name = "Взятое задание" verbose_name_plural … -
django - i want to redirect to the profile page after a user edits thier profile
when a user finish updating thier profile i want to redirect them back to the profile page but it keeps showing that Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['(?P<username>[^/]+)/$'] i have tried making my views redirect but it now. views.py def profile_update(request): Profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('profile') else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, 'userauths/profile_update.html', context) urls.py main project dir from userauths.views import UserProfile urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('userauths.urls')), path('<username>/', UserProfile, name='profile'), ]