Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to query a list django
def get_queryset(self): result = Tenants.objects.all() filters = self.request.GET.get('filter') if filters is not None: filters = filters[1] if filters[1] == ',' else filters filters_list = filters.split(',') filter_result = Tenants.objects.none() for value in filters_list: filter_result = filter_result | result.filter(Q(business_type__icontains=value) |Q(category__icontains=value)) return filter_result return result.all() here i want the query parameters to be business_type and category when using get method and checking the data i am only able to filter one field either business_type or category when using filter twice like /?page=1&filter=business_type&filter=category then i am getting the data i want but i need the data when the url is like /?page=1&filter=business_type,category -
relation does not exist Django Postgresql Dokku
I created a new model on my already existing Django app.When i updated my git I did these: git pull git push dokku main Then i did these: python3 manage.py makemigrations python3 manage.py migrate But i get this error whenever i try to do an operation: relation "accounts_articleimageshared" does not exist Why?? I don't want to dump my already existing database because i would have to dump it everytime i try to update my app.How can i solve this? -
How to get instance of model in UpdateAPIView django REST?
I have a model Request is below class Request(models.Model): PENDING = 1 APPROVE = 2 REJECT = 3 STATUS_CHOICES = ( (PENDING, 'Pending'), (APPROVE, 'Approve'), (REJECT, 'Reject') ) seller = models.ForeignKey( Seller, on_delete=models.CASCADE, related_name='requests', ) owner = models.OneToOneField( UserProfile, on_delete=models.CASCADE, related_name='request', ) reject_reason = models.TextField(default='') status = models.PositiveSmallIntegerField(STATUS_CHOICES, default=1) created_at = models.DateField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) And an UpdateAPIView class RequestDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Request.objects.all() serializer_class = RequestUpdateSerializer permission_classes = (IsAuthenticated, IsAdminOrRequestOwner) name = 'request-detail' # TODO: send an email inform user that the request have been approve or reject def update(self, request, *args, **kwargs): if self.request.user.profile.role != 3: raise serializers.ValidationError( {'detail': 'You do not have permission to perform this action'}) return super().update(request, *args, **kwargs) What I need is to send an email to the owner of that Request instance. I have written a function to do that but it has to be called in update() method of UpdateAPIView In order to send an email, it required the data from the Request instance that is being updated. The request data only contains information about status My question is what is the proper way to get the Request instance inside the UpdateAPIView. My approach is to get the id from kwargs params and … -
Backend problem in running someone else's Django project | error: 'form 1 is invalid'
I have downloaded the following project from GitHub-https://github.com/sanjaysupanch/Online-Company-Management-Website and run it on my Windows 10 system through the cmd prompt. After creating the virtual environment and running makemigrations, migrate and runserver, the login page opens up. When I proceed to create a new user by clicking on 'Register', there two options 'Employee' and 'Company'. After choosing 'Company', I fill in the details and click on 'Register' but then, receive the error 'form 1 is invalid'. I tried to register as an Employee and that option gave me the same error as well. I am new to Django Python Web Development and this project isn't my own. I suspect this problem has something to do with the backend database but can't figure what the problem might be. Please help me. (A thing to note- When I create a superuser through the cmd prompt, I am able to log into the website through that username and password.) (PS- I wasn't able to attach any screenshots due to the size limit. If something is unclear, please let me know and I'll clarify. Thanks and cheers!) -
How to list messages in order in Django
SO I have been trying to implement a basic one to one chat system in Django. So far, I have created a model that takes in two foreign keys( sender, recipient) and a Charfield by the name of message. class message(models.Model): sender=models.ForeignKey(User,related_name='sender2',on_delete=models.CASCADE) receiver=models.ForeignKey(User,related_name='reciever2',on_delete=models.CASCADE) message1=models.CharField(max_length=10000000) Now, I am able to create message objects but what I want to do is display in a back-and forth conversation on one single page. I have so far been able to fetch all messages for a particular "sender-receiver" combination. def view_message(request,pk): client1=User.objects.get(id=pk) client2=request.user message1=message.objects.filter(sender=client1,receiver=client2).all() return render(request,'message.html',{'messages':message1}) Now the above view just shows all messages for the single user who logged in, sent to the other user whose Primary key is being used/clicked on, But I also want to show are "replies" they receive in a conversation-style manner and in order. Hopefully, You guys understand what I am saying here. A one-to-one private messaging system (not asynchronous), so the page can refresh and reload all messages sent and received but in order. Thank you :) -
Convert string to User pk after posting a form with Django Rest Framework
I am trying to build a feature with AJAX and DRF whereby a user can follow another user. However when I initiate it, the POSTed data does not appear to be hitting the DRF endpoint so I am getting no errors beyond: {user: ["Incorrect type. Expected pk value, received str."],…} following_user: ["Incorrect type. Expected pk value, received str."] user: ["Incorrect type. Expected pk value, received str."] When I hardcode in a couple of integers to the AJAX call it works, so I just need to convert the usernames which are passed as strings to their relevant IDs, I don't know how to do this, however. Here is my js function: const followUser = function(followedUser){ var pathArray = window.location.pathname.split('/'); var currentUser = 'ben' console.log(followedUser); console.log(currentUser) $.ajax({ type: 'POST', url: '/api/userconnections/', data: { csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value, 'user': currentUser, 'following_user': followedUser }, success: function(data) { alert('Successfully Followed') }, error: function (jqXhr, textStatus, errorThrown) { console.log('ERROR') console.log(jqXhr) }, }); } Here is my serializer: class UserConnectionListSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField() following_user = serializers.StringRelatedField() class Meta: model = UserConnections fields = ['user','following_user'] class UserConnectionSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = '__all__' Here is my models.py file class UserConnections(models.Model): user = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) following_user = models.ForeignKey(User, … -
Change database cached data django while model is updated
I have a model that has a mapping to external API data. For example class Local(models.Model): external_mapping_id = models.IntegerField() name = models.CharField(max_length=255) url = models.UrlField() when I change the name or URL of this model it sends a patch request to the external API and changes the object there too. And I have an endpoint that I cache for 1 hour which shows a list of external objects. The problem is that I can't see updated external objects while I change url or name. Because of cache. How can I change cached data to fit updates without removing caching? CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'google_service_cache', } } -
How to send Email in Django using office365
I am working in a project where I need to send the email to the user who is filling the Email in the form. I am able to send email by using my Gmail Account details but while using outlook.365. This is the image with error that I am getting. My requirement is : Once users come in the registration form and fill the details as Name, Email, Mobile Whatever Email is put there in the form, send the email with link to create new password. Here is my code: settings.py: # Using outlook365: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'support@academic.com' EMAIL_HOST = 'smtp.outlook.office365.com' # (also tried : smtp.office365.com and outlook.office365.com) EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = 'My_Password' # Using my gmail account: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'admin@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = 'My_Password' views.py: subject = "Academic - Create New Password" message = "Hi %s! Please create your new Password here : http://127.0.0.1:8000/api/create-password" % firstname send_mail( subject, # Subject of the email message, # Body or Message of the email 'support@academic.com', # from@gmail.com (admin@gmail.com for gmail account) [email], # to@gmail.com # email that is filled in the form ) Please guide … -
Nginx serving Django static files must have folder with same name as URL
I am serving static files using Nginx. My config looks like this: # django settings STATIC_URL = '/static_folder/' STATIC_ROOT = '/app_data/' # nginx config location /static_folder/ { root /app_data/; } It does not work like this. I need to change the STATIC_ROOT to include the static_folder part. Like this: # django settings STATIC_URL = '/static_folder/' STATIC_ROOT = '/app_data/static_folder/' # <-- here # nginx config location /static_folder/ { root /app_data/; } I want to be able to serve like this: /app_data/logo.png instead of this: /app_data/static_folder/logo.png It is not a big deal if you have one URL part in STATIC_URL but if I use nested URLs, I need to repeat it in STATIC_ROOT too. It gets too deep. For example: # django settings STATIC_URL = '/static_folder/and/another/folder' STATIC_ROOT = '/app_data/static_folder/and/another/folder/' # nginx config location /static_folder/ { root /app_data/; } How can I get rid of this and serve files in /app_data/ without including static_url parts in the folder structure. -
ModuleNotFoundError: No module named 'djfilter.wsgi.application'; 'djfilter.wsgi' is not a package
I am trying to deploy Django app on Heroku ModuleNotFoundError: No module named 'djfilter.wsgi.application'; 'djfilter.wsgi' is not a package -
Django ModelChoiceField display like charField
the ModelChoiceField that should display a list of some type of user, but instead it displays like a charfield ( figure 1 ) figure1 this is my views.py @login_required def create_appointement(request): user = User() if request.method=='POST': appointment = request.POST['type'] if appointment=='register patient': form_appointment = AppointmentForm_2(request.POST or None) if form_appointment.is_valid(): form_appointment.save(commit=False) form_appointment.user_ho_add = request.user start_time = form_appointment.start_time future_time = dt.datetime(1970, 1, 1, start_time.hour, start_time.minute, start_time.second, start_time.microsecond) + timedelta(minutes=30) form_appointment.end_time = dt.time(future_time.hour, future_time.minute, future_time.second, future_time.microsecond) form_appointment.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request, 'appointement/add_appointement2.html', {'user_form':form_appointment, } and this my forms.py class AppointmentForm_2(forms.ModelForm): doctor = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.DOCTOR)) patient = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.PATIENT)) date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), input_formats=settings.DATE_INPUT_FORMATS) start_time = forms.DateField(widget=forms.DateInput(attrs={'type': 'time'}), input_formats=settings.TIME_INPUT_FORMATS) class Meta: model = Appointment fields = ('patient', 'doctor', 'date', 'start_time') the doctor field work perfectly but the patient field dont work and this is my models.py class Appointment(models.Model): user_ho_add = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_ho_add_appointment') patient = models.CharField(null=True,max_length = 200, default=defaultTitle) doctor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='doctor_app') date = models.DateField(null=False, blank=False, default=timezone.now) start_time = models.TimeField(null=True, blank=True, default=timezone.now) end_time = models.TimeField(null=True, blank=True, default=timezone.now) is there a way to make the patient field display a choice field? -
Django APIClient.post sends data in list which has issues when you use pop
So I already have a working api endpoint for creating my model. If I use post man by sending it this data in the body. Everything works fine { "field1": "test", "field2":"test", "field3":"test" } But if I try to create a test for it by doing this: new_data = { "field1": "test", "field2":"test", "field3":"test" } resp = self.client.post(reverse('item_rest-list'), data=new_data) And in my create function in view I pop some fields like so: def create(self, request, *args, **kwargs): field1 = request.data.pop('field1', None) field1 becomes a list because request.data value is like this: { "field1": [u"test"], "field2":[u"test"], "field3":[u"test"] } If I do a .get rather than .pop i get it as a string but I need to remove it from the parameters because of some business logic. field1 = request.data.get('field1') Is there a way to make test not convert it to test? so to summarize. request.data value if coming from postman is this: { "field1": "test", "field2":"test", "field3":"test" } but if coming from self.client.post, its like this { "field1": [u"test"], "field2":[u"test"], "field3":[u"test"] } -
installing a package in pycharm+docker
As part of django-cookiecutter I have a docker container which has the python+packages to host the app. The app works on localhost:8000 so it's all there. That was set up by a script via django-cookiecutter. I'm trying to hook PyCharm to the docker container and it all looks like it's working but bugs me about a new package I tried installing (2 different ways - one through docker desktop-> django-> cli, and the other through pycharm) These sections should help diagnose the problem but in the event viewer it says it installed but I don't know where it installed because it says at the top that it's not installed, nor is it in the list of packages. -
How to filter for ManytoManyField in generic class-based views
I am trying to filter the queryset for when my model has today's day(like Monday, Tuesday, Wednesday, etc). I made the weekday as a manytomanyfield in my model so that the user could choose multiple weekdays for a single instance of the model. I know the code below for my views is messy, but I hope you guys get it: today = datetime.date.today() today_weekday = 0 if today.weekday() == '0': today_weekday = 'Monday' if today.weekday() == '1': today_weekday = 'Tuesday' if today.weekday() == '2': today_weekday = 'Wednesday' if today.weekday() == '3': today_weekday = 'Thursday' if today.weekday() == '4': today_weekday = 'Friday' queryset = queryset.filter(agent__user=user).filter( class_start_date__lte=today, class_end_date__gte=today, ).filter(weekday=today_weekday) The part I am having trouble with is the last part .filter(weekday=today_weekday). weekday is the manytomanyfield in my model, and I want to check if today's weekday matches one of the weekdays in the model. I hope you guys can help me with this problem. I am sure there are better ways to do it, but I hope you guys can help me fix the .filter(weekday=today_weekday) first, so it is at least functional. Thanks a lot! -
Python & Docker not clean threads
I have docker on my server and premium_daemon.py as daemon which clears the database and cancels orders. premium_daemon.py import time from django.core.management import BaseCommand from django.utils import timezone from adminPanel.models import MyUser, Message, User_purchase, Bot_user, Item from apiV1.bot_services import send_order_canceled class Command(BaseCommand): def handle(self, *args, **options): while True: users = MyUser.objects.filter(is_premium=True) for user in users: if user.premium_expiration_date < timezone.now(): user.is_premium = False user.save() messages = Message.objects.all() for message in messages: if timezone.now() > message.created_at + timezone.timedelta(days=7): message.delete() orders = User_purchase.objects.filter(is_paid=False) for order in orders: admin_user_obj = MyUser.objects.get(id=order.belongs) if order.time_created + timezone.timedelta(minutes=admin_user_obj.booking_time) < timezone.now(): send_order_canceled(order) bot_user = Bot_user.objects.get(belongs=order.belongs, chat_id=order.chat_id) if order.balance_to_return: bot_user.balance += order.balance_to_return bot_user.active_orders -= 1 bot_user.save() try: item = Item.objects.get(id=order.item) if item.strings == '': item.strings = '\r\n'.join(order.strings.split('\n')) else: item.strings = '\r\n'.join((order.strings.replace('\n', '\r\n') + '\r\n' + item.strings).split('\r\n')) item.quantity = len(item.strings.split('\r\n')) item.save() order.delete() except: pass time.sleep(10) docker-compose.prod premium_daemon: build: ./app command: python manage.py premium_daemon volumes: - ./app/:/usr/src/app/ env_file: - ./.env.prod depends_on: - db My htop after 20 mins runing docker: htop As you can see, I have 2400 threads premium_daemon.py How did it works? Why python not cleaning threads? How they create, I don't using threads. How can I clean threads? -
How can I get the full url of the image in DRF?
I am not good at English. I hope you understand. There can be multiple images in the diary. Diary and DiaryImage are in a 1:N relationship. this is my model from django.db import models from userSystem.models import User class Diary(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(User, related_name="diary_user", on_delete=models.CASCADE, null=True) title = models.CharField(max_length=30) content = models.CharField(max_length=800) date_created = models.DateField(auto_now_add=True) class DiaryImage(models.Model): diary = models.ForeignKey(Diary, on_delete=models.CASCADE) image = models.ImageField(default='/media/diary/default_image.jpeg', upload_to='diary', blank=True, null=True) this is my serializer from rest_framework import serializers from diary.models import DiaryImage, Diary class DiaryImageSerializer(serializers.ModelSerializer): image = serializers.ImageField(use_url=True) class Meta: model = DiaryImage fields = ['image'] class DiarySerializer(serializers.ModelSerializer): images = serializers.SerializerMethodField() def get_images(self, obj): image = obj.diaryimage_set.all() return DiaryImageSerializer(instance=image, many=True).data class Meta: model = Diary fields = ['id', 'title', 'content', 'date_created', 'images'] def create(self, validated_data): instance = Diary.objects.create(**validated_data) image_set = self.context['request'].FILES for image_data in image_set.getlist('image'): DiaryImage.objects.create(diary=instance, image=image_data) return instance this is my view from diary.serializers import DiarySerializer class DiaryViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, ] serializer_class = DiarySerializer def get_queryset(self): return self.request.user.diary_user.all() settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py diary_list = DiaryViewSet.as_view({"get": "list", "post": "create"}) urlpatterns = [ path('admin/', admin.site.urls), path('diary/', diary_list, name="diary-list"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I ran this code, the image was saved successfully. However, when loading … -
How to add the source IP in Django Logger in settings.py?
I have the following logger configuration in my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '[{asctime}] {message}', 'datefmt' : '%Y-%m-%d %H:%M:%S', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/home/user/server.log', 'formatter':'simple', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, } It is giving me the logs in the following format. [2021-03-31 13:01:48] Watching for file changes with StatReloader [2021-03-31 13:01:50] "GET / HTTP/1.1" 200 20 However, I also want to get the source IP for HTTP requests like this: [2021-03-31 13:01:48] Watching for file changes with StatReloader [2021-03-31 13:01:50] Source IP : 112.73.20.208 | "GET / HTTP/1.1" 200 20 How can I achieve this? NOTE : I did come across a post regarding something similar but it's not clear, too old and seems abandoned as the comments don't have any response. -
How can i load images in django template with asynchronous system?
I was trying to make asynchronous system in django. I've used Channels for this purpose, and i was trying to send the image url to my template and display the image on the template page. But it didn't work. Here is my settings.py file STATIC_URL = '/static/' import os STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Here is how i send the data from the database. class WSConsumer(WebsocketConsumer): def connect(self): self.accept() x = Student.objects.filter(id=1) self.send(json.dumps({ 'name':x[0].name, "img":x[0].image.url, })) index.html file {% load static %} <!DOCTYPE html> <html> <head> <title>Index</title> </head> <body> <div id='img'></div> <script> var socket = new WebSocket('ws://localhost:8000/ws/some_url/'); socket.onmessage = function(event) { var data = JSON.parse(event.data); console.log(data); var url = data.img var el = document.getElementById("img"); el.innerHTML=`<img src= ${url}>`; } </script> </body> All the asynchronous system works perfectly.The js is already getting the image but it's not displaying the image but the other data. -
How to convert currency in Django?
I have to make conversions between currencies in my Django project. This app has multiple customers and every customer has credit_limit field. Every customer's credit limit amount can be in a different currency and I have to convert all of them to the USD. Because I have a dashboard page and I display some charts with doing operations with these currencies like adding etc... I used django-money and works fine, but it returns Money field and I cannot display it in charts because it is not a float or int field. How can I convert my currencies and return integer of float values? Thanks for any helping. Here are my codes: views.py def customer(request): form_class = NewCustomerForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': form = NewCustomerForm(request.POST) if form.is_valid(): newCustomer = form.save() newCustomer.company = company selected_currency = newCustomer.currency_choice selected_limit = newCustomer.credit_limit newCustomer.usd_credit_limit = convert_money(Money(selected_limit, selected_currency), 'USD') newCustomer.save() return redirect('user:customer_list') else: form = form_class() return render(request, 'customer.html', {'form': form}) models.py class Customer(models.Model): ... CURRENCIES = [ ('USD', 'USD'), ('EUR', 'EUR'), ('GBP', 'GBP'), ] currency_choice = models.TextField(max_length=50, default='Select', choices=CURRENCIES) credit_limit = models.FloatField(default=0, null=True) usd_credit_limit = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', null=True, default=0) risk_rating = models.CharField(max_length=50, default='Select', choices=RISK_RATING, null=True) -
django uuid or hashid field for primary keys? and how to prefix the generated ids with say "cust_"
I am currently using django-shortuuidfield to generate a unique UUID primary key on the Customer model as shown below class Customer(models.Model): customer_id = ShortUUIDField() user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False) This guarantees that the customer_id field is unique with space and time. However, this generates an id similar to B9fcKdMDHbwKCBoADjbNyA and I want to prefix this with cust_ to make it like this cust_B9fcKdMDHbwKCBoADjbNyA. How do I achieve this without making multiple db calls? I also looked into django-hashid-field which supports prefixes out of the box but this does not guarantee UUID, and on a larger scale, we may run into unique contain failed issues that are not desirable. Any thoughts on this? Let me know... -
How to fix "Key (username)=() already exists." error
I want to create a user with type 'learner'using mobile nummber,when i am trying to do this there is an error, django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_user_username_key" DETAIL: Key (username)=() already exists. views.py class Register(APIView): def get_permissions(self): return (AllowAny(),) def post(self, request, *args, **kwargs): mobile = request.data.get('mobile') if mobile: data = {'mobile': mobile} serializer = RegisterSerializer(data=data) if serializer.is_valid(raise_exception = True): serializer.save() return Response('sucess') else: return Response('error') serializers.py class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('mobile',) def create(self, validated_data): user_data = validated_data.pop('user') user_data['user_type'] = 'learner' user_serializer = UserSerializer(data=user_data) user_serializer.is_valid(raise_exception=True) user = user_serializer.save() user.groups.add(validated_data['group']) user.save() return user instance = self.Meta.model(**validated_data) instance.user = user instance.save() return instance -
How to display a pickled set in Django admin interface?
I have a model, which has a BinaryField, which I use to store a short set of strings. It might not look like the most elegant solution, but it's what I have to work with for now: class Player(models.Model): player_id = models.CharField(max_length=32, primary_key=True) _awards = models.BinaryField(null=True) def set_awards(self, data): self._awards = pickle.dumps(data) def get_awards(self): return pickle.loads(self._awards) The field works fine, I just want to display that _awards set in the admin interface. I tried this, but it didn't work: class PlayerAdmin(admin.ModelAdmin): list_display = ('player_id') readonly_fields = ('_awards') def _awards(self): return self.get_awards() Instead of a list, I get this in the admin interface: <memory at 0x105a81040> -
Is there a way to display a html page both in another page and with its own URL?
I am working on a web app to display details on electronics boards based on a database. I have two ways of displaying results to a search : The first way is to click on a board and it makes you go on the detail page (so this page has its own URL an I can pass it to somebody else) The second way is to compare multiple boards and the details are shown on the same page (just under the boards I selected to compare) Both ways display the same html page called "details.html" Here is my problem : To make the first way work, I used {% extends "base.html" %} and I created a block in the latter so I still have all the menus (that are in "base.html" file) the available in the details page. first way However, to make the second way work, I would like to put the html of "details.html" in a div so that it is displayed on the same page. But, because of the {% extends ...%}, all the menus from "base.html" are also displayed... (which seems logical because I made it so it is displayed for the first way to work.) … -
How to perform inner Join To get customer from Common City In Django ORM?
I have following table. Salesman salesman_id | name | city | commission -------------+------------+----------+------------ 5001 | James Hoog | New York | 0.15 5002 | Nail Knite | Paris | 0.13 5005 | Pit Alex | London | 0.11 5006 | Mc Lyon | Paris | 0.14 5007 | Paul Adam | Rome | 0.13 5003 | Lauson Hen | San Jose | 0.12 And another table named Customer. customer_id | cust_name | city | grade | salesman_id -------------+----------------+------------+-------+------------- 3002 | Nick Rimando | New York | 100 | 5001 3007 | Brad Davis | New York | 200 | 5001 3005 | Graham Zusi | California | 200 | 5002 3008 | Julian Green | London | 300 | 5002 3004 | Fabian Johnson | Paris | 300 | 5006 3009 | Geoff Cameron | Berlin | 100 | 5003 3003 | Jozy Altidor | Moscow | 200 | 5007 3001 | Brad Guzan | London | | 5005 I want to get salesman name, customer name and their cities for the salesmen and customer who belongs to the same city. I can write this query in SQL but I am not been able to hook up with ORM. SELECT … -
how to implement two user types (seller and customer or buyer) using django allauth like fiverr?
I am working on a web e-commerce project where there will be two types of user (seller, customer).I have been wondering how to implement the logic like fiverr seller and buyer. I have created a user account with two flags yet (is_seller, is_customer). class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, blank=True) customer = models.ForeignKey('Customer', on_delete=models.CASCADE) is_seller = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() I don't know if it is the good approach. what will be the best approach to this kind of scenario? kindly Someone guide me. Any help will be appreciated.