Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-tables pagination per_page not working as expected
I have a django-tables2 table with pagination via the RequestConfig class. I am trying to limit the results per page to 250 at max, to reduce database load and to keep the table organized. This is my code to limit the per_page GET parameter. def overview(request): # limit results per page to 250 results_per_page = 25 try: results_per_page = int(request.GET.get('per_page')) if request.GET.get('per_page') is not None else 25 sanetized_results = results_per_page if results_per_page <= 250 else 250 results_per_page = sanetized_results except: results_per_page = 25 pass # Create the pagination # BREAKS HERE RequestConfig(request, paginate={'per_page': results_per_page }).configure(table) The first part of the code works. however, at the RequestConfig it still uses the old per_page from the URL. Am I missing something? -
Django detective spots POST requests
I installed django-detective last night and today there are many weird post requests in it. It looks like somebody is trying to post stuff like this on my website: /wp-admin/admin-post.phpnd_stats_value_import_settings=home[nd_stats_option_value]https://jackielovedogs.com/pret Please do not go to this link as I think it might be hosting malware !! What does this mean? How can I prevent this from happening? Thank you -
uwsgi with Django, why have a system wide installation of uwsgi, and how does it integrate with sourcecode?
PS, before someone says it should be posted in serverfault/superuser/swengineering/etc/etc... I just read the descriptions of the related stack exchange websites (https://stackexchange.com/sites), and Stack overflow bests describe me, a programmer, not server maintainer, nor a sw development lifecycle something or other. Additionally, all the related questions I have been reading to do with uwsgi I have been reading are her on SO. Yes this question does not have code, but is related to my codebase. I have tried asking a related question before, only to get told to put it on another site, then on the other side told to put it back on the other site. Sorry, now that is out the way... The question... I have followed the official uwsgi docs to successfully deploy a nginx/uwsgi/django stack. The step I don't understand why is: Install uWSGI system-wide Why does one need to install it system wide for deployment? Why cant the deployment just call my virtual env? If I need the system wide installation, why do I need the virtual env version of uwsgi (is it only for dev purposes)? I dev on a different machine, and use djangos dev server to test with, so I don't need … -
Django How to pass instance to view
I can't find out how to do this, I have a list view, that when you click on one of the list objects, it takes you to an update page, but I can't work out how you pass the instance so to it so that and data posted goes to that instance on the database. CBV do this automatically in a hidden black box way, and I can't see how it is done for a function based view. Model class Project(models.Model): date_published = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=64) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def __str__(self): return self.title Form class ProjectUpdateForm(forms.ModelForm): class Meta: model = Update fields = [ 'project', 'category', 'update' ] View def project_update_view(request, slug): obj = Project.objects.get(slug=slug) form = ProjectUpdateForm(request.POST or None) if form.is_valid(): form.save() context = { "form": form, "object": obj } return render(request, 'project_portal/project_update.html', context) url: path('<slug:slug>/update/', project_update_view, name='project-update'), So I want to be able to do away with the 'project' field in the Form because the user is already looking at that instance he shouldn't have to then pick it in the form. -
What do errors "init_1 marked as not fetchable", or "Tensor embedding_2_input:0 not found in graph" mean?
I am using CNNSequenceClassifier from sklearn-sequence-classifiers for sequence prediction. The problem is I have been running into these two errors in a weird kind of way: Tensor embedding_2_input:0, specified in either feed_devices or fetch_devices was not found in the Graph Operation 'init_1' has been marked as not fetchable. The second one happens when I refresh the page and execute the code again (by the way, the whole thing is within a django project) I say weird because my code has two prediction parts. When I run the first one and then the second, the errors do not arise. But when I do the opposite these errors show up. I have searched a lot and there are rare information on solutions people have suggested. And the ones that have been marked helpful are totally different from the structure of my code's prediction. Basically I have no clue what these errors are referring to. Here's what's happening inside the codes (they are functions inside the views.py): from django.http import JsonResponse from django.db.models import Max, Min, Sum, Avg, Q from datetime import timedelta, date import datetime import jdatetime import json import math import numpy as np import operator import shelve import os from … -
Intermittent 500 error when inserting into MySQL from Python Flask App
I keep getting a 500 issue when inserting data into MySql DB. I know when the issue occurs but can't figure out why. When I insert data (e.g. new user) into my DB, I can see it has been inserted correctly from MySql Workbench but about 50% of the time when I call the data thats just been inserted, it returns None After I restart uwsgi (service uwsgi restart) and use the app again, it works as expected until I add some more data then the issue occurs again but only for data inserted after the restart. The app works as expected when running on my local windows machine. Would really appreciate any help on this before my head explodes! This is for a new CentOS 7 Linux server using MySql 8, Python 3.7. I have tried this with 3 different databases with the same result. I have rebooted the server and uwsgi. To recreate, I made testuser@test.com which is correct when getby_email function is called. Basically when the query asks the database for a user with that email, its randomly returns 'None' even though I can see on MySql workbench that the user is in the database. Then when … -
Django: Peer authentication failed for user
I've already a functioning website that use sqlite3 but I prefer to restart my website project with an empty project that immediately use PostgreSQL/PostGIS. At the end of the configuration of settings.py I will make a dump for upload all the sqlite3 tables into the new DB. Nobody models of the old project will modify into this new project. The differece between the old and the new project is only the DBMS. This is settings.py: INSTALLED_APPS = [ ... 'django.contrib.gis', ] ... DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'my_project_name', 'USER': 'db_user', 'PASSWORD': 'password_of_db_user', } } After this I've tried to test the server with python3 manage.py runserver but I see this error message: django.db.utils.OperationalError: FATAL: Peer authentication failed for user "db_user" I'm sure that NAME, USER and PASSWORD are correct, the db is in localhost. I've created, a couple of week ago, another simple project to learn GeoDjango with this same settings and that website run fine. -
ImageField not validating
Why isn't Django's ImageField throwing a validation error here? # field in model image_mobile = ImageField( upload_to='static/images/', blank=True, null=True ) # in test from django.core.files.uploadedfile import SimpleUploadedFile attachment = SimpleUploadedFile("file.mp4", b"file_content", content_type="text/plain") obj.image_mobile = attachment obj.save() self.assertEqual(obj.image_mobile, '') Outputs this: AssertionError: <ImageFieldFile: static/images/file_7wanB5P.mp4> != '' From the documentation: Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image. -
GET ERROR 500 (Internal Server Error) AJAX DJANGO
I try to achieve a method that when I click the button, the webpage can show different views(based on which button I click). But after I run the server, I get this: jquery.min.js:4 GET http://127.0.0.1:8000/sheet/?Page_1=Page_1 500 (Internal Server Error) I created button divs and used ajax. So if I click Page_1/Page_2/Page_3, the webpage can show up different content. I initial variables Page_1/2/3 and sent them back to Django. In the Django, I will compare data. If they are matched, it will jump to the desired html file web.html .... <button id="Page_1">customer</div> <button id="Page_2">mobile</div> <button id="Page_3">meeting</div> <script type="text/javascript"> $(document).ready(function(){ var id="Page_1" $("#Page_1").click(function(){ $.ajax({ url:"{% url "sheet" %}", data:{Page_1:id}, success:function(result){$("#vizContainersk").html(result);} }); }); }); .... the rest of ajax are same as above one. view.py .... @api_view(['GET']) def get_tableau_url(request): return render(request, 'web.html') def sheet(request): url ='http://xx.xx.xxx.xx:8000/trusted?username=some_name&target_site=demo' result = requests.post(url, timeout=15) context={} context['token'] = result.text q1 = request.GET.get('Page_1') s1 = "Page_1" q2 = request.GET.get('Page_2') s2 = "Page_2" q3 = request.GET.get('Page_3') s3 = "Page_3" if (q1 == s1): return render(request, 'sheet0.html', context) if (q2 == s2): return render(request, 'sheet1.html', context) if (q3 == s3): return render(request, 'sheet2.html', context) I except to solve Internal Server Error -
os.system(inpsectdb) runtime doesn't not create model
To my problem: I need to create a model during runtime. We create new database and fill them with tables and information. After that we need to create the model for the database. I do that with the following code: os.system("python3 D:/django/alpha/manage_inspectdb.py inspectdb --database realtest > D:/django/alpha/api_manager/schemas/realtest.py") When I run the command in program I get an empty realtest.py file. When I run the command on command line I get the expected result a realtest.py with all the generated classes. I found out that this does work when i run it on my local Computer. As soon as i try to push it in deployment i doesnt work anymore. In deployment i have Apache Server with Python and Django all up-to-date. -
How to hide a button if the user don't have permission?
I'm working as an intern for a company on GeoNode 2.8. I have to hide the Download Layer button if the user is not in the permission list. The previous intern made it in an older version of Geonode by adding a {% get_obj_perms request.user for resource.layer as "perms" %} before the button display function. But when I add it on my version of GeoNode, it didn't change anything and the button still there. {% if resource.storeType != "remoteStore" %} {% get_obj_perms request.user for resource.layer as "layer_perms" %} <li class="list-group-item"> {% if links or links_download %} <button class="btn btn-primary btn-md btn-block" data-toggle="modal" data-target="#download-layer">{% trans "Download Layer" %}</button> {% else %} {% if request.user.is_authenticated %} <button class="btn btn-primary btn-md btn-block" id="request-download">{% trans "Request Download" %}</button> {% endif %} {% endif %} </li> {% endif %} -
What is The Standard Way to Structure Django Rest urls
I have a project in which I have several app: project/app1 project/app2 In those apps exist views for which I want to have basic CRUD. So the usual way for the urls is to use routers. app1/api/views: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer So far so good. I register a router under this path: project/urls.py But, if I want to add other views under app1, I don't know how to structure the urls. Let's say I want to list reviews about a specific book: class TestAssesment(ListCreateAPIView): def get_queryset(self): queryset = BookReviews.objects.filter( book_id=self.kwargs["pk"]) return queryset serializer_class = BookReviewSerializer The url I'm seeking is: books/<int:id>/reviews/ Where and how should I put this url? Shoud I dismiss the router inside project/urls.py and replace it with path('books/', include('books.api.urls')) and handle all the related urls there? What is the cleanest way to structure URLs in such cases? -
How to style django-allauth Template?
I'm new in Django, so i don't know how to give style to my templates. I had read the Allauth official Docs but i don't understand how to style them? i had downloaded the templates from github and did all the dir settings. and now its working. this is my login template which i have to convert into django allauth template. <div class="container"> <div class="col-sm-10 main-section ml-auto mr-auto"> <div class="card text-center shadow p-0 mb-0"> <div class="card-header"> <ul class=" nav nav-tabs card-header-tabs"> <li class="nav-item ml-auto"> <button type="button" class="close nav-link" aria-label="Close" > <span aria-hidden="true"><a href="index.html">&times;</a></span> </button> </li> </ul> </div> <div class="card-body"> <div class="modal-content"> <form class="col-sm-11 ml-auto mr-auto"> <h1 class="heading ">Login </h1> <div class="form-group"> <input type="email" class="form-control" placeholder="Enter Email"> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Password"> </div> <button type="submit" class=" btn col-sm-6 ml-auto mr-auto" id="log- icon">Login</button> <div class="col-sm-6 forgot ml-auto mr-auto"> <a href="#">Forgot Password?</a> </div> <div class="col-sm-6 forgot ml-auto mr-auto"> <a href="signup_E.html">Create an Account</a> </div> </form> </div> </div> </div> </div> </div> And the Allauth template look like this , i'm uploading only the direct login form of allauth <p>{% blocktrans %}If you have not created an account yet, then please <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %}</p> {% endif %} <form class="logi`enter … -
Create input field in django ModelForm through autocomplete select
I have a dynamic DropDownBox in Django ModelForm through autocomplete select2. Selections are coming out properly, but I don't know how to save new choices into the database through autocomplete select2. Help me to solve. My ModelForm Title = forms.ModelChoiceField(queryset=Book1.objects.values_list('Title', flat=True).distinct(), widget=autocomplete.ModelSelect2()) class Meta: model = Book1 fields = [ 'Title'] class Book1Admin(admin.ModelAdmin): form = Book1Form save_as = True -
My images are stored in the Django model but not in my media directory unless if the page gets refreshed. How to solve this issue?
I've created a simple image upload page which allows a user to upload an image from the system. It rejects any extensions other than PNG, JPEG, JPG and SVG. Once successful, the user will get sent to a page which states that the image upload is successful. However, once returned back to the image upload page; when a user uploads again without refreshing the page, the image gets stored into the Django model but not in the media directory. What's the reason for this? I'm using Django 2.2.2 version and am currently new to it. Code: models.py from django.db import models import os from PIL import Image from datetime import date import datetime from .validators import validate_file_extension import base64 def get_directory_path(instance, filename): today = date.today() t = datetime.datetime.now() day, month, year = today.day, today.month, today.year hour, minutes, seconds = t.hour, t.minute, t.second filename = str(day) + str(month) + str(year) + str(hour) + str(minutes) + str(seconds) + '.png' dir = 'media' path = '{0}/{1}'.format(dir, filename) return path class Image(models.Model): image = models.FileField(upload_to = get_directory_path, default = 'media/sample.png', validators=[validate_file_extension]) created_date = models.DateTimeField(auto_now = True) def __str__(self): return str(self.id) @property def image_url(self): with open(self.image.path, "rb") as imageFile: base64.b64encode(imageFile.read()) with open(self.image.path, "wb") as fh: … -
how to set callback and website url for localhost in twitter app
i am getting this problem and how should i add best call back url in twitter app Website URL http://localhost:8000/ http://127.0.0.1:8000/ http://twitter/username/ http://example.com callback url http://localhost:8000/ https://localhost:8000/ http://127.0.0.1:8000/ http://localhost:8000/auth/twitter/callback/ http://twitterusername.com/ http://127.0.0.1/complete/twitter/ http://127.0.0.1/oauth/complete/twitter/ http://127.0.0.1/folder_name/ HTTPError at /social-auth/login/twitter/ 403 Client Error: Forbidden for url: https://api.twitter.com/oauth/request_token -
Django group by only using users_id and get all other fields from model
views.py condition = Q(vendor_id=vendor_id) sum_invoice_qry = Sum('amount', filter=Q(transaction_type=1)) sum_payment_qry = Sum('amount', filter=Q(transaction_type=2)) qs = Transaction.objects.values('users_id').annotate(sum_invoice=sum_invoice_qry).annotate(sum_payment=sum_payment_qry).filter(condition) => I need to group by users_id and all other fields from model, - But, currently it is making this query: SELECT `tbl_transactions`.`users_id`, SUM(CASE WHEN `tbl_transactions`.`transaction_type` = 1 THEN `tbl_transactions`.`amount` ELSE NULL END) AS `sum_invoice`, SUM(CASE WHEN `tbl_transactions`.`transaction_type` = 2 THEN `tbl_transactions`.`amount` ELSE NULL END) AS `sum_payment` FROM `tbl_transactions` WHERE (`tbl_transactions`.`vendor_id` = 3544 AND `tbl_transactions`.`billing_type` = ) GROUP BY `tbl_transactions`.`users_id`, `tbl_transactions`.`date_time`, `tbl_transactions`.`date_added` ORDER BY `tbl_transactions`.`date_time` DESC, `tbl_transactions`.`date_added` DESC => Why the date_time and date_added is appended in group by? how to remove them => How to get all others fields, like vendor_id, amount... from models models.py from django.contrib.auth import get_user_model from django.db import models # Create your models here. class Transaction(models.Model): users = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) vendor_id = models.IntegerField(blank=True) transaction_id = models.CharField(max_length=100,blank=True) #transaction_type = models.CharField(max_length=100,blank=True) TYPE_CHOICES = ((0, 'Select Transaction Type'),(1, 'Invoice'), (2, 'Payment')) transaction_type = models.IntegerField(default=0,blank=True,choices=TYPE_CHOICES) amount = models.DecimalField(max_digits=15,decimal_places=2) out_std_amount = models.DecimalField(max_digits=15,decimal_places=2,blank=True) description = models.TextField(blank=True) attachment = models.ImageField(upload_to="images/transactions/%Y/%m/%d",blank=True) quantity = models.IntegerField(default=0) billing_type = models.CharField(max_length=50,blank=True) date_time = models.DateTimeField(auto_now=False) added_by = models.IntegerField(blank=True) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): super(Transaction, self).save(*args, **kwargs) class Meta: db_table = 'tbl_transactions' ordering = ['-date_time','-date_added'] def __unicode__(self): return self.transaction_id -
MySQL (1118, 'Row size too large (> 8126)) & increasing innodb_log_buffer gives me error
I'm running a staging server on an Ubuntu 16.04, When I try to save a particular document, I get the following error: OperationalError at /product/1172 (1118, 'Row size too large (> 8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED may help. In current row format, BLOB prefix of 768 bytes is stored inline.') The document contains many text fields with anywhere between 10 - 1000 characters. When I delete some of the text, I could actually save the document just fine. So it's probably character bound. The interesting bit is that when I try to clone the same document details into my local MYSQL version, it works just fine. So my next logical step was to compare innodb_ global variabls. I compared and the only variable that was different was innodb_log_buffer_size was set to 16M on local, but 8M on the staging version. So I tried to set it up from mysql.conf under [mysqld] statement. However, when I try to restart the service for mysql, I get the following error: Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details. And when checking the … -
Success-message not working in Django Class based Createview
I have my View Below I tried everything but Success-message not working in Django Class-based Createview. Where I am wrong? class TaskCraeteView(LoginRequiredMixin,CreateView): model=Task success_message = "Task Craeted successfully!" reverse_lazy('create-task') login_url = 'login' template_name = 'create-task' form_class = TaskCreateForm get_success_url ="/" def form_valid(self,form): print(form.cleaned_data) form.instance.task_assign_by = self.request.user server = form.save(False) server.save() # form.save() task= Task.objects.latest('id') print(type(task)) for users in form.cleaned_data['task_assign_to']: TaskComplete.objects.create(completed_by=users, task_id= task) for p in form.cleaned_data['task_perticulars']: task.task_perticulars.add(p) for t in form.cleaned_data['task_subtask_name']: task.task_subtask_name.add(t) return HttpResponseRedirect("add") -
How to make dropdown menu to be visible when hover in django?
I have made a dropdown menu in django so that a user could select one option but whenever I click on dropdown menu, all the contents hide itself except the one I hover a mouse on it. How to make all the contents visible?? forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image','payment_method','detail'] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) payment_method = models.CharField(max_length=10, choices=Paymet_choices) profile.html {{p_form|crispy}} -
Django rest framework where to write complex logic in serializer.py or views.py?
I am new to Django Rest Framework. Using serializer and views a simple CRUD is easy. When the logics increase, it is quite confusing where to write logics in serializer or views. Some developers do prefer "Thick serializer and thin views" and some developers "Thick views and thin serializer". Maybe this is not a big issue and I think it is up to the developer whether to write more on views or serializer, but as a newbie what will be your suggestion to follow? Should I write more on views or serializer? There are many answers on Django View Template but can not find a satisfying answer for Django Rest Framework. Thoughts of experienced developers will be highly appreciated. Thank you. -
how to poll message from SQS using celery worker, the message is in JSON format and worker not able to decode the format
how to poll message from SQS using celery worker, the message is in JSON format and worker not able to decode the format Note: These messages are not sent into SQS using celery beat, This queue is subscribed from SNS my celery worker command is: celery worker -A status_handling -l info -Q es_status_test Msg in Queue: { "Type" : "Notification", "MessageId" : "f7e40fd9-8f92-59c5-afd9-5a1847aaae57", "TopicArn" : "arn:aws:sns:us-west-2:410317669909:email_service_responses-testing", "Message" : "{\"SESResponseStatusCode\": 200, \"Status\": \"Delivered\", \"Message\": \"Email sent successfully.\", \"MessageId\": \"a59e85a2-8b7a-4b49-9354-0a7a4170b0c0\", \"Uuid\": null}", "Timestamp" : "2019-08-05T06:00:24.943Z", "SignatureVersion" : "1", "Signature" : "Ofa0Xh20WfBha1sXOdqcs967/4m4/2398cm47hmFB/Tk8i47thL5ge6X6hCO/SuL1fE7yC0/2vVaC2s22HOlAwtnpPmOVWwno3h3OQq8B/lqdbKBriYan0U10ye0WtPPfjkPsRJyfDwit1QKf80vmUXjt9ccqGIBm+fJwS8zeLnn/Z8KWqOhr+VQBzK+cNZOotdhxE0M8Paah8/C3gqaBHc3Yi89dV2dZUF56mexMK+mccNo9ScGVTJrbfWHkKK/cQeD0pgUpfPKPsmGAyQzaBKAe9Nx24lqsGFSE8GGItVWdv9x9xCh8/q+HimRAP0pM24FcqqczVGu+CXe/lZcnQ==", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-6aad65c2f9911b05cd53efda11f913f9.pem", "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:410317669909:email_service_responses-testing:e493364b-b593-4134-8c0e-c60fc8feebe8" } Error is coming: [2019-08-04 23:00:25,116: CRITICAL/MainProcess] Unrecoverable error: JSONDecodeError('Expecting value: line 1 column 1 (char 0)') Traceback (most recent call last): File "/home/vagrant/env/lib/python3.7/site-packages/celery/worker/worker.py", line 205, in start self.blueprint.start(self) File "/home/vagrant/env/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/vagrant/env/lib/python3.7/site-packages/celery/bootsteps.py", line 369, in start return self.obj.start() File "/home/vagrant/env/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/home/vagrant/env/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/vagrant/env/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 596, in start c.loop(*c.loop_args()) File "/home/vagrant/env/lib/python3.7/site-packages/celery/worker/loops.py", line 91, in asynloop next(loop) File "/home/vagrant/env/lib/python3.7/site-packages/kombu/asynchronous/hub.py", line 362, in create_loop cb(*cbargs) File "/home/vagrant/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line 111, in on_readable return self._on_event(fd, _pycurl.CSELECT_IN) File "/home/vagrant/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line 124, in _on_event self._process_pending_requests() File "/home/vagrant/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line 130, in _process_pending_requests self._process(curl) File "/home/vagrant/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line … -
access post phone numer&message chat enable or disable?
we have 3plans Basic , Premium and pro..... type of users registerd/subscribe with plan. whe hve problem is Basic posted image with access to premium, so premium customer can access full details of phone/chat are enable and he can see.but pro customer can see only details but he can't see phone/chat because he don't have access? please tell me how to write code for this in python django? id,plan:1 Basic ,2 Premium,3 pro if request.method == "POST": if 'userblogpostview' in request.POST: posview_results = AddNewposts.objects.get(id=id) postimg_results=Useruploadedpostimages.objects.filter(newpost_id=posview_results.id).all() subcriptionname = Userinformation_tbl.objects.get(userinfo_id=request.user.id) if user.is_active: subcriptionname = Userinformation_tbl.objects.get(userinfo_id=request.user.id) return render(request, 'widgetsapp/userpostblogview.html',{'i1': posview_results, 'postimg_results': postimg_results,'subname':subcriptionname}) else: subname='XXXXXXXXX' return render(request, 'widgetsapp/userpostblogview.html', {'i1': posview_results, 'postimg_results': postimg_results, 'subname': subcriptionname}) return render(request, 'widgetsapp/userpostblogview.html',{'i1': posview_results, 'postimg_results': postimg_results,}) when we are login only it works , if not login it showing error? -
Django Warning (urls.W005) URL namespace isn't unique urls
Hi I'm getting this error when doing my migrations or using the python manage.py runserver command. WARNINGS: ?: (urls.W005) URL namespace 'suppliers' isn't unique. You may not be able to reverse all URLs in this namespace ?: (urls.W005) URL namespace 'teachers' isn't unique. You may not be able to reverse all URLs in this namespace This is my urls.py inside my app directory (classroom): from rest_framework_simplejwt.views import TokenRefreshView from classroom.views.classroom import * from .views import classroom, suppliers, teachers urlpatterns = [path('', classroom.home, name='home'), path('sign-in/', SignInView.as_view(), name='get-token'), path('refresh/', TokenRefreshView.as_view(), name='refresh-token'), path('username/available/', is_username_available, name='username-available'), path('sign-up/', CreateUserView.as_view(), name='sign-up'), path('current_user/', current_user), path('users/', UserList.as_view()), path('createrfq/', createrfq.as_view()), path('suppliers/', include(([path('load', suppliers.QuizListView.as_view(), name='quiz_list'), path('interests/', suppliers.SupplierTruckView.as_view(), name='supplier_trucks'), path('home/', suppliers.TakenQuizListView.as_view(), name='taken_quiz_list'), path('quiz/<int:pk>/', suppliers.take_quiz, name='take_quiz'), path('quiz/edit/<int:pk>/', suppliers.edit_quiz, name='edit_quiz'), # teachers modules path('quiz/add/', suppliers.QuizCreateView.as_view(), name='quiz_add'), path('quiz/confirm/<int:pk>/', suppliers.QuizUpdateView.as_view(), name='quiz_change'), path('quiz/<int:pk>/delete/', suppliers.QuizDeleteView.as_view(), name='quiz_delete'), path('quiz/<int:pk>/question/add/', suppliers.question_add, name='question_add'), path('quiz/<int:quiz_pk>/question/<int:question_pk>/', suppliers.question_change, name='question_change'), path('myposts/', suppliers.QuizListView1.as_view(), name='quiz_change_list'), path('myposts/<int:pk>/results/', suppliers.QuizResultsView.as_view(), name='quiz_results'), path('upload/pod/<int:pk>', suppliers.pod_upload, name='model_form_upload'), # path('pod/', suppliers.image_path, name='pod'), path('financials/', suppliers.invoices, name='financials'), path('lr/<int:pk>/', suppliers.LrFormView, name='lr_form'), path('printlr/<int:pk>/', suppliers.PrintLR, name='lr_print'), path('invoice/<int:pk>/', suppliers.InvoiceView, name='invoice_edit'), path('trips/', suppliers.trips, name='supplier_trip'), path('printinvoice/<int:pk>/', suppliers.PrintInvoice, name='invoice_print'), ], 'classroom'), namespace='suppliers')), path('shipper/', include(([ path('editprofile/', teachers.ShipperUpdateView.as_view(), name='update_shipper'), path('freight/', teachers.QuizListView.as_view(), name='quiz_change_list'), path('assigned/', teachers.AssignedListView.as_view(), name='assigned_list'), path('activetrucks/<int:pk>/', teachers.take_quiz, name='take_quiz'), path('activetrucks/', teachers.QuizListView1.as_view(), name='active_trucks'), path('rtd-items/', teachers.rtd_items.as_view(), name='rtd-items'), # this fucked up code was written by chirag gulati path('dispatched-items/', … -
How should I add permissions to a model correctly?
When users register, then I add a permission to view content. However, the added permission is classing with Django default. I'd like to add a view permission, but do not know how. Once, users get this permission, they can view specialized content. class Viewing(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) view_content = models.BooleanField(default=False) order_id = models.CharField(max_length=250, blank=True) purchases = models.IntegerField(default = 0, blank=True) class Meta: ordering = ['user'] permissions = (("view_content", "Content Access"),) def __str__(self): return f'{self.user} ({self.view_content})' django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: c(auth.E005) The permission codenamed 'view_content' clashes with a builtin permission for model 'mymodel.Viewing'.