Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What solid alternatives are there to Django's `UniqueConstraint` with a condition?
Goal: I want to ensure there is only one active owner per Thing. Problem: As our DB is MySQL, I can't use the condition parameter of Django's UniqueConstraint. I'm looking for a reliable, scalable alternative to this: class Thing(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField() class Meta: constraints = [ UniqueConstraint( fields=['owner'], condition=Q(active=True), name='one_active_owner_per_thing' ) ] Would it be best to create a separate table for active Things, override the save method, or something else? -
Display message on screen of iframe src is empty
I want to display a message "Please click on a match to get started" when there is no match link clicked. i.e. the iframe is without an src. I am using django at the backend. Here is my html: </form><br> {% for match in all_matches %} <li style="list-style:none; text-align: center"><a style="padding: 6px 8px 6px 16px;text-decoration: none;font-size: 18px;color: #ffffff;display: block;" href="{{match.url}}" target="iframe1">{{match.name}}</a></li> <hr class="new1"> {% endfor %} </div> <div class="col-sm-9 col-xs-9 col-md-9 col-lg-9" id="frameContainer"> <iframe name="iframe1" id="fr" style="display: block;" width=100% height=100% frameborder="0" allowFullScreen="true"></iframe> </div> -
Data not persisting on Docker - Windows 10 Volumes docker-compopse.yml
Thanks for having a look at this. I'm getting started with using Docker along Django and while trying to set up postgres to have its own volume in order to have data persisting after docker-compose down, it isn't saving at all. Steps: 1) docker-compose up -d 2) docker-compose exec web python manage.py migrate 3) docker-compose exec web python manage.py createsuperuser 4) check if all is fine at the /admin and that user exists 5) docker-compose down Then when running it back up: 1) docker-compose up -d 2) check /admin and have errors that are only resolved if I run step 2 and 3 above. I'm using Windows 10. I have tried setting this env var as recommended by other posts but without success: COMPOSE_CONVERT_WINDOWS_PATHS=1 The directory (full path) I am working on is also shared at the Docker/Settings/Resources/File Sharing area. Any idea on how to solve this? Thanks a lot! docker-compose.yml version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/postgres_data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: -
Problem During Saving of wages models in django
I have four model EmployeeRegistration, attendance, rate and Wages simultaneously. I want to update the Wages model in every last days of the month. For this i am synchronizing the all attendance from attendance model from date 01/01/2020 to 30/01/2020. And save the manipulate data to Wages Model. My attendance models class Attendence(models.Model): EmpId = models.IntegerField(verbose_name='EmpId') Name = models.CharField(max_length=50,verbose_name='Name') Site = models.CharField(max_length=50,verbose_name='Site') Days = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Days') Nh = models.IntegerField(verbose_name='Nh') #SingleOt = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='SingleOt',null=True) DoubleOt = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='DobleOt',null=True) choices = [('P','Present'),('A','Absent'),('O','Off')] Status = models.CharField(choices=choices,blank = False,max_length=10,verbose_name='Status') AttendenceOn = models.DateField(default = timezone.now) def __str__(self): return '{EmpId}/{Name}/{date}'.format(EmpId=self.EmpId,Name=self.Name,date=self.AttendenceOn) My rate model is below class Rate(models.Model): Site = models.ForeignKey(Site,on_delete=models.CASCADE) Category = models.ForeignKey(Category,on_delete=models.CASCADE,default=False) Department = models.ForeignKey(Department,on_delete=models.CASCADE,default=False) Basic = models.DecimalField(max_digits=10,decimal_places=2) Da = models.DecimalField(max_digits=10,decimal_places=2) Rate = models.DecimalField(max_digits=10,decimal_places=2) Hra = models.DecimalField(max_digits=10,decimal_places=2) Ca = models.DecimalField(max_digits=10,decimal_places=2) SplAllow = models.DecimalField(max_digits=10,decimal_places=2) CanteenAllow = models.DecimalField(max_digits=10,decimal_places=2) def __str__(self): return '{site}_{cat}'.format(site =self.Site,cat=self.Category) My Wages model is below class Wages(models.Model): EmpId = models.IntegerField(verbose_name='EmpId') Name = models.CharField(max_length=50,verbose_name='Name') Site = models.CharField(max_length=50,verbose_name='Site') Days = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Days') Nh = models.IntegerField(verbose_name='Nh') SingleOt = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='SingleOt',null=True) DoubleOt = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='DobleOt',null=True) Basic_rate = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Basic_rate') Da_rate = models.DecimalField(max_digits=10,decimal_places=2,verbose_name ='Da_rate') Basic_Amt = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Basic_Amt') Da_Amt = models.DecimalField(max_digits=10,decimal_places=2,verbose_name ='Da_Amt') Ot_Amt = models.DecimalField(max_digits=50,decimal_places=2,verbose_name='Ot_Amt') FoodingAdd = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Fooding') AttendenceAward = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='AttendenceAward') OtherPayment = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='otherPayment',null=True) Gross = models.DecimalField(max_digits=50,decimal_places=2,verbose_name='Gross') Pf = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Pf') Esi = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Esi') FoodingDeduct = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Fooding') OtherDeduction … -
Django using "." as primary key gives 404
I am using DRF along with drf-nested-routers to configure my routing. I have an api route structure this way. /posts/1/comments Now instead of using the id I have decided to use the name of the object instead. /posts/mypost/comments This works perfectly but an issue occurs when a . is being added to the key. /posts/my.post/comments When including a . as part of the key for the resource, it returns a 404 error on Django. I have been trying to debug this issue to no avail. -
<HttpResponse status_code=200, "image/png"> is not JSON serializable
I have build a CNN model and able to classify well. But i want trying to use Django to classify the class of an image when an image is passed in the url. Here are few thing i tried. If i return just the label it works, below is Code snippet from my apps.py label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct) return (label) 2.a Here is the problem. I am trying to return the image as well with label on it. which i am not successful. label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct) output = imutils.resize(output, width=400) cv2.putText(output, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) return HttpResponse(output, content_type = 'image/png') 2.b Here is the 2nd approach to return the image, unfortunately failed. label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct) output = imutils.resize(output, width=400) cv2.putText(output, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) resp = HttpResponse("", content_type = 'image/png') resp.write('output') return resp Here is my views.py @api_view(['GET']) # Decorator def call_model(request): #if request.method == 'GET': # sentence is the query we want to get the prediction for params = request.GET.get('image_loc') # predict method used to get the prediction resp = prediction(image_loc = … -
What does ProgrammingError mean?
I am having these ProgrammingErrors occurring on my production server lately. The page which the user is submitting a form at is a UserCreateView and is being redirected to the phone-verification page. The error reads: Internal Server Error: /phone-verification/ ProgrammingError at /phone-verification/ column quiz_sitting.percent_correct does not exist LINE 1: ...rrect_questions", "quiz_sitting"."current_score", "quiz_sitt... ^ I am not sure why its looking at quiz_sitting in the database because /phone-verification/ has nothing to do with that. The view for /phone-verification/ looks like this: @login_required def phone_verify_check(request): employee = request.user phone_verify, _ = PhoneVerify.objects.get_or_create(employee=employee) login_tracker = EmployeeLogin.objects.create(employee=employee, ip_address=get_client_ip(request)) login_tracker.save() if phone_verify.verified: return redirect('dashboard') else: return redirect('resend') I am using Django tenant schemas for handling subdomains which means when I run a migration it looks like: python manage.py makemigrations python manage.py migrate_schemas --shared python manage.py migrate_schemas --tenant I recently deleted all my migrations because I was having these ProgrammingErrors on another page and then I ran the makemigrations etc again and it seemed to have fix it. But now it is occurring again. I really hope there isn't some sort of corruption in the database like columns being mixed up. Any help is greatly appreciated! -
The design of CSS is not applied to autocomplete
<div class="jumbotron vertical-center" id='search_mainpage'> <div class="container"> <div class="col-md-12"> <div class="wrapper"> <div class="search_area"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %}{% bootstrap_form form %} <datalist id="mylist"></datalist> {{ lst }} </form> </div> </div> {{ form.media }} </div> </div> </div> Guys this is my search entry field that brings dropdown however i want to change the background color, font color and size in css. i tried in css: datalist { background: yellow; color: blue; font-size: 15px;} However it does not work. Can you please help me to tell what i am doiung wrong ? The autocomplete is done by js however the design i want to change in CSS. How to do that ? -
Error as "django.core.exceptions.ImproperlyConfigured: WSGI application 'myWebApp.wsgi.application' could not be loaded; Error importing module
I am getting error as "django.core.exceptions.ImproperlyConfigured: WSGI application 'myWebApp.wsgi.application' could not be loaded; Error importing module." while creating POD in Openshift. I have tried several ways (from google, You tube) to resolve it but unsucessful. Below is the error description. File "/opt/app-root/lib/python3.6/site-packages/whitenoise/django.py", line 18, in <module> from django.utils.six.moves.urllib.parse import urlparse ModuleNotFoundError: No module named 'django.utils.six' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/rh/rh-python36/root/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/opt/rh/rh-python36/root/usr/lib64/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/opt/app-root/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/opt/app-root/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "/opt/app-root/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/opt/app-root/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "/opt/app-root/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 50, in get_internal_wsgi_application ) from err django.core.exceptions.ImproperlyConfigured: WSGI application 'myWebApp.wsgi.application' could not be loaded; Error importing module. I have deployed it over Openshift via OC consle using Dockefile. Below is the dockerfile which i have used. Even Deployment is sucessful but while running the command "python manage.py runserver" in POD terminal , i am getting same error as above. FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /src WORKDIR /src ADD . /src RUN pip install … -
Is the server running locally and accepting connections on socket "/var/run/postgresql/.s.PGSQL.5432"?
Im running docker on Windows 10, when I try to start the docker with: docker-compose up --build All services were on, but I got the error django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? This is my docker-compose.yml file: version: "3.4" services: medicinesite: # container_name: medicine_app image: medicinesite build: context: . network: host stdin_open: true tty: true command: python manage.py runserver volumes: - .:/app # - /app/postgres_data ports: - 8000:8000 depends_on: - postgres postgres: # container_name: medicine_db image: postgres:11 volumes: - ./postgres_data:/var/lib/postgresql environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres ports: - 5432:5432 This is my Dockerfile: FROM python:3.8 RUN mkdir /app RUN mkdir /var/run/postgresql RUN mkdir /var/lib/postgresql WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt CMD ["gunicorn", "--bind", "0.0.0.0:8000", "medicinesite.wsgi"] RUN ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432 What I've tried: - Create directory in /var/run/postgresql - Create directory in /var/lib/postgresql - Set psycopg2 in requirements.txt to: psycopg2==2.8.4 --no-binary psycopg2 - Add ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432 in Dockerfile The result is still same, please any help would be appreciate. -
Django: How to get related data from different db tables and display it as one
I have this two models which creates my tables, now my question is, how can I get only home_team and away_team fields on Events table then get odd from Bets table and display it in one match class Event(models.Model): sport_id = models.ManyToManyField(Sport) league_id = models.ManyToManyField(League) home_team = models.CharField(max_length=255) away_team = models.CharField(max_length=255) match_date = models.DateField() match_time = models.TimeField() featured = models.IntegerField() class Bet(models.Model): league_id = models.ManyToManyField(League) match_id = models.ForeignKey( 'Event', on_delete=models.CASCADE, ) bet_id = models.IntegerField() bet_name = models.CharField(max_length=255) choice_id = models.IntegerField() choice_name = models.CharField(max_length=255) odd = models.FloatField() match_date = models.DateField() -
Django: join tables - show student stats but only the stats connected to specific team
can't really wrap my head around this. So i want to show the stats of students in a given team. Students can have multiple stats but i only want to show the stats of the student if the stats are from my team. Consider the models class Stat(models.Model): statname = models.CharField(max_length=200) statvalue = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100)]) def __str__(self): return f"{self.statname self.statvalue}" class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) stat = models.ManyToManyField(Stat) def __str__(self): return f"{self.user}" class Coach(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f"{self.user}" class Team(models.Model): name = models.CharField(max_length=200) student = models.ManyToManyField(Student) coach = models.ManyToManyField(Coach) some_kind_of_stat_relation? def __str__(self): return f"Team {self.id}" The view: def team_view(request, pk): team = get_object_or_404(Team, pk=pk) # Get the coaches and students coaches = team.coach.all() students = team.student.all() Not sure how to combine these tables. Hope you can see what im missing. -
Know if signal is triggered from django admin
i need to send a mail only when the model is saved from django admin, I was try with sender.user.is_superuser but i can't found the specific method -
Getting an error when trying to push my files to heroku "git push heroku master ERROR"
ERROR: Could not find a version that satisfies the requirement decouple==0.0.7 I am following this tutorial : https://www.youtube.com/watch?v=F5WXNI3Dq8U&t=1208s I need help narrowing down what is causing this kind of error. Would having the latest python package be the issue ?. -
How to use a user as a ForeignKey in a Django model
I've got this model in my Django application: class ClubSession(models.Model): location = models.CharField(max_length=200) coach = models.ForeignKey('auth.User', on_delete=models.CASCADE) date = models.DateTimeField(default=now) details = models.TextField() def __str__(self): return self.title I can run python manage.py makemigrations club_sessions without issue but when I thn run python manage.py migrate club_sessions I get ValueError: Field 'id' expected a number but got 'username'. username is a superuser and already exists. How do I resolve this? -
How can i request the article for comments in django?
I am trying to create comments for article in Django.I have already done the views,models and serializer and it works fine.But i don't know to how to request the article that i have to relate the comment with. Models.py class Comment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.OneToOneField(UserProfile, on_delete=models.CASCADE, related_name='author1') article = models.OneToOneField(Article, on_delete=models.CASCADE, related_name='author2') content = models.CharField(max_length=100) Serializers.py class CommentCreateSerializer(serializers.ModelSerializer): content = serializers.CharField(required=False) class Meta: model = Comment fields = ('content',) def create(self, validated_data): return Comment.objects.create(**validated_data) Views.py class CommentView(CreateAPIView): serializer_class = CommentCreateSerializer permission_classes = (IsAuthenticated,) def post(self, request, *args, **kwargs): serializer = CommentCreateSerializer(data=request.data) if serializer.is_valid(): comment = serializer.save() serializer = CommentCreateSerializer(comment) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, format=None): queryset = Comment.objects.all() serializer = CommentCreateSerializer() return Response(serializer.data) Does anybody know why? -
Trying to set up SendGrid with Django and send first email. Getting 'HTTP Error 403: Forbidden'
Background I'm using a mac. I've followed SendGrids instructions on how to set it up within Django: Step 1) echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env echo "sendgrid.env" >> .gitignore source ./sendgrid.env Step 2) pip install sendgrid Step 3) Create send-email.py file containing the following: # using SendGrid's Python Library # https://github.com/sendgrid/sendgrid-python import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail message = Mail( from_email='from_email@example.com', to_emails='to@example.com', subject='Sending with Twilio SendGrid is Fun', html_content='<strong>and easy to do anywhere, even with Python</strong>') try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message) Step 4) python send-email.py The problem However, my terminal outputs HTTP Error 403: Forbidden with step 4 and no email is sent. Can anybody help me with this? -
Using PyVimeo error 404 when create a live event
I am just starting the integration of vimeo on my web platform for lives (I have a premium account) Currently, the client connects well with this code: vimeo.VimeoClient(token=settings.VIMEO_ACCESS_TOKEN,key=settings.VIMEO_CLIENT_ID,secret=settings.VIMEO_CLIENT_SECRET) Until then, no worries. Then I do a test to create a live with the following code: uri = '/me/live_events' response= client.post(uri, data={'title':'test from api'}) And I have a 404 feedback, I also did the test directly from vimeo with message : Note that the only two fields required are client_id and title. And my scopes token : I don't see where my mistake may be Thanks for your help ! :) -
Create Object (in ViewSet class) with Celery Task in Django
Hello I encountered a problem which i am not able to solve by myself. I tried to call function create_with_celery inside create but it didnt work How should I call create.delay with proper arguments? I don't know how to properly call create function to make workers create objects class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer @app.task(bind=True) def create(self, request): article = Article.objects.create(link=request.data['link']) article.save() serializer = ArticleSerializer(article, many=False) words = WordList(article.link) # take every 90nth word for faster loading only dev approach i = 0 for word in range(0, len(words.list)): # try to take word from database i += 1 try: existing_word = Word.objects.filter(name=words[word]) Word.objects.create( name=existing_word[0].name, advance_level=existing_word[0].advance_level, definition=existing_word[0].definition, article=Article.objects.get(id=article.id) ) print('word nr {}/{} "{}" created from database'.format(i, len(words.list), words[word])) except: # if it's not existing fetch data from web Word.objects.create( name=words[word], advance_level=get_word_frequency(words[word]), definition=get_word_definition(words[word]), article=Article.objects.get(id=article.id) ) print('word nr {}/{} "{}" fetched from web'.format(i, len(words.list), words[word])) response = {'message': 'Article created ', 'result': serializer.data} return Response(response, status=status.HTTP_200_OK) -
Django3: How to load JS file according to the app
I am working on a Django app and the client is looking forward to add more related apps with it. The main difference is the app.js file I am using for one app is not at all needed in another and need a different file instead. How can I crack this? -
Remove second key/value from dict (django)
I need to remove the second key/value from a dict. It's always the second one. The values differ. What's the best way to do this? -
Why is my Django test failing when the view actually works?
I have a class based view that works as designed in the browser. I'm trying to write unit tests for the view and they keep failing. I'm wondering why. The view (the UserPassesTest is whether the user is a superuser or not): class EditUserView(LoginRequiredMixin, UserPassesTestMixin, TemplateView): """handles get and post for adding a new AEUser""" template_name = 'editUser.html' title = 'Edit User' def get(self, request, *args, **kwargs): """handles the GET""" post_url = reverse('edit_user', args=[kwargs['user_id']]) usr = get_object_or_404(AEUser, pk=kwargs['user_id']) form = EditUserForm(initial={'is_active':usr.is_active, 'is_superuser':usr.is_superuser}, \ user=usr, request=request) return render(request, self.template_name, \ {'title_text':self.title, 'post_url':post_url, 'form':form}) The Test Case: class TestEditUser(TestCase): """test the AddUser view""" @classmethod def setUpTestData(cls): cls.user = AEUser.objects.create_user(username='shawn', email='shawn@gmail.com', password='test') cls.user.is_superuser = True cls.user.save() def setUp(self): self.client = Client() def test_get(self): """tests the GET""" self.client.login(username=self.user.username, password=self.user.password) get_url = reverse('edit_user', args=[self.user.id]) response = self.client.get(get_url, follow=True) self.assertEqual(self.user.is_superuser, True) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'editUser.html') I have 3 asserts in the test case. If I comment out the last two, and only assert that the user is a superuser, the test passes. For whatever reason, though, on the other two asserts, I get failures. The error I receive is: AssertionError: False is not true : Template 'editUser.html' was not a template used to render the response. … -
Django: How to use background task to frequently update timestamp of a model daily or weekly based on frequency of recurrence
I am trying to automatically update the timestamp of a recurring Menu Model based of it's frequency of recurrence. when a user creates a menu and isrecurring is set to True, if the frequency of recurrence is daily, change the timestamp to the current date, on a daily basis, if the frequency of recurrence is weekly, change the timestamp to the current date, on a weekly basis, if the frequency of recurrence is every 2 weeks, change the timestamp to the current date every 2 weeks and so on. But if isrecurring is False, leave the timestamp as the initial date the menu was created. models.py class Menu(models.Model): none = 0 Daily = 1 Weekly = 7 EVERY_2_WEEK = 14 EVERY_4_WEEK = 30 Frequency_Of_Recurrence = ( (none, "None"), (Daily, "Daily"), (Weekly, "Weekly"), (EVERY_2_WEEK, "Every 2 week"), (EVERY_4_WEEK, "Monthly"), ) # removed fields that are not required here isrecurring = models.BooleanField(default=False) frequencyofrecurrence = models.IntegerField(choices=Frequency_Of_Recurrence) datetimecreated = models.DateTimeField(verbose_name='timestamp', default=timezone.now) How do I achieve this using background task, or any task scheduler. Thanks in advance. -
RecursionError:maximum recursion depth exceeded
i'm building an e-commerece and when i try to add more than one orderitems to the order but i get this error enter image description here . Any help is appreciated . def Cart(request): `enter code here` customer=request.user.customer if request.user.is_authenticated: order,status=Order.objects.get_or_create(customer=customer,complete=False) items=order.orderitem_set.all() else: items=[] context={"items":items} return render(request,'store/Cart.html',context) and this the tree models class Customer(models.Model): user=models.OneToOneField(User,null=True,on_delete=models.CASCADE,blank=True) name=models.CharField(max_length=200,null=True) email=models.EmailField(null=True,help_text='A valid email address,please.') objects = models.Manager() def __str__(self): return self.name class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True) date_orderd=models.DateField(auto_now_add=True) complete=models.BooleanField(default=True,null=True,blank=False) transaction_id=models.CharField(max_length=200,null=True) objects = models.Manager() def __str__(self): return str(self.pk) class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True) quantity=models.IntegerField(default=1,null=True,blank=True) date_added=models.DateField(auto_now_add=True) objects = models.Manager() def __str__(self): return self.product.name @property def get_total(self): total=self.product.price*self.quantity return self.get_total -
Django get username of logged in user and pass it to models
I am creating a project in django in which I have two diff users i.e. Customers and restaurants. I am creating a model for Menu in which I want add to add user name of logged in user to restaurant name in models. Is there anyway to do this. I have searched through the net got answers like foreign key but not able to implement. Also I need username in views to search from database according to username. Models.py class menu_details(models.Model): restaurant_name = models.CharField(blank=True, max_length=20) dish_name = models.CharField(blank=True, max_length=20) dish_type = models.CharField(max_length=10, choices=food_type, default='veg') price = models.CharField(blank=True, max_length=20) description = models.TextField(blank=True, max_length=5000) image = models.ImageField0(blank=True) class Meta: db_table = "menu_details"