Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I got a database error when Im using Django
Nice to meet you. Im from japan and If im not using properly English,please teach me. Let me ask some questions. I created a django project,and tried this code at the terminal. python manage.py startapp myhp Then models.py file has created. Then I wrote some class and I tried this code at the terminal. python manage.py startapp runserver Then following error has occured.(I dont know which point is important,so Ill show all) Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\ProgramData\Anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\migrations\recorder.py", line 76, in applied_migrations if self.has_table(): File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\base\introspection.py", line 48, in table_names return get_names(cursor) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\base\introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\sqlite3\introspection.py", line 73, in get_table_list ORDER BY name""") File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\utils.py", line … -
sendgrid-django - Invalid Header Value?
I've been trying to get Sendgrid setup with Django and am using the Sendgrid-Django library (https://github.com/elbuo8/sendgrid-django) that is officially created by Sendgrid. I'm using it for the built in password-reset functionality in Django. On Sendgrid, I've verified my API key has full access and added it as an env variable in Heroku, but I'm still getting an 'Invalid Header' error when I try to hit password reset (and thus send an email). I've tested writing the email to a file and it works correctly then. settings.py: SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') EMAIL_BACKEND = "sgbackend.SendGridBackend" using: python 3.7.3 Django==3.0.7 sendgrid-django==4.2.0 sendgrid==3.6.3 Heroku Logs: 2020-08-17T00:13:34.139336+00:00 app[web.1]: Traceback (most recent call last): 2020-08-17T00:13:34.139340+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner 2020-08-17T00:13:34.139340+00:00 app[web.1]: response = get_response(request) 2020-08-17T00:13:34.139343+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response 2020-08-17T00:13:34.139344+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2020-08-17T00:13:34.139344+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response 2020-08-17T00:13:34.139346+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2020-08-17T00:13:34.139346+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view 2020-08-17T00:13:34.139346+00:00 app[web.1]: return self.dispatch(request, *args, **kwargs) 2020-08-17T00:13:34.139346+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper 2020-08-17T00:13:34.139347+00:00 app[web.1]: return bound_method(*args, **kwargs) 2020-08-17T00:13:34.139347+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view 2020-08-17T00:13:34.139347+00:00 app[web.1]: response = view_func(request, *args, **kwargs) 2020-08-17T00:13:34.139347+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/views.py", line 222, in dispatch 2020-08-17T00:13:34.139347+00:00 … -
Go vs Python for Backend & Rest APIs [closed]
I have been writing Python(including DRF) for a couple of years. However, interested in Go as well. I'm going to develop Backend and REST APIs from scratch for one application. Since I'm yet to decide the tech stack, I'd like to know a comparison of Go vs Python for my use case. Which one should I prefer and in what scenarios for a REST API service? Any answer which can cover the following points would be much appreciated: Complexity of the application Maintainability Scalability and performance Security Preferred Type of application Thanks! -
Audio Streaming website using media server setup
I have a react js front end and python (django) back end setup on a linux server. I want to stream audio in my website through a media server (so that the audio will be supported in all platforms, shouldn't be downloadable). Can someone help me by pointing in the right direction please. P.S: I have my audio files in an AWS S3 bucket. -
Django JWT authentication using external API
I am trying to integrate a django application with an authentication api provided externally. I have the External API url to post to which is similar to the below https://testing.co.nz/api/token/jwt/generate How do you integrate the standard Django default authentication with using externally generated JWT tokens? There is plenty of information on how to start hosting JWT tokens and authorisation within your django application with the likes of djangorestframework-jwt and djangorestframework-simplejwt, but nothing on using an external API. Any guidance would be welcome. -
Content Security Policy: The page’s settings blocked the loading of a resource at http://127.0.0.1:8000/favicon.ico (“default-src”).)
I coding this web app and getting this error: Content Security Policy: The page’s settings blocked the loading of a resource at http://127.0.0.1:8000/favicon.ico (“default-src”). Views.py code: def following(request): if request.user.is_authenticated: username=request.user.username user_id=User.objects.get(username=username) following=Followers.objects.filter(userid=user_id) post_list1=None for f in following: post_list=Post.objects.filter(userid=f.followeruserid) if post_list1 is None: post_list1=Post.objects.filter(userid=f.followeruserid) post_list1=post_list1.union(post_list,post_list1) #post_list1=list(Post.objects.all().values()) return JsonResponse({ "posts":list(post_list1.values()) #"likes":list(likes.values()) }) else: return render(request, "network/login.html") javascript code: function fetchfollowing() { fetch(`/following`) .then(response => response.json()) .then(data => { /* const page=document.querySelector('#page3').innerText; pagein=Number(localStorage.getItem('page')); if (pagein>page){ document.querySelector('#page1').innerText=pagein document.querySelector('#page2').innerText=pagein+1 document.querySelector('#page3').innerText=pagein+2 }*/ add_post(data.posts,data.likes) window.scroll(0,localStorage.getItem('position')) }) } function add_post(contents,liked) { // Create new post for (let j=0;j<contents.length;j++){ const post = document.createElement('div'); post.className = 'post'; post.id=contents[j].id var counter=0; var likeverb; if (liked != undefined ){ var username = document.querySelector('#userloged').innerHTML; for (let i=0;i<liked.length;i++){ if (liked[i].postid_id===contents[j].id && liked[i].username===username){ counter++; } } if (counter===0){ likeverb='Like' } else{ likeverb='Unlike'; } } else{ likeverb='Login'; username=0; } var d=new Date(contents[j].DateTime) var formatdate=d.toLocaleDateString(undefined,{month:'long',day:'numeric',year:'numeric'})+' '+d.toLocaleTimeString() if (contents[j].username===username){ post.innerHTML = `<a href="profile?id=${contents[j].userid_id}">${contents[j].username}</a><br>${formatdate}<br>${contents[j].post}<br>${contents[j].totallikes} <br><button class="edit">Edit</button> <a href="" class="like">${likeverb}</a>`; } else { post.innerHTML = `<a href="profile?id=${contents[j].userid_id}">${contents[j].username}</a><br>${formatdate}<br>${contents[j].post}<br>${contents[j].totallikes} <br><a href="" class="like">${likeverb}</a>`; } // Add post to DOM document.querySelector('#posts').append(post); } }; and this is my Html Code: {% extends "network/layout.html" %} {% block body %} {% if user.is_authenticated %} {% endif %} <div id='posts'> </div> {% endblock %} and this is … -
Failed to import pip modules on aws bitnami django lightsail instance
i followed AWS tutorial for django lightsail instance: https://aws.amazon.com/es/getting-started/hands-on/deploy-python-application/ i tried to deploy my own code but apache gives me errors on piped installed modules. It seems that instance have different paths. Some one has deployed custom django projects on django lightsail instance? [Sun Aug 16 22:58:29.402644 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] mod_wsgi (pid=4065): Exception occurred processing WSGI script '/opt/bitnami/apps/django/django_projects/orderbot/ordermenu/wsgi.py'. [Sun Aug 16 22:58:29.403437 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] Traceback (most recent call last): [Sun Aug 16 22:58:29.403493 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] File "/opt/bitnami/apps/django/django_projects/orderbot/ordermenu/wsgi.py", line 22, in <module> [Sun Aug 16 22:58:29.403504 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] application = get_wsgi_application() [Sun Aug 16 22:58:29.403515 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] File "/opt/bitnami/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Sun Aug 16 22:58:29.403521 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] django.setup(set_prefix=False) [Sun Aug 16 22:58:29.403530 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] File "/opt/bitnami/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup [Sun Aug 16 22:58:29.403535 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] apps.populate(settings.INSTALLED_APPS) [Sun Aug 16 22:58:29.403544 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] File "/opt/bitnami/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate [Sun Aug 16 22:58:29.403549 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] app_config = AppConfig.create(entry) [Sun Aug 16 22:58:29.403558 2020] [wsgi:error] [pid 4065] [client 177.240.102.67:65250] File "/opt/bitnami/python/lib/python3.8/site-packages/django/apps/config.py", … -
Django Paginate, returns incorrect number of items on the page
I am trying to use Django's built-in Paginate method to limit 6 items per page. After setting up the paginate, I get a different number of items on each page first page - 1 item second - 3 items, etc Here is my set up: models.py class Project(models.Model): title = models.CharField(max_length=100, unique=True) url = models.URLField(unique=True) ... class Meta: ordering = ["-date_added"] ... views.py class ProjectListView(ListView): model = Project paginate_by = 6 template_name = "home.html" home.html {% extends 'base.html' %} {% load static %} {% block content %} <div> {% for site in page_obj %} <p>{{ site.title }}</p> {% endfor %} </div> <!-- Code below is from the official [documentation][1] --> <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> {% endblock content %} I tried doing this in the shell, like in the official documentation and there results were fine: In [3]: projects = Project.objects.all() In [4]: p = Paginator(projects, 6) In [9]: page1 = p.page(1) In [21]: len(page1.object_list) Out[21]: 6 In … -
How can i render django-crispy-forms as DetailView?
Python Django How can i render django-crispy-forms as DetailView? without the posibility of editing it Thanks -
Django + SendGrid - Sending works in Python shell but not in localhost or Heroku
I know there's a lot of questions similar to this, but I've gone through all of them and can't figure out what's wrong with my setup. I added password reset functionality using the built in defaults on Django, and can get emails written to a file without issue. I also setup SendGrid with Django, using the following settings: SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True After this, I tested sending an email with: from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'me@mywebsite.com', ['me@mywebsite.com'], fail_silently=False, ) Which works, the email sends and the function returns 1. However, when I try to reset my password on localhost I get the following error: SMTPSenderRefused at /password_reset/ (550, b'Unauthenticated senders not allowed', 'webmaster@localhost') I figured it was because I hadn't setup my SendGrid account with localhost. But I had set it up with my DNS for mywebsite.com , so it might work from my app. I pushed to Heroku and tried to send, but got the following error: 2020-08-16T22:42:16.055837+00:00 app[web.1]: 2020-08-16 22:42:16 [10] [ERROR] pathname=/app/.heroku/python/lib/python3.7/site-packages/django/utils/log.py lineno=228 funcname=log_response Internal Server Error: /password_reset/ 2020-08-16T22:42:16.055848+00:00 app[web.1]: Traceback (most recent call last): 2020-08-16T22:42:16.055849+00:00 app[web.1]: … -
Django: get all values from model
I'm building an admin page where you can edit all tables from DB, and I need some automatization to provide user models to front-end. So for that, I need to make as many inputs as fields the model has and also I need to insert the value into the input which is also from model field value. So I made this to provide as many inputs as I need: fields = Users._meta.get_fields() fields_list = [field.name for field in Users._meta.get_fields()] With this code I can make as many inputs as I need. {% for field in fields_list %} <input type="text" id="{{field}}" value="???????" name="inputUsername6" placeholder="{{field}}" class="form-control text-center mb-4"> {% endfor %} As you can see there's one thing missing... The value, how can I provide the value for the field? I can do this manually and then pass it to the front-end, but I have many tables and I think there are better ways to make this work. field_value = [model.id, model.last_login, model.public_id] -
docx2pdf module causing error when site is live
I am trying to generate a pdf report and show it in to the user in the browser. The method i used to do this was to generate the report using docx and then use docx2pdf in order to convert the generated report into pdf format. My code works perfectly when i host it locally on my machine. However when i try to toast it online via heroku i get the following error: docx2pdf is not implemented for linux as it requires Microsoft Word to be installed The weird thing is that i am not using a linux machine. I have tried both safari and google chrome browsers and i get the same result. I find it strange because when i host the site locally, the pdf gets generated and shown in the browser exactly the way i want it. but when i upload to heroku i get the error. The code that deals with th e conversion is: def making_a_doc_function(request): doc = docx.Document() doc.add_heading("no text") doc.save('thisisdoc.docx') #converting the generated docx into a pdf file convert("thisisdoc.docx", "output.pdf") pdf = open('output.pdf', 'rb') response = FileResponse(pdf) return response -
NoReverseMatch at Reverse for 'url-name' with arguments '('',)' not found
everyone. Here is the problem: I'm the 'NoReverseMatch' message when i try to enter localhost/condominio/generate NoReverseMatch at /condominio/generate Reverse for 'generate-details' with arguments '('',)' not found. 1 pattern(s) tried: ['condominio/generate/(?P<loc_id>[^/]+)$'] Here are my code parts: urls.py: path('generate', views.generate, name='generate-section'), path('generate/<str:loc_id>', views.generate_details, name='generate-details'), views.py: def generate(request): loc = Locatario.objects.order_by('unidade_id') return render(request, 'calccondominio/generate.html', context)``` def generate_details(request, loc_id): loc = get_object_or_404(Locatario, pk=loc_id) ctr = loc.contrato_set.get(pk=loc_id) return render(request, 'calccondominio/generate_details.html', {'loc':loc, 'ctr':ctr}) generate.html: {% extends 'blog/base.html' %} {% block content %} <div class="container"> <div class="card w-100"> <div class="card-body"> <h5 class="card-title">Unidades atualmente ocupadas:</h5> {% for l in loc %} <a href="{% url 'generate-details' locid.id %}">{{l.unidade}}</a> {%endfor%} </div> </div> </div> {% endblock content %} Thanks for your help. -
RelatedObjectDoesNotExist at /profile User has no profile
I am getting this error, again and again, RelatedObjectDoesNotExist at /profile The user has no profile. as I have created signal when any user will be created then the profile will be automatically created , it was working before but when I wrote code for an update after that this error started appearing I got stuck at this signals.py @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: profile.objects.create(user=instance) print('profilecreated') @receiver(post_save,sender=User,) def save_profile(sender,instance,**kwargs): instance.profile.save() print('profile saved') MODELS.PY class profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) image=models.ImageField(upload_to='profile_pics',default='media/vikash.jpg') def __str__(self): return f'{self.user.username} profile' views.py @login_required def profile(request): if request.method=='POST': u_form=userupdateform(request.POST,instance=request.user) i_form=imageupdate(request.POST,request.FILES, instance=request.user.profile) if u_form.is_valid() and i_form.is_valid(): u_form.save() i_form.save() messages.success(request,'you account has been updated!') return HttpResponseRedirect(reverse('profile')) else: u_form=userupdateform(instance=request.user) i_form=imageupdate(instance=request.user.profile) context={'u_form':u_form,'i_form':i_form} return render(request,'users/profile.html',context) forms.py class userupdateform(forms.ModelForm): email=forms.EmailField() class Meta: model=User fields=['username','email'] class imageupdate(forms.ModelForm): class Meta: model=profile fields=['image'] here are errors=error forgive about the indentation -
Running unreal engine game on Django
As you probably know, unreal engine has a way to export your games to html5. So I had the idea to run a browser game on my Django server and here I get the first error message. When trying to run the game I get the following: I'm using: Django 3.0.3 Unreal engine 4.23.1 The basic (in the engine included) fps template I looked it up on google and didn't found, a documentation on running Django together with unreal engine or even anything related to that topic. So I'm reaching out to you. Is there any way to run Unreal Engine Games together with Django? If you have any qestions, feel free to ask! Kudos, to you guys! PS: For the replication of the error, I uploaded everything to dropbox. (One file is too big for GitHub and for dropbox, I had to put it in a zip file because it doesn't take the init.py ...) https://www.dropbox.com/sh/y0aswllv878bdp4/AABMA5CGIgnOm4hBW_NHK8VTa?dl=0 -
How to create child django models dynamically
I want to create 73 different django models, those models will be very similar, so in theory I would inherit from a base model class and just change the name of the Model/table. I am aware this is not the best database structure, however I believe this unconventional structure may improve other aspects of my application. The initial point is to test this hypothesis. How can I have django create the models, without me having to define all 73 of them? class BaseModel(models.Model): some_field = models.CharField(max_length=255) some_other_field = models.CharField(max_length=255) class Model_NR_01(BaseModel): pass ... class Model_NR_73(BaseModel): pass Also, in the sample above, I believe the BaseModel would also be created. How could I prevent that, having at the end of the migration only the 73 models mentioned? (If possible, of course). PS.: I did searched several similar questions, couldn't find an actual answer, only warnings of how bad design it is. I am aware. -
Django Operational Error: foreign key mismatch
I have two models: from django.db import models from django.contrib.auth.models import User # Create your models here. class Category(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="categories") name = models.CharField(max_length=30, unique=True, primary_key=True) class Todo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='todos') # TODO: Add confirmation before deleting category category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="todos_in_category", null=True) item = models.CharField(max_length=50) added = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) Previously, Category's PK was the default id, however, I changed it to the name field. When I ran the migrations, i received the operational error. Thinking that it was perhaps due to a conflict between the existing id fields and the new primary key, I cleared the data in the database but with no success. Any ideas as to what could be the issue here? Thanks! -
how create a test for a api view with boto3
I created the following view to generate pre-signed credentials to upload files to an s3 bucket, I'm new to testing and boto3, what I want to know is how can I create a test for a view that uses a package like boto3 ? I read that I can simulate the generate_presigned_post, but I'm having trouble understanding how I can do this, can you guys help me on how I can test for a case like this using pytest, please? class AnimesFileCredentials(views.APIView): def get(self, request, pk, *args, **kwargs): created_by = request.user.id serializer = AnimesFileCredentialsSerializer(data=self.request.query_params) if serializer.is_valid(raise_exception=True): file_name = serializer.validated_data.get('file_name') content_type = serializer.validated_data.get('content_type') category = serializer.validated_data.get('category') animes_file = { 'anime_id': pk, 'document': file_name, 'category': category, 'created_by_id': created_by } AnimesFile.objects.create(**animes_file) presigned_post = self.generate_presigned_post(file_name, content_type) logger.info(f'created document: {file_name} to animes_id: {pk}.') return Response(presigned_post) return Response(serializer.errors) def generate_presigned_post(self, file_name, content_type): S3_BUCKET = settings.AWS_MEDIA_STORAGE_BUCKET_NAME client = boto3.client('s3', endpoint_url=settings.AWS_S3_ENDPOINT_URL) # localstack dumy url presigned_post = client.generate_presigned_post( Bucket=S3_BUCKET, Key=file_name, Fields={'acl': 'private', 'Content-Type': content_type}, Conditions=[{'acl': 'private'}, {'Content-Type': content_type}], ) logger.info(f'created presign post to document: {file_name}.') return presigned_post my test is really simple @pytest.mark.parametrize('animes_file__category', [AnimesFile.ACTION]) def test_animes_file_generate_presigned_post(db, client, anime, animes_file): url = reverse('api:files:animes-files', kwargs={'pk': anime.pk}) response = client.get(url, {'category': category, 'content_file': 'application/jpg', 'file_name': animes_file.document}) data = response.json() results = … -
The response content must be rendered before it can be iterated over. Django Rest Framework
I have a Cart model and Cartserializers. I am trying to do that is if cart defects exist in the cart and then update the cart by increasing the quantity of cart. I tried a lot to do this. But it raises an error every time this time is The response content must be rendered before it can be iterated over. Here is my code :) views.py* class CartViewSet(viewsets.ModelViewSet): serializer_class = CartSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user if user.is_authenticated: if user is not None: if user.is_active and user.is_superuser or user.is_Customer: return Cart.objects.all() raise PermissionDenied() raise PermissionDenied() raise PermissionDenied() filter_backends = [DjangoFilterBackend] filterset_fields = ['date_created', 'user'] @action(detail=False) def count(self, request): queryset = self.filter_queryset(self.get_queryset()) count = queryset.count() content = {'count': count} return Response(content) def create(validated_data, get): quantity, created = Cart.objects.update_or_create( user = validated_data.get('user', None), defects=validated_data.get('defects', None), defaults={'quantity': validated_data.get('quantity' + str(1), None)}) return quantity if quantity is created.create: return Response ({ 'status' : True, "detail" : "created" }) if quantity is created.update: return Response ({ 'status' : True, "detail" : "updated" }) models.py from django.db import models from accounts.models import User, SubCategory # Create your models here. class Cart(models.Model): user = models.ForeignKey('accounts.User', related_name="carts", null=True, on_delete=models.SET_NULL) quantity = models.IntegerField(default=1) service = … -
Django model editable but hide in main page
I want to hide my model from Django main page administration but it can be editable as a foreign key in other models. Is this possible? -
How do I html format my blog post in django?
So I want to make a blog post with HTML formatting from the admin page directly. For example from the models.py, you see the description is a TextField. When I go to the admin page to make a blog post, I want to be able to add HTML tags to my blog. So the text field will have HTML content. While I call the blog post onto the HTML template I want it to read the description as a HTML file and not just a text field. models.py from django.db import models class Blog(models.Model): title = models.CharField(max_length=100) description = models.TextField() date = models.DateField() Blog.description at admin page <HTML> <body> <p>Welcome to my first blog post!!</p> </body> </html> blog.html <h1>{{ blog.title }}</h1> <hr> <p>{{ blog.description }}</p> Any help is appreciated. Thanks! -
In python django, would it be possible to extract data from database table and store it in an array?
I tried to extract the data using 'tablename.objects.Fname()' but I am still confused on how to store all the first names in the array from database. if yes could anyone provide with an example, any sort of help would be appreciated. -
sub-select returns 4 columns - expected 1 while submitting django form
I am trying to submit the django form which takes automatic username from input field and takes a checklist of names. When I submit form it gives me error sub-select returns 4 columns - expected 1 Views.py def weekly(request): context = '' weekly_form = WeeklyForm() daily_form = DailyForm() context = {'weekly_form': weekly_form, 'daily_form': daily_form} # Weekly Report Code to execute on submit if request.method == 'POST' and 'weekly' in request.POST: form = WeeklyForm(request.POST) print("This line is printed in weekly") if form.is_valid(): tname1 = request.POST.get('teachers') data = form.cleaned_data print (data) print("This line is printed 1") report = wreport(tname = tname1, sname = data['sname'], fdate = data['date'], objective = data['objective'], tplan = data['target'], how = data['how'], material = data['material'], extra = data['support']) report.save() messages.success(request, "Your report was submitted Successfully.") else: print(form.errors) While trying to traceback error i found that it wasn't taking tname value properly which was originally a Foreign Key I changed it back to a Charfield. Now it is not showing any reasons in traceback. I am also including my models.py after changes done. Models.py class wreport(models.Model): _id = models.AutoField tname = models.CharField(max_length = 255, default = "") sname = models.CharField(max_length = 255, default = "") classes = models.CharField(max_length = … -
how to add password protect option when add post in django admin
I want to creat a option like 'password protected' for post in admin. which you can select if or not you want your post to be protected by password. If protected, it means your post will require viewer to type in password to see the post. Is there a way to do that? -
l can't login with the method l used, l have tried to use the authenticate method but it's not working can someone point me in the right direction
def index(request): #check if username and password POST requests exits (user submitted form) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(request,username=username, password=password) if user is not None: auth.login(request, user) return redirect('home') else: messages.info(request, "invalid credentials") return redirect('index') else: return render(request, 'index.html') here is my code l even tried to just use authentication without the auth but same results