Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django default image upload preview
Good day, is there any tool for Django out-of-the-box to preview images before upload? I'd like to add this feature without JS scripts or Django modules. -
Django Rest Framework creatable fields and updatable fields
Below is my sample model: class DemoModel(models.Model): field_one = models.IntegerField() field_two = models.IntegerField(blank=True, null=True) The Serializer: class DemoSerializer(serializers.ModelSerializer): """ Here only field_one should be creatable and only field_two should be updatable """ class Meta: model = models.DemoModel fields = '__all__' My question is how can I write the view for this serializer and model, so that when using the post method the client can not add data for the field_two field. Client can only add data to field_one. But while updating, the client can update the value of field_two, but can not update the value of field_one field. Thank you -
How to process the data in realtime that received with a Django made API?
I'm new to Django. Currently, I've built an API with Django. The frontend would use this API to POST the data to mysql DB. Now I want to do some realtime process. Once the frontend POST data, I can instantaneously aquire and process(e.g. some algorithm with python) the data. Is it possible? How can I know when I received the data? Is it possible to get this data without access the DB? Where should I put the code to process the received data(in a new file or in models.py,views.py,serializers.py)? # models.py class Room(models.Model): code = models.CharField(max_length=100, default="", unique=False) host = models.CharField(max_length=100, unique=True) #serializers.py class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = ('id', 'code', 'host') #views.py class RoomView(generics.ListCreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer def home(request): q = request.GET.get('q') if request.GET.get('q') != None else '' rooms = Room.objects.filter( Q(Room__host__icontains=q) ) return render(request) #Once frontend POST data. def process(): tcp_client_socket.send(latestdata['host']) ... -
Passing Id and Context in Django Redirect
I want to pass a model to a html page as context when I login into an account. My Home page url comes with user id as a url parameter. But i cant pass any context in redirect views.py from django.contrib.auth import authenticate,login,logout from django.contrib import messages from django.shortcuts import redirect, render from django.http import HttpResponse from .models import users from home.models import Posts def f1(request): Post = Posts.objects.all() context = {'Post':Post} if request.method == "POST": username = request.POST['username'] password = request.POST['password'] uz = authenticate(request,username=username, password=password) if uz is not None: login(request,uz) id = users.objects.filter(name=username).values('id')[0]['id'] return redirect('home',id) # This Works Fine return redirect('home',id,context) # This is not Working else: messages.error(request,"Wrong Credentials") return render(request,'login.html') urls.py from django.contrib.auth import logout from django.urls import path from . import views urlpatterns=[ path('<str:users_id>/',views.func,name="home"), ] How can I pass the context? If I can't tell me an alternative way to do it. #Thanks -
Ruserver is fine; Getting error while migrate - Django
while running server its working fine; website working fine; everything is fine. but when I am trying migrate something I am getting error as below. even if I am adding new model and trying to do makemigrations and migrate everything happening and working fine, but migrate shows error as below. couldn't find out the problem. Operations to perform: Apply all migrations: admin, auth, contenttypes, pmp, sessions Running migrations: Applying pmp.0035_alter_tests_reports_visit...Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: new__pmp_tests_reports.visit_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\py\patient_management_project\manage.py", line 22, in <module> main() File "E:\py\patient_management_project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 131, in migrate state = self._migrate_all_forwards( File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line … -
'NoneType' object is not iterable in Django
I am getting this error when I create a new course. Please help to solve this. My admin panel shows 'Courses' then I click 'add' button but when I save it shows this error TypeError at /admin/course/course/add/ 'NoneType' object is not iterable Request Method: POST Request URL: http://127.0.0.1:8000/admin/course/course/add/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: 'NoneType' object is not iterable Exception Location: C:\Users\bilol\AppData\Local\Programs\Python\Python37-32\lib\site-packages\parler\models.py, line 759, in save_translations Python Executable: C:\Users\bilol\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.3 Python Path: ['C:\\Django\\mysite', 'C:\\Users\\bilol\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\bilol\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', Here is my model. I made migrations. class Course(TranslatableModel): STATUS = ( ('True', 'True'), ('False', 'False'), ) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=30) keywords = models.CharField(max_length=255) description = models.CharField(max_length=255) image = models.ImageField(blank=True, upload_to='images/') status = models.CharField(max_length=10, choices=STATUS) slug = models.SlugField() create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title -
InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3':
I am getting the error "InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3': No module named parse" while loading the django application from obuntu. Can anyone help on this? regards Mallika -
Django template inheritance {% include %} with model set
This is for a simple blog that you can comment on each post. I'm getting an error when I try to include a template to a parent template. The variables are not getting passed. I understand that templates cannot pass their context to each other. My main.html is a list view of posts. Each post has another list of comments. {% for comment in post.comment_list|slice:"0:7" %} {% include 'blog/comments.html' with comment=comment %} {% endfor %} My comments.html is the template for each comment. <div><h1> {comment.username} {comment.id} {comment.body} </div></h1> What can I do here to make this work? -
Django Form Wizard dynamic form not aligning
I have a very specific issue with my Form Wizard, and after a lot of tinkering I just can't figure it out. I tried googling it but I think it's too specific. At step 3, the user has the option to add "contacts". When they press the button I have a little JS script that generates a form. Consecutive forms can be added and will be aligned in rows of 2. Once you go to the next step you have the option to return to the previous step if you forgot something. But, when you do, the 2 contacts that were filled in will appear in their separate row instead of the same row. (See pictures) I have no idea why this is happening. I'm really hoping on a sort of guru who had this happen to them or can spot something in the code. Thanks in advance! init.js function hideInitialFormset(prefix, row) { let fields = []; if (prefix === "contacts") { fields = [$('#id_contacts-0-name').val(), $('#id_contacts-0-funct').val(), $('#id_contacts-0-email').val()]; } let total = $('#id_' + prefix + '-TOTAL_FORMS'); if (total.val() === '1') { if (fields.includes('')) { row.hide(); total.val('0'); } } } main.js function total_field(prefix) { // get hidden field with jQuery once … -
How to make a dependent combo loading work when CreateView is used in django?
I have a Project Model. And I have a Feature model which has the Project model as foreign key. Now I have a StatusUpdate model, which has both Project model and Feature model as the Foreign keys. Now on a StatusUpdate create page, only the feature names of the selected project name should be loaded, when we select a project name. Models: class Project(models.Model): project_name = models.CharField(max_length=100, unique=True, verbose_name='Project Name') from projects.models import Project class Feature(models.Model): feature_name = models.CharField(max_length=100, verbose_name="Feature Name") project_name = models.ForeignKey(Project, verbose_name="Project Name", on_delete=models.CASCADE) from features.models import Feature from projects.models import Project class Statusupdate(models.Model): project_name = models.ForeignKey(Project, verbose_name="Project Name", on_delete=models.CASCADE) feature_name = models.ForeignKey(Feature, verbose_name="Feature Name", on_delete=models.CASCADE) forms.py from .models import Statusupdate class StatusupdateModelForm(forms.ModelForm): class Meta: model = Statusupdate fields = ['project_name', 'feature_name''] widgets = {'project_name': forms.Select(attrs={'class': 'form-group form-control col-sm-10 '}), 'feature_name': forms.Select(attrs={'class': 'form-group form-control col-sm-10'}) } urls.py from django.urls import path from .views import ( StatusupdateCreateView, StatusupdateDeleteView, StatusupdateListView, StatusupdateUpdateView, StatusupdateDetailView ) app_name = 'statusupdate' urlpatterns = [ path('', StatusupdateListView.as_view(), name='status-list'), path('create/', StatusupdateCreateView.as_view(), name='status-create'), path('<int:id>/', StatusupdateDetailView.as_view(), name='status-detail'), path('<int:id>/update/', StatusupdateUpdateView.as_view(), name='status-update'), path('<int:id>/delete/', StatusupdateDeleteView.as_view(), name='status-delete'), ] StatusUpdate CreateView from .models import Statusupdate from .forms import StatusupdateModelForm class StatusupdateCreateView(LoginRequiredMixin, CreateView): template_name = 'statusupdate/status_create.html' model = Statusupdate form_class = StatusupdateModelForm def form_valid(self, … -
how to loop through a condition in Django template
I'm attempting to display "you don't have active investment" just when there are no investments, however I've discovered that whenever the loop runs, it displays the same message regardless of whether or not there are any investments. I believe I have given enough information to anyone who is willing to give it a trial. The code snippet is below, along with a screenshot at the bottom. <h1 class="md:ml-[11.5em] mt-7 mb-0 font-bold"> Active Plan</h1> {% for investment in investments %} {% if investment.is_active == True %} <div class="row justify-center my-5 md:my-3"> <div class="col-md-9 border-2 border-gray-300 rounded-lg"> <div class="pricing-table-item bg-athens-gray px-4 md:py-0"> <div class="space-y-10 md:flex justify-between items-end"> <div> <h1 class="font-bold capitalize" style="font-family: Open Sans;">{{investment.plan}}</h1> <div class="text-sm my-2" style="font-family: Open Sans;"><span class="text-gray-400">Invested Amount -</span> <span class="font-bold">{{investment.deposit_amount}} USD</span></div> </div> <div class="flex justify-between align-items-center"> <div> <h1 class="font-bold capitalize" style="font-family: Open Sans;">{{investment.created_at}}</h1> <div class="text-sm my-2 text-gray-400" style="font-family: Open Sans;">Start Date</div> </div> <div class="ml-3 mr-3"> <i class="fa-solid fa-arrow-right-long text-gray-400"></i> </div> <div> {% if investment.plan == "Basic - Daily 2% for 180 Days" %} <h1 class="font-bold capitalize" style="font-family: Open Sans;">{{investment.due_date}}</h1> {% else %} <h1 class="font-bold capitalize" style="font-family: Open Sans;">{{investment.due_date}}</h1> {% endif %} <div class="text-sm my-2 text-gray-400" style="font-family: Open Sans;">End Date</div> </div> </div> <div class="md:flex justify-center items-center"> <div> {% … -
I have a project how to deploy it to different servers automatically?
I have a project that created with django. I finished it and deploy it to a ubuntu server but someone want to deploy this project to in own ubuntu server and it is take much time to up this project in a server as you know. So I wonder about is there any way to deploy a product automatically like with bash script file or python script file. I want to give an instance for what I really want. As you know there is nothing inside a new server. So my project has requirements like docker, postgresql etc. I want to write a script that install all requirements, create a database or what I wish. Is this possible? -
Django rest framework : Generics custom method for "RetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView)" not working
In this generic APIView when I'm trying to log in through a nonadmin user it is giving "detail": "You do not have permission to perform this action." but working fine for admin user. I don't whether the problem is in code or permission.py I've shared my Views.py, permissions.py and models.py for the same. class BookingRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsUserOrIsAdmin] # queryset = Booking.objects.all() # serializer_class = BookingSerializer def get_queryset(self): if self.request.user.is_admin == False: user_data= self.request.user book = Booking.objects.filter(user= user_data) return book else: book = Booking.objects.all() return book serializer_class = BookingSerializer permissions.py from django.contrib.auth import get_user_model from rest_framework.permissions import BasePermission User = get_user_model() class IsUserOrIsAdmin(BasePermission): """Allow access to the respective User object and to admin users.""" def has_object_permission(self, request, view, obj): return (request.user and request.user.is_staff) or ( isinstance(obj, User) and request.user == obj ) views.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','contact_number','gender','address','state','city','country','pincode','dob'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible … -
Error- unsupported operand type(s) for -: 'str' and 'datetime.timedelta' In Django
Hi Everyone i have working on Django-framework, I am created on function where i give parameter start_date and end_date, i am trying get previous week start_date and end_date based on start_date but getting Error - unsupported operand type(s) for -: 'str' and 'datetime.timedelta', please help me out. from datetime import datetime, timedelta, date def report(request): start_date = request.GET.get('start_date') print(start_date) # 2022-06-06 end_date = request.GET.get('end_date') print(end_date) # 2022-06-12 last_week_start_date=start_date - timedelta(days=7) last_week_end_date=last_week_start_date + timedelta(days=6) d_report = connection.cursor() d_report.execute('''select * from table where start_date=%s and end_date=%s''',[start_date,end_date]) -
How to fetch row data value or id from datatable on checkbox and add in to the broadcast list select in django python template?
How to fetch row data value on checkbox select and add to the list on button click event? We are trying to get values on select on check box and try to add on list but we don't know how to integrate django variable to javascript? I am new to python and djnago so need guidence javascript code: function showDiv() { var form = document.getElementById("myform"); form.submit(); } function selectAll(){ var ele=document.getElementsByName('seluserid'); for(var i=0; i<ele.length; i++){ if(ele[i].type=='checkbox') ele[i].checked=true; } } function deSelectAll(){ var ele=document.getElementsByName('seluserid'); for(var i=0; i<ele.length; i++){ if(ele[i].type=='checkbox') ele[i].checked=false; $(".btnbrdcstlist").hide(); } } function getvalues() { var val = []; $(':checkbox:checked').each(function (i) { // alert("In each function"); val[i] = $(this).val(); console.log(val[i]); }); } function Showbrdcstbtnv() { if ($('.cstm').is(":checked")) $(".btnbrdcstlist").show(); else $(".btnbrdcstlist").hide(); } function showDiv() { var form = document.getElementById("myform"); form.submit(); } Html Code: <button class="btn btn-primary" type="button" id="selectall" onclick="selectAll(),Showbrdcstbtnv(this)">Select All</button> <button class="btn btn-primary" type="button" id="deselectall" onclick="deSelectAll()">Deselect All</button> <!-- Checkbox select Datatable start for opt-1 --> <div class="row justify-content-end btnbrdcstlist " id="btnbrdcstlist" style="display:none"> <a href="{% url 'adduser' bid=adduser.id %}" class="btn btn-primary" style="margin-bottom: 15px;">Add To Broadcastlist</a> </div> Datatable code : <table class="table nowrap checkbox-datatable" id="usertbl"> <thead> <tr> <th> <!-- <div class="dt-checkbox"> <input type="checkbox" name="select_all" value="1" id="example-select-all" class="cstm" onclick="Showbrdcstbtnv(this)" /> <span class="dt-checkbox-label"> </span> </div> … -
Django Rest Framework gives "I/O operation on closed file" this kind of error while uploading an image
When i try to create objects in a loop which contains data in image field, in first time the object is created and in the next iteration it gives "I/O operation on closed file" this kind of exception. for student in data: student_obj = StudentRegistration.objects.filter(id=student) student = student_obj.first().name if student: obj = StudentDetails.objects.create(student=student_obj.first(), age=request.data.get('age'), photo=request.FILES.get('photo'), created_on=created_on_time) -
Ternary codes of countries in django_countries
I need to list the ternary codes of countries in django_countries but I can not reach the list my import : from django_countries import countries ... def populate_countries(): for country in list(countries): Country.objects.get_or_create( country_name=country.name, country_code=country.code ) ... >>> AttributeError: 'CountryTuple' object has no attribute 'alpha3' How can I reach them? -
How can I split deployments of Django apps in the same project with shared models and database?
I have an architectural question: We have a Django project made of multiple apps. There is a core app that holds the main models used for the other sets of apps. Then, we have a couple apps for user facing APIs. Lastly, we have some internal apps and tools used by developers only that are accessible in Admin UI as extended features. Our deployment process is very monolithic. We use Kubernetes and we deploy the whole project as a whole. Meaning that if we only had changes in an internal app and we need that in production, we will build a new Docker image and deploy a new release with a new version tag incremented. I'm not a big fan of this because change in internal tools shouldn't create a new release of the user facing applications. I have been wondering if there is a way to split those deployments (maybe make them into a microservice architecture?). So we could deploy the user facing applications separate from the internal tools. I know I could build separate images, tags and everything for parts of the project but I'm not sure how they could communicate between each other if internal_app_1 depends on … -
django.db.utils.OperationalError: sub-select returns 8 columns - expected 1
I'm attempting to generate a QuerySet that collects all the tags that are posted in all of a given user's posted questions. On top of that, annotate over each Tag instance to find out how many times each tag was posted. The problem I'm encountering however is with the following error that is being raised: django.db.utils.OperationalError: sub-select returns 8 columns - expected 1 What is this error referring to and how can it be resolved in order to get the aforementioned desired QuerySet? class TestProfileInstanceTagData(TestCase): @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user("ItsMe") profile = Profile.objects.create(user=cls.user) tag1 = Tag.objects.create(name="TagA") tag2 = Tag.objects.create(name="TagB") tag3 = Tag.objects.create(name="TagZ") question1 = Question.objects.create( title="This is a title about question1", body="This is the post content about question1", profile=profile ) question1.tags.add(tag3) question2 = Question.objects.create( title="This is a title about question2", body="This is the post content about question2", profile=profile ) question2.tags.add(*[tag1, tag3]) question3 = Question.objects.create( title="This is a title about question3", body="This is the post content about question3", profile=profile ) question3.tags.add(tag2) cls.queryset = profile.get_tag_post_data() def test_user_posted_tag_queryset(self): self.assertEqual(self.queryset.count(), 3) class Profile(Model): user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE) def get_tag_post_data(self): questions_with_tag = self.questions.filter(tags__name=OuterRef("name")) return Tag.objects.filter( question__profile=self ).distinct().annotate(count=Count(Subquery(questions_with_tag))) class Tag(Model): name = CharField(unique=True, max_length=25) class Post(Model): body = TextField() date = DateField(default=date.today) comment = ForeignKey('Comment', … -
gpu usage from Cilent Server Runtime Process when running Django 'python manage.py' on localhost:8000
Does anyone have this same issue? My task manager shows Client Server Runtime Process at around 6% after I run the cmd 'python manage.py runserver' on localhost:8000. I've turned on my Hardware-accelerated GPU scheduling on my windows game graphics settings per this video https://www.youtube.com/watch?v=EGBCpB57yWU This worked after I restarted my computer, Client Server Runtime Process showed 0% gpu.. but as soon as I run my dev server it went back to around 6%. I scanned my pc with Norton and Malwarebytes.. nothing.. Updated everything to no avail. CPU: i7 9700k GPU: 2070 super 30gb ram 1tb Samsung M.2 for boot -
how to set DTL(Django Tamplate language) for loop and value through javascript
I want to set django for loop to set value through javascript like this. is this correct way? or Is there any other way? var table = $('.checkbox-datatable').DataTable({ 'scrollCollapse': true, 'autoWidth': false, 'responsive': true, "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]], "language": { "info": "_START_-_END of TOTAL_ entries", searchPlaceholder: "Search", paginate: { next: '<i class="ion-chevron-right"></i>', previous: '<i class="ion-chevron-left"></i>' } }, 'columnDefs': [{ 'targets': 0, 'searchable': false, 'orderable': false, 'className': 'dt-body-center', 'render': function (data, type, full, meta){ return '<div class="dt-checkbox"><input type="checkbox" name= "id[]" id="chkuser" value="' + {% for dd in departmentData %}{{dd.id}}{% endfor %} + '" /><span class="dt-checkbox-label"></span></div>'; } }], 'order': [[1, 'asc']] }); -
What the best online storage option for my Django project? [closed]
I’m fairly new to Django and would like to know about the best available online storage options. I’ve done some research and I saw something about Amazon Web Services (AWS). Are there any other popular options that’s free where I don’t have to use my card to pay for these services? Just don’t want to pay since I’m only feeling out the options for now. Thanks for your suggestions in advance! -
Reverse for 'path' not found. 'function' is not a valid view function or pattern name?
I want to pass the argument to the function through the url. But I am getting error as Reverse for 'combodetails' not found. 'combodetails' is not a valid view function or pattern name. urls.py : path('combodetails/<int:id>/', combodetails, name="combodetails"), views.py : def combodetails(request, id): print(id) return render(request, "dashboard/combodetails.html", context={}) .html : <a href="{% url 'dashboard:combodetails' model.id %}" class="icuwfbegb"> I have used the same method in other functions and they are working fine. But here I don't know what's happening? -
Django Models making unique ,unique_together
I am a beginner and building Real-Time Chat with Django Web Sockets for my portfolio ,so I have model Thread that contains first_person and second_person , so it is like one to one room . from django.db import models from django.contrib.auth.models import User # Create your models here. from django.db.models import Q class ThreadManager(models.Manager): def by_user(self, **kwargs): user = kwargs.get('user') lookup = Q(first_person=user) | Q(second_person=user) qs = self.get_queryset().filter(lookup).distinct() return qs class Thread(models.Model): first_person = models.ForeignKey(User,on_delete = models.CASCADE,related_name='first_person') second_person = models.ForeignKey(User,on_delete = models.CASCADE,related_name='second_person') objects = ThreadManager() updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('first_person', 'second_person') My problem is that , i want to make this Thread model unique . I used unique_together, as you can see in Thread model ,but it only works for one way .For example , if i enter first_person : Alex and second_person : Sam ,it saves . But in vice versa , it also saves,if i change the places of people ,like : first_person :Sam and second_person : Alex . I also tried this code in my admin.py: class ThreadForm(forms.ModelForm): def clean(self): super(ThreadForm, self).clean() first_person = self.cleaned_data.get('first_person') second_person = self.cleaned_data.get('second_person') lookup1 = Q(first_person=first_person) & Q(second_person=second_person) lookup2 = Q(first_person=second_person) & Q(second_person=first_person) lookup = Q(lookup1 … -
Probably a very basic question: can I build and maintain the same website (in Django) from both Windows and macOS?
Disclaimer: First, I apologise if I'm incorrectly applying technical terms here or, worse, completely misunderstanding things. I'll edit if corrected. Context: Lately I've been building and deploying some basic website ideas to Heroku using the Django framework. I've been doing this on Windows, using venv as my virtual environment "wrapper". I've been building these exclusively from the command line interface. I also have a MacBook that I'd like to use to access and manage those websites, and in future, larger projects. I would prefer not to install Windows on this MacBook. To be clear, I know that it's possible to build and deploy a website using Django and Heroku on macOS. I know there are, at the very least, some syntactical differences in how I would approach this from the CLI versus Terminal. Desired outcome: I would like to set up a website in the fashion indicated above on Windows or macOS, and then access and manipulate it from the other OS. Questions: Is this possible? (Or if I set it up on Windows must I only use Windows to manage it?) If I set up a website in this fashion using Django, Heroku, and venv on Windows, how (if …