Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering objects based on two attributes being the same
With regards to the below model, how could I filter through existing objects so that I find only objects where 'Name' contains a certain word, for example, "Green" but also where the vendor of the object also contains "Green"? I am of course referring to the value (assuming same type although in this example I am using char and text field). class Hat(models.Model): Name = models.CharField(max_length=255, unique = False) Size = models.IntegerField(choices=list(zip(range(1, 11), range(1, 11))), unique=False) Vendor = models.TextField(max_length=255, unique = False) List = [for Hat in Hat.objects.filter(Name__contain="Green")] -
I need to highlight the check text in color
When I start to check the words, I have what has come in green, and the error is red, and when I have an error, it does not highlight it in red, but only displays my error message. How can I make it highlight the error? view.py @login_required @permission_required("service.add_post") def create_post(req): form = PostForm() if req.method == "POST": form = PostForm(req.POST) if form.is_valid(): form.save() title = form.cleaned_data.get("title") if title != "POST": messages.error(req, f"Something went wrong") return redirect('index') # id = form.cleaned_data.get("pk") messages.success(req, f"Post {title} was created successfully") return redirect('index') return render(req, "create_post.html", {"form":form}) create_post.html {% extends "index.html" %} {% block content %} <h1>Create Post</h1> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-primary">Create New Post</button> {% endblock %} ``` Already changed a lot of things but nothing helped.[](https://i.stack.imgur.com/dbS3i.png) -
what is a python program to interchange first and last element of dictionary?
how may we interchange the positions of first and last element in a dictionary. I tried to use the swap function which did'nt work quite well for me, what can i use to achieve my desired result, please answer. -
Returning JsonResponse from a django rest-framework serializer
My question is how would I return a custom JsonResponse from a rest-framework serializer? I have a view with this code: # Send money to outside of Pearmonie class sendmoney_external(viewsets.ModelViewSet): # Database model queryset = User.objects.all() # Serializer - this performs the actions on the queried database entry serializer_class = SendMoneyExternalSerializer # What field in database model will be used to search lookup_field = 'username' My serializer is something like this: # Serializer for sending money to another Pearmonie user class SendMoneyExternalSerializer(serializers.ModelSerializer): # This is the function that runs for a PUT request def update(self, instance,validated_data): # Verifies the requesting user owns the database account if str(self.context['request'].user) != str(instance.username) and not str(self.context['request'].user) in instance.userprofile.banking_write: raise exceptions.PermissionDenied('You do not have permission to update') account_number = self.context['request'].data['to_account'] amount = self.context['request'].data['amount'] to_bank = self.context['request'].data['to_bank'] # Creates the order in the database from_user = BankingTransaction.objects.create( user = instance, date = timezone.now(), from_account_num = instance.userprofile.account_number, from_account_name = instance.userprofile.company, to_account = self.context['request'].data['to_account'], to_bank = to_bank, amount_transferred = amount, description = self.context['request'].data['description'], trans_reference = self.context['request'].data['trans_reference'], status = self.context['request'].data['status'], ) instance.userprofile.notification_count += 1 instance.userprofile.save() # Creates the notification for the supplier in the database from_notification = Notifications.objects.create( user=instance, date=timezone.now(), read=False, message=f'You have paid N{amount} to account number {account_number} … -
How to fix this django path without this prefix?
I made a simple blog and then i made a new app and copied all codes (changed to new apps) and i made url path. And all of them second app path doesn't work and it wants prefix... Where is my fault? Here is the github repo and also my codes here... https://github.com/eseymenler/firmas Ulus = folder name Ulusal = project name Ulusalb = First app Firma = Second app main project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("", include('ulusalb.urls')), path("firma/", include('firma.urls')), ] When i made this i have an error like this but when i make this from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("", include('ulusalb.urls')), path("1/firma/", include('firma.urls')), ] It works. Why this happen? I want url like this path("firma/", include('firma.urls')) How can i solve this? -
Django JSignature Templated Docs
I am utilizing Django 4.1.3, templated_docs, and Jsignature. I am hoping to be able to place the signature image generated by jsignature directly to the document. I have attempted almost every combination of utilizing Draw_signature, templated_docs {% image %}, and even {{form.media}} {{form.field}} noted in Jsignature. any insight here is helpful. from templated_docs import fill_template from templated_docs.http import FileResponse from django.http import HttpResponseNotFound from invoiceManager.models import Invoice from jsignature.utils import draw_signature def invoice_view(request, **kwargs): pk = kwargs.get('pk', None) if pk: # try: invoice = Invoice.objects.get(pk=pk) information = { 'repairDate': invoice.repair_date, 'claim': invoice.claim_authorization_number, 'customerName': invoice.customer.name, 'customerAddress': invoice.customer.address, 'customerCityStateZip': f'{invoice.customer.city} {invoice.customer.state.abbreviation}, {invoice.customer.zip_code}', 'customerPhone': invoice.customer.phone_number, 'insuranceName': invoice.insurance.name, 'policyNumber': f'policy Number: {invoice.policy_number}', 'VIN': f'VIN: {invoice.vehicle_information.vin}', 'YMM': f'{invoice.vehicle_information.year} {invoice.vehicle_information.make} {invoice.vehicle_information.model}', 'customerSignature': draw_signature(invoice.signature), 'technician': invoice.technician.name, 'location': invoice.business_location.name, 'submissionDate': invoice.invoice_submission_date, 'amount':invoice.invoice_amount, } repairLocations = {f'RL{x}':"Repair Made" for x in invoice.location_of_repairs.all().values_list('id', flat=True).order_by().distinct()} information.update(repairLocations) filename = fill_template( 'docs/base_invoice.odt', information, output_format=".pdf") visible_filename = 'invoice{}'.format(".pdf") return FileResponse(filename, visible_filename) -
How to add dynamically data in form through ajax in javascript or jquery?
i got data from db through ajax and try to add in forms input tags. When i add data in the form dynamically through Ajax. , the webpage got stuck and a black layer coming on the webpage, i could not able to anything tech stack:(Django/javascript/jquery) $.ajax({ url:url, method:"post", data:mydata, dataType:"json", success:function(data) { if(data.status==1) { let is_free=data.value['is_free']; console.log(typeof data.value['is_free']); document.getElementById("id_Lecture_Title").value=(data.value['title']); document.getElementById("lec_desc").value=(data.value['desc']); document.getElementById("free_preview_lec").checked=true; $("#add_lecture_model").modal("show"); } }, error:function(data) { alert("Something went wrong"); } }); enter image description here Help me to solve this problem>> -
How to validate Nested Serializer in Django Rest Framework
I have ReviewRatings and ReviewImages models in which ReviewImages is ForeignKey to ReviewRatings so that an user can upload single or multiple images along with reviews. I have overridden the create method for ReviewRatings in ReviewRatingSerializer and creates ReviewImages in it also. I Have ReviewImagesSerializer also. So My doubt is How do I validate the images am looping through before saving it. Is there anyway to call ReviewImagesSerializer in create method of ReviewRatingSerializer to validate the files? #Serializer.py class ReviewImagesSerializer(ModelSerializer): class Meta: model = ReviewImages fields = ["images"] class ReviewSerializer(ModelSerializer): user = SerializerMethodField() review_images = ReviewImagesSerializer(many=True, required=False) class Meta: model = ReviewRatings fields = [ "user", "rating", "review", "created_at", "updated_at", "review_images", ] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" def create(self, validated_data): review_images = self.context["images"] reviews = ReviewRatings.objects.create(**validated_data) for image in review_images: ReviewImages.objects.create(review=reviews, images=image) return reviews -
getting error in printing the dictionary values to html
I want to print to get the details of different cities weather and I had written the code as below. While retreving the data I am not able to fetch the data to HTML. views.py from django.shortcuts import render # Create your views here. import urllib.request import json import requests def display(request): city=['vijayawada','guntur','tenali','rajahmundry','amaravathi'] for i in city: source = urllib.request.urlopen( 'https://api.openweathermap.org/data/2.5/weather?q=' + i + '&units=metric&appid=5980455dc827c861d5ac4125c3673b43').read() list_of_data = json.loads(source) data = { "country_code": str(list_of_data['sys']['country']), "coordinate": str(list_of_data['coord']['lon']) + ', ' + str(list_of_data['coord']['lat']), "temp": str(list_of_data['main']['temp']) + ' °C', "pressure": str(list_of_data['main']['pressure']), "humidity": str(list_of_data['main']['humidity']), 'main': str(list_of_data['weather'][0]['main']), 'description': str(list_of_data['weather'][0]['description']), 'icon': list_of_data['weather'][0]['icon'], } print(data) return render(request, "display.html",data) display.html <html> <head> <title>API Display</title> </head> <body> <h1>Weather details</h1> <form> {% for i in data %} {{ country_code }} {{ temp }} {{ i }} {% endfor %} </form> </body> </html> I am trying to print the values of the dictionary to html but not getting printed. The values are printing correctly in the console which means the for loop in views.py is working correctly. Please tell me where I am wrong -
Get formset name variables in django templates
I am sending a formset to my template. I want to add some style to it, so I need to access his variables. I took the following code from documentation, where they print the form and it has some attributes, amongside them the name="form-0-title". for form in formset: print(form.as_table()) <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Django is now open source" id="id_form-0-title"></td></tr> ... As I want to style my forms, I need to give the inputs a name to know how to treat them in the backend. When I do the following in the templates {{ proficiency_form.management_form }} {% for form in proficiency_form %} {{form.title.name}} {% endfor %} I get title, title, ... instead of id_form-0-title, id_form-1-title, ... How can I get the correct name in the templates? -
"Get 500 (Internal Server Error)" on Django+React
I'm working on Django+React project. I have made user and project models in django. I can get access to project list page, but i am stuck trying get access to project page. Another thing is, when i use link on page with list of projects, it sends to http://localhost:3000/projects/undefined. projectlist page: http://localhost:3000/projects/ project page: http://localhost:3000/projects/skyscrapper Console: GET http://localhost:8000/api/projects/undefined/ 500 (Internal Server Error) Terminal: base.models.Project.DoesNotExist: Project matching query does not exist. [07/Dec/2022 20:47:10] "GET /api/projects/undefined/ HTTP/1.1" 500 101255 project.js import { React, useState, useEffect } from 'react'; import axios from 'axios'; import { Row, Col, Image, ListGroup } from 'react-bootstrap' import './index.css' import './bootstrap.min.css' function Project() { // projects is the data, setprojects is a function that sets the value of projects const [project, setProject] = useState([]); useEffect(() => { const fetchproject = async({slug}) => { try { const res = await axios.get(`http://localhost:8000/api/projects/${slug}`); setProject(res.data); } catch (err) {} }; const slugData = window.location.href.split("/"); fetchproject(slugData[slugData.length-1]);// add your slug value in this method as an argument }, []); return ( <div> <Row className="my-1 p-4"> <Col xs={3} sm={2} md={2} lg={1} > <Image className="p-1 rounded-circle bg-dark mx-auto d-block" style={{width: 100, height: 100}} src={project.image} fluid /> <ListGroup variant="flush" > <ListGroup.Item> <h3 class="rfs-10">{project.name}</h3> </ListGroup.Item> <ListGroup.Item style={{fontSize: 12}}> … -
Django Channels Consumer won't execute method
I'm trying to develop a chat application that saves messages in the database via a WebSocket with Django Channels. settings.py: ASGI_APPLICATION = "app.asgi.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': "channels.layers.InMemoryChannelLayer", }, } asgi.py: from api.routing import websocket_urlpatterns application = ProtocolTypeRouter({ "http" : get_asgi_application(), "websocket": JWTAuthMiddleware( URLRouter( websocket_urlpatterns ) ), }) routing.py: websocket_urlpatterns = [ path('ws/chat/<chat_uuid>/', consumers.ChatConsumer.as_asgi()) ] consumers.py class ChatConsumer(AsyncJsonWebsocketConsumer): @database_sync_to_async def create_message(self, sender, message, chat): if sender: if content_validation(message): chat = Chat.objects.filter(uuid=chat) if chat.exists(): msg = Message.objects.create(sent_by=sender, content=message) chat.first().messages.add(msg) return msg return None @database_sync_to_async def check_security(self, user, uuid): # Chat has to exist and user has to be part of it chat = Chat.objects.filter(Q(Q(user1=user) | Q(user2=user)) & Q(uuid=uuid)) if chat.exists(): return True return False async def connect(self): self.chat_uuid = self.scope['url_route']['kwargs']['chat_uuid'] self.room_group_name = 'chat_%s' % self.chat_uuid user = self.scope["user"] if user: check = await self.check_security(user, self.chat_uuid) if check == True: # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.disconnect(401) async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] name = text_data_json['name'] print(text_data_json) user = self.scope["user"] # Is this smart? User not receiving a message for whatever reason … -
Page not found (404) Error in Django How can access to my Aboutus Page
When i click my about us button in my web site. It's not working. How can access to my Aboutus Page? I have a error "Page not found (404)" Request Method: GET Request URL: http://127.0.0.1:8000/aboutus Raised by: django.views.static.serve My home/urls.py from home import views urlpatterns = [ path('home/', include('home.urls')), path('aboutus/', views.aboutus , name='aboutus'), ] My home/views.py: from django.http import HttpResponse from django.shortcuts import render from home.models import Setting def index(request): setting=Setting.objects.get(pk=1) context={'setting':setting, 'page':'home'} return render(request,'index.html',context) def aboutus(request): setting=Setting.objects.get(pk=1) context={'setting':setting , 'page':'aboutus'} return render(request,'aboutus.html',context) -
Rarely get SynchronousOnlyOperation error in different GET requests which have database query in Django 3.2.6
Error occurs only in development server environment, cant reproduce it in local. Dev server is a docker composed environment with Django 3.2.6, python 3.7, gunicorn (for wsgi), daphne (for asgi), postgres 12, redis, celery & celery-beat inside. Error happens in GET requests which are not supposed to have any async context. For example, log of one of these errors: gunicorn_1 | [2022-12-07 13:40:21 +0000] [24] [DEBUG] GET /api/v2/sync/groups gunicorn_1 | Internal Server Error: /api/v2/sync/groups gunicorn_1 | Traceback (most recent call last): gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner gunicorn_1 | response = get_response(request) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response gunicorn_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view gunicorn_1 | return view_func(*args, **kwargs) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view gunicorn_1 | return self.dispatch(request, *args, **kwargs) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch gunicorn_1 | response = self.handle_exception(exc) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception gunicorn_1 | self.raise_uncaught_exception(exc) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception gunicorn_1 | raise exc gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 497, in dispatch gunicorn_1 | self.initial(request, *args, **kwargs) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 414, in initial gunicorn_1 | self.perform_authentication(request) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", … -
Not sending messages to db
When I try to send messages to a temporary email address, it arrives there but does not go into the django database. view.py def about(req): form = MessangeForm() if req.method == "POST": form = MessangeForm(req.POST) if form.is_valid(): subject = form.cleaned_data.get('title') body = form.cleaned_data.get('body') try: send_mail(subject, body,settings.EMAIL_HOST_USER, ["nakkosikni@gufum.com"], fail_silently=False) form.save() except Exception as err: print(str(err)) return redirect('index') return render(req, "about.html", {"form": form}) models.py ``` class Messange(models.Model): title = models.CharField(verbose_name='Subject', max_length=250, null=True, blank=True ) body = models.TextField(verbose_name='Body') def __str__(self): return f'(self.body)' forms.py class MessangeForm(ModelForm): class Meta: model = Messange fields = ["title", "body"] widgets = { "body": forms.Textarea(attrs={'class': 'form-control'}), } When I click on submit button I get this error. [07/Dec/2022 21:20:12] "GET /about HTTP/1.1" 200 2332 ОШИБКА: неверный синтаксис для типа time: "rtjyfukugil" LINE 1: ..._messange" ("title", "body") VALUES ('hjdfhjehf', 'rtjyfukug... I don't understand what needs to be changed there. -
How to render thousands of a model objects in fraction of seconds in django?
Suppose, I have a model "Student" in my django application. Now, i already have 10k student registered in my portal and i want to render all the objects at a time in a template. But the issue is, this rendering process takes a lot of time to list all the students. So, how we can make an overcome ? Consider the worst case scenario, The database have millions of students. -
Django :Retrive files from django model with signed urls from different buckets
Hope evryone doing good I want to upload some files in different buckets , and the bucket names are also stored in adjescent django field in same table. How can i retrieve that bucket name and use for upload in storage option in FileField ,The below is my table looks like class TestFileField(models.Model): id = models.AutoField(primary_key=True,blank=True,null=True) name = models.CharField(max_length=30,null=True,blank=True) **bucketname** = models.CharField(max_length=30,null=True,blank=True) sourcefile = models.FileField(upload_to=get_upload_path, blank=True,storage = GoogleCloudStorage(bucket_name = **bucketname <-- i want a value which stored in the above bucketname field** )) Or Im also trying like this, @deconstructible class CustomBucketSelection(GoogleCloudStorage): def __init__(self,*args,**kwargs): kwargs['bucket_name'] = 'mubuckey' or settings.bucket super(CustomBucketSelection,self).__init__(*args,**kwargs) def url(self, name): bucketname = current_instance.bucketname ----------------------------- i want current instance here to fecth th bucket name or credentials which stores in same database like this once i got bucket name i will generate signed url and returns that url ----------------------------------- return urll class TestFileField(models.Model): id = models.AutoField(primary_key=True,blank=True,null=True) name = models.CharField(max_length=30,null=True,blank=True) bucket_name = models.CharField(max_length=30,null=True,blank=True,default=settings.GS_BUCKET_NAME) # filename = models.FileField(upload_to=get_upload_path, blank=True,storage = CustomBucketSelection) Actually the thing is while im saving files its perfectly storing but while im retriving the files, i want signed urls with that corresponding storage buckets , so im trying like this, Please confirm me that is it possible … -
Django rosetta is saving translation but not showing new translations until the server (docker) restart
I'm using rosetta with default settings and it shows new translations in local server(no docker). but in production, I'm using docker and it's not showing updates until restart. docker-compose.yml: version: '3' volumes: production_postgres_data: { } # django production_temp_data: { } production_media: { } production_static: { } production_locale: { } services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile volumes: - production_temp_data:/tmp/ - production_media:/app/media/ - production_static:/app/staticfiles/ - production_locale:/app/locale/ depends_on: - postgres env_file: - ./.env command: /start restart: always logging: driver: "json-file" options: max-size: "100m" max-file: "10" ... django start command: #!/bin/bash set -o errexit set -o pipefail set -o nounset python /app/manage.py collectstatic --noinput python /app/manage.py makemessages --all --ignore=venv python /app/manage.py compilemessages --ignore=venv /usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 -w 1 --threads 1 --access-logfile - --error-logfile - --log-level info --capture-output --enable-stdio-inheritance --chdir=/app --timeout 180 django==4.1.3 gunicorn==20.1.0 django-rosetta==0.9.8 There is no logs to debug. tried with ROSETTA_WSGI_AUTO_RELOAD=True but it didn't work. -
Wrong installed virtualenv
I wanted to intall virtualenv in CMD (Windows 11). Unfortunately it was downloaded in the place I did not want to install it (it was supposed to be installed on D but it was installed on C. Also the folder i was expecting to be created was not created. What should I do to completly get rid of it from my computer? That is what occured after typing "virtualenv django" in CMD (django is the name of the folder which was supposed to be created): created virtual environment CPython3.11.0.final.0-64 in 1709ms creator CPython3Windows(dest=D:\django, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\mmilk\AppData\Local\pypa\virtualenv) added seed packages: pip==22.3.1, setuptools==65.6.3, wheel==0.38.4 activators BashActivator,BatchActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator I chose the folder I wanted to install the program typed "virtualenv django". Later on the program introduced me where is the whole data which was created. It was on C instead of D. Is it true if I turn off the computer the virtualenv gets deactivated? Can I download it once again but this time on the completly different drive? For example the wrong virtualenv on C, the correct virtualenv on D. I'd only work on the virtualenv on the D drive. -
Django Polls Tutorial No answer detected in choice.votes polls
I decided to learn Django and started with the 'Django Polls App' which I figured would be the most simple, I am gripping the idea of how it works but I am stuck. To learn a bit better, I changed the variables and names from the original docs to my own. Example : question_text = q_text, Choice = Choices, choice_text = choice.. etc. Now I can't figure out what's wrong with my code as I can't make the polls work. There is no error code but it simply doesn't display the number of votes or show a success sign. I was also following Traversy Media's Django Crash Course (Polls App). My code : views.py from django.http import Http404, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse from django.template import loader from .models import Question, Choices def index(request): latest_ques = Question.objects.order_by('-published')[:5] context = {'latest_ques': latest_ques} return render(request, 'polls/index.html', context) def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choices_set.get(pk=request.POST['choices']) except (KeyError, Choices.DoesNotExist): return render(request, 'polls/detail.html', { 'question': … -
How to retrive image from django database?
I saved image in database, there are multiple images and i want to retrive it in my website. my image is stored in static folder inside app folder that is card/static/images. my images is showing when i enter link http://127.0.0.1:8000/images/p.jpeg this is my urls.py ` urlpatterns = [ path('admin/', admin.site.urls), path('', include('card.urls')), path('index/', include('card.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is my models.py class dish(models.Model): dish_name = models.CharField(max_length=255) dish_size = models.CharField(max_length=7) dish_price = models.IntegerField() dish_description = models.CharField(max_length=255) dish_image = models.ImageField() dish_date = models.DateField() this is my index.html file <img src="{{ request.dish.dish_image.url }}" height="100px" width="100px"> this is my setting.py STATIC_URL = 'static/' MEDIA_URL = 'images/' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'card/static/images') ` -
Python/Django MakeMigrations Error Traceback
Here is what appears when i try to use python manage.py makemigrations traceback error Here is models.py code ----------------------code------------------------------------- from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=255, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: verbose_name_plural = 'categories' # def get_absolute_url(self): # return reverse("store:category_list", args=[self.slug]) def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='product_creator') title = models.CharField(max_length=255) author = models.CharField(max_length=255,default='admin') description = models.TextField(blank=True) image = models.ImageField(upload_to='images/') slug = models.SlugField(max_length=255) price = models.DecimalField(max_digits=4, decimal_places=2) in_stock = models.BooleanField(default=True) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Products' ordering = ('-created',) def __str__(self): return self.title ------------------code end------------------------------- im new and i dont know whats the problem -
'ForwardManyToOneDescriptor' object has no attribute 'user_type'
Models.py class UserType(models.Model): owner=models.ForeignKey(User,on_delete=models.CASCADE,default=1) user_type=models.CharField(max_length=20,default='admin') Views.py def register(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') fname = request.POST.get('firstname') lname = request.POST.get('lastname') email = request.POST.get('email') newpass = make_password(password) newuser = User.objects.create(username=username,password=newpass,first_name=fname,last_name=lname,email=email) newuser.save() usertype = request.POST.get('usertype') newtype = UserType.objects.create(user_type=usertype) newtype.save() messages.success(request, "Registration successful") if UserType.owner.user_type == 'Student': return redirect('Stuproadd') elif UserType.owner.user_type == 'Teacher': return redirect('Teachproadd') else: return redirect('index') return render(request, 'register.html') register.html <body> <h1>Register</h1> <div class="container"> <form method="post"> {% csrf_token %} <label>Username:</label> <input type="text" name="username" placeholder="Enter your username" required /><br><br> <label>First Name:</label> <input type="text" name="firstname" placeholder="Enter First Name" required /><br><br> <label>Last Name:</label> <input type="text" name="lastname" placeholder="Enter last name" /><br><br> <label>Email:</label> <input type="text" name="email" placeholder="Enter your email" required /><br><br> <label>password</label> <input type="password" name="password" placeholder="enter your password" required /> <br><br> <label>confirm password</label> <input type="password" name="password" placeholder="confirm your password" required /> <br><br> <label>Select your Role:</label> <input type="radio" name="usertype" value="Student"> <label>Student</label> <input type="radio" name="usertype" value="Teacher"> <label>Teacher</label> <button type="submit">Register</button> Already User,<a href="{% url 'index' %}">Login Here</a> </form></div> </body> This is the code.I'm getting error as 'ForwardManyToOneDescriptor' object has no attribute 'user_type' After clicking register button, I want to go to stuproadd when the user type is student and teachproadd when the user type is teacher. How is it? pls help -
Django : meaning of {% url 'zzz' %}?{{ yyy }}?
I came across a code in a HTML file and I did not understand how it works. {% url 'calendar' %}?{{ prev_month }} Especially, what does the "?" mean? And how is the code interpreted? It is used in a button to switch between month but I cant figure out how it works. I tried to print different places in the code to see what is executed with but I did not find anything interesting. Thanks -
how to output data from a linked table in django?
I have a built-in User table and a Note table associated with it by key. class Note(models.Model): header = models.CharField(max_length=100) note_text = models.TextField() data = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE) That is, a registered user may have several notes. How do I get all these notes from this particular user (who has now visited his page)? I need to get these notes in views.py. I tried different ways, don't know how to do that.