Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inner Join relationship filter in Django REST framework
I have models like these relationship I access these models via Django REST framework api class User(models.Model): name = models.CharField(max_length=128,unique=True) class Mix(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True) pub_date = models.DateTimeField('date published',default=timezone.now) class AccessToken(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name="%(app_label)s_%(class)s", ) token = models.CharField(max_length=128,unique=True) and here is the viewset class MixViewSet(viewsets.ModelViewSet): queryset = Mix.objects.all() serializer_class = MixSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filter_fields = ["id","user"] // how can I Set?? token class MixSerializer(serializers.ModelSerializer): class Meta: model = Mix fields = ('id','pub_date','user') then I want to get the mixes by token with this procedure Select from AccessToken table and find one user select * from Mix where user = user(selected at 1) I guess it is something like inner join??? How can I make it in django filter??? -
Does models.ForeignKey accept instances of itself as default value?
I have a model that has a many-to-one relationship with itself: class Foo(models.Model): b = models.CharField(max_length=10) parent = models.ForeignKey('self', on_delete=models.CASCADE) This Foo.parent default value should be the same instance. I mean if the user didn't specify parent field, it needs to refer to the object that is being created. How can i implement this? -
I am new in Django. can you help me with this error
this is my index.html file.i am getting error at line 11.is this syntax is right? this is my output TemplateSyntaxError at / Invalid block tag on line 11: 'static'https://fonts.googleapis.com/css?family=Roboto:50,150,200,250,350''. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.5 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 11: 'static'https://fonts.googleapis.com/css?family=Roboto:50,150,200,250,350''. Did you forget to register or load this tag? Exception Location: C:\python39\lib\site-packages\django\template\base.py, line 531, in invalid_block_tag Python Executable: C:\python39\python.exe Python Version: 3.9.1 Python Path: ['F:\Home', 'C:\python39\python39.zip', 'C:\python39\DLLs', 'C:\python39\lib', 'C:\python39', 'C:\python39\lib\site-packages'] Server time: Wed, 28 Jul 2021 10:18:22 +0000 -
Django - Data is not submitted to my database, but no error
i'm making a system that tracks the owners of different phone companies, by letting a user add the owners' names. i'd like for the user to be able to add several owners at one time, and, hoping to avoid a lot of RegEx, Ajax and Node, i made 5 'Owner' tables in my database (the epitome of spaghetti code, i know). The last 4 Owner tables have null=True and blank=True, so that they are optional. When displaying this in the UI, i put each form field representation of the Owners in its own div and hide the last 4 divs. the user can choose to 'add another owner' by clicking a button, up to 4 extra owners. Rarely all five divs are filled out, so some of them always remain hidden by basic javascript. I then proceed to save all of them using .save() like any other model. when the user has filled out all the desired fields and hit "submit", everything runs fine, however... the data never gets sent to the database. i get no errors anywhere, which leads me to guesstimate that the form i'm passing in when i save the data isn't valid. I know it's the … -
My django project doesn't want to be deployed on heroku
I want to push my django project on heroku, I did all the steps from the tutorial, and I got an error ModuleNotFoundError: there is no module called 'ckeditor' I tried to solve this problem by doing all the steps in this stackoverflow post - ModuleNotFoundError: No module named 'ckeditor_uploader' in django but that didn't work for me. This is mine settings.py - > https://codeshare.io/Jb786X This is my Traceback (venvecosite) (base) cristian@FInch:~/Desktop/GreatEcology my project/ecosite/ecowebsite$ git push heroku master Enumerating objects: 1716, done. Counting objects: 100% (1716/1716), done. Delta compression using up to 4 threads Compressing objects: 100% (1685/1685), done. Writing objects: 100% (1716/1716), 46.84 MiB | 6.84 MiB/s, done. Total 1716 (delta 174), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Python has released a security update! Please consider upgrading to python-3.8.11 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.8.5 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing dependencies with Pipenv 2020.11.15 remote: Installing dependencies from Pipfile.lock (180c80)... … -
Architecture of web application with multiple microservices
I am currently planning a web application with multiple microservices and trying to think of a possible architecture. This is the stack I would like to use: Backend: Django Frontend: React DB: whatever fits Docker (or something else if it fits better) Messaging framework, such as RabbitMQ Task queue, such as Celery I would like to integrate different services with different languages, such as simple Bash scripts, larger Flask apps, projects on GitHub written in Python, Javascript, Bash, C++, etc. Given the nature of these projects, some are just simple API requests, others may require compilation. So I was thinking about dockerizing each service and putting it on a different server. I would then call each service via a button and arguments, with some sort of API, something like this: server-IP.service(args) which would then trigger the service. Some of these services won't be used often, so this would be along the lines of "hibernate in your Docker container until I call you". Some services might return more than a simple json response, for example there might be a screenshot tool that takes multiple screenshots. How would I get these back and display them in my front end? I'm thinking of … -
Django rest framework serializer fields using single API call
I have a route that uses a ViewSet router.register( r'mapping_details', GlobalMappingDetailsViewSet, base_name='global-store-product-mappings' ) This view set contains a get_queryset method and a serializer. class GlobalMappingDetailsViewSet(viewsets.ModelViewSet): serializer_class = GlobalMappingDetailsSerializer def get_queryset(self): return models.Mappings.objects.all().select_related('my_column') class GlobalMappingDetailsSerializer(serializers.ModelSerializer): class Meta: model = models.Mappings fields = ('column1', 'column2') I want to add 2 fields that are populated using a single API call in the response of the request. I could use serializers.Field but will have to make separate calls for both the fields. Does someone know the right way to handle this use case? -
How can a field in the Django admin panel be made writable for a model only when it is being created, and it'll be read only at other times?
I am working on a project similar to a stock market. In this project I have a model called Share which is as follows: class Stock(models.Model): _title = models.CharField(max_length=50) _description = models.TextField() _total_subs = models.IntegerField() _sold_out_subs = models.IntegerField() _created_at = models.DateTimeField(auto_now_add=True) _updated_at = models.DateTimeField(auto_now=True) _status = models.BooleanField() Access to create new records for this model is to be supposed only through the Django admin panel, so in the admin.py file in my app I wrote a class to manage it called StockAdmin as follows: class StockAdmin(admin.ModelAdmin): list_display = [] readonly_fields = ['_sold_out_subs'] class Meta: model = Stock How can I make a _total_subs so that it can be writable when it being create and then it should be in read-only fields? -
Best way to update a Django-model-instance/database-table from another server without Django
Say I have two servers prod and API. On prod I have a Django application running and say I have the following model class MyModel(model.Models): name = models.Charfield() age = models.IntField() birthdate = models.DateTimeField() has_birthday = models.BooleanField() thus the model in my database would look like name | age | birthdate | has_birthday -----+-------+-------------+------------- john 30 1990-01-30 0 doe 20 1987-05-01 0 .... Each day on API I run a daily script which checks, if someone has birthday - if they do, set has_birthday=1 (note, everything above is just an example for illustration purposes). Since API just is a server for daily jobs, I have not deployed a Django-application on that server, thus I wonder, what is the usual/best way to update the MyModel table with the following logic? My first intuition is just to make a plain and simple update- SQL statement e.g from utils import get_con_to_db con = get_con_to_db() query = <SQL update query> con.execute(query) but that is rather error prone in case I decide to change my model in some way. Is there a better/more secure way of doing so, without having to create a Django application on API thus maintaining two Django applications? -
Django REST Framework: NOT NULL constraint failed
I know that there are answers regarding Django Rest Framework, but I couldn't find a solution to my problem. I have the following setup in Django REST Framework: models.py: class Variant(models.Model): variant = models.CharField(max_length=30) class Question(models.Model): question = models.CharField(max_length=250) multiple = models.BooleanField(default=False) variants = models.ForeignKey(Variant, db_index=True, on_delete=models.CASCADE) answer = models.CharField(max_length=30) class Quiz(models.Model): name = models.CharField(max_length=250) description = models.TextField() questions = models.ForeignKey(Question, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now=True, db_index=True) serializers.py: class VariantSerializer(serializers.ModelSerializer): class Meta: model = Variant fields = ['id', 'variant'] class QuestionSerializer(serializers.ModelSerializer): variants = VariantSerializer(many=True, read_only=True) class Meta: model = Question fields = ['id', 'question', 'multiple', 'variants', 'answer'] def create(self, validated_data): variants_data = validated_data.pop('variants') question = Question.objects.create(**validated_data) for variant in variants_data: Variant.objects.create(question=question, **variant) return question class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) class Meta: model = Quiz fields = ['id', 'name', 'description', 'date_created', 'questions'] def create(self, validated_data): questions_data = validated_data.pop('questions') quiz = Quiz.objects.create(**validated_data) for question in questions_data: Question.objects.create(quiz=quiz, **question) return quiz When I try to post some data assigned using a JSON file like this one: { "name": "quiz", "description": "quiz quiz quiz", "questions": [ { "question": "What is the weather today?", "multiple": false, "variants": [ { "variant": "cloudy" }, { "variant": "cold" } ], "answer": "cloudy" }, { "question": "What is the weather … -
Node as opposed to Django for running big python scripts
I am building an app that requires running a python script that implies a significant wait time. I am having a hard time deciding whether I should stick with Django or should dive into Nodejs, due to the fact that I find plugging in my front end (React) a pain point, and because I would like to work with Apollo Server. What is your opinion? Is Nodejs not suited for running such python scripts? Thank you! -
See django template in pytest failure output
During rendering a Django template my pytest based test fails. I would like to see two things: The name of the template, and a snippet of the part which caused this exception. Maybe I am blind, but I don't see it: tests/magic/test_render_search.py:8 (test_render_foo_search_results) @pytest.mark.django_db def test_render_foo_search_results(): portal = PortalFactory.create() foo = fooFactory.create(name='dummy') foo_index.sync_foo(foo.id) foo_index.commit() > html = render_foo_search_results('name=dummy', portal=portal) test_render_search.py:16: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../../magic/templatetags/render_search.py:17: in render_foo_search_results return get_foo_search_results_context( ../../magic/render_util.py:62: in get_foo_search_results_context html_data = cached_foo_render(search_results, ../../magic/render_util.py:41: in cached_foo_render rendered = render_to_string(template, { ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/loader.py:62: in render_to_string return template.render(context, request) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/backends/django.py:61: in render return self.template.render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/base.py:171: in render return self._render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/test/utils.py:96: in instrumented_test_render return self.nodelist.render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/base.py:937: in render bit = node.render_annotated(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/base.py:904: in render_annotated return self.render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/defaulttags.py:443: in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/urls/base.py:90: in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
How to display data from a model method
Good evening community I am new to programming and I have been working on a Django project to enhance my skills. I would like to display data from a method model in my templates. Here is the project's model, class Company(models.Model): #Company data company_name = models.CharField(max_length=100) outstanding_shares = models.IntegerField() share_price = models.DecimalField(max_digits= 5, decimal_places=2) revenue = models.IntegerField() expenses = models.IntegerField() total_assets = models.IntegerField() total_liabilities = models.IntegerField() current_assets = models.IntegerField() current_liabilities = models.IntegerField() operating_cashflows = models.IntegerField() capex = models.IntegerField() #Date of creation created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now= True) def __str__(self): return self.company_name #Company methods def net_income(self): return self.revenue - self.expenses Here is the Views file, def tools(request): submitted = False form = CompanyForm() if request.method == 'POST': print(request.POST) form = CompanyForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/simple_investing/tools?submitted=True') else: form = CompanyForm if 'submitted' in request.GET: submitted = True context = {'form': form, 'submitted': submitted} return render(request, 'simple_investing/tools.htm', context) Here is the forms file, class CompanyForm(ModelForm): class Meta: model = Company fields = ('company_name', 'outstanding_shares', 'share_price', 'revenue', 'expenses', 'total_assets','total_liabilities', 'current_assets','current_liabilities', 'operating_cashflows', 'capex') widgets = { 'company_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'Company name'}), 'outstanding_shares': forms.NumberInput(attrs={'class': 'form-control', 'placeholder' : 'Shares outstanding'}), 'share_price' :forms.NumberInput(attrs={'class': 'form-control', 'placeholder' : 'Share price'}), 'revenue' :forms.NumberInput(attrs={'class': 'form-control', 'placeholder' : 'Revenue'}), … -
django-allauth: reset password email, send the key instead of a link?
With django-allauth, to change password, user go to /password/reset/ and input a email address and confirm (user is redirected to /password/reset/done/ afterwards). Then the user receive an email. User get a link (password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/) with a key from the email, and through that link, user can change password. However, I'd like to reduce the pages user have to open. Here're what I want: instead the reset link, send to user the key only overwrite password_reset_done.html to add a key input form (method="GET") user enter the key and confirm, and get redirected to password/reset/?key=xxx 2 is easy to implement, but I don't know how to implement 1 and 3. Here is the password reset email django-allauth send by default. There's only a password_reset_url. How to replace it with the generated key? And how could I overwrite the url from password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/ to password/reset/?key=(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)? -
django-background-task - A specific kind of task are not running whereas other tasks still run
I have been using django-background-task for a while but the last background-task function I just added is not working. I created a new backgroud_task as below in a marketplace/tasks.py from background_task import background @background(schedule=1) def background_pair_new_account(lv_external_id: str, lv_siren: str, lv_vat_number: str, lv_pack: str) -> None: print(lv_external_id, lv_siren, lv_vat_number, lv_pack) The background task is called as below: from marketplace.tasks import background_pair_new_account background_pair_new_account("12345678", "789234678", "FR01789234678", "full") The background task is well created in backend: TASK NAME TASK PARAMS RUN AT marketplace.tasks.background_pair_new_account [["12345678", "789234678", "FR01789234678", "full"],{}] 28 juillet 2021 09:59 But when I run python manage.py process_tasks, my task doesn't run. However the other tasks still works. What are the reasons why a task would not run even if the execution date is passed, the task is not locked and no error is mentionned ? -
Dictionary web app in Django - how to switch languages so that word in search bar don't delete
I am working on Dictionary web application - similar to Google translate. I have this problem: there are only have two languages, eng and cro and search bar in which user types word that requires translation. When user starts typing, for example some english word, and sees that dictionary is set to CRO-ENG, user needs to switch dictionary to ENG-CRO. But then, word which user started to type when dictionary was set to CRO-ENG deletes. I know it is because ENG-CRO and CRO-ENG are two separately pages but I need that text which is typed in search bar stays there despite switching between languages. There is a part of code (search bar) from eng-cro.html page: {{form.errors}} <form method="GET" action="" autocomplete="off" {% if srch %} value="{{ srch }}" {% endif %}> <div class="search"> <input type="text" name="srch" placeholder="search" id="search" autocomplete="off" list="ddlautocomplete_eng" /> <datalist id="ddlautocomplete_eng"> {% for result in dicty%} <option>{{result.engWord}}</option> {% endfor%} </datalist> </div> </form> There is a part of views.py (after searching, user gets a list of words which starts with the word he search): def eng_to_cro(request): words = Dictionary.objects.order_by('engWord') srch = request.GET.get('srch') if srch: words = words.filter(engWord__istartswith=srch) else: words = None args = {'words': words, 'srch': srch} return render(request, 'app/eng-cro.html', … -
Celery configuration in settings.py file
Can anyone explain about these lines in celery RabbitMQ in Django. Which time it will be use ? I ran 2 tasks(addition operation and endpoint in django) in celery RabbitMq without these lines successfully. So Please explain when it will be used in settings.py and celery rabbitmq CELERY_BROKER_URL = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' Thanks in advance -
Using Django's Case/When queryset conditions to set more than one value?
I have two values that depend on the same case when condition in my sql call. Currently I duplicate the condition to set each value separately, but can I combine the two identical cases to set both values at once? -
How to use the DateTimeFilter in django-filter, passing it a custom 'method' parameter?
I am trying to call an endpoint configured as such: https://www.nottherealurl.com/foods?transaction_datetime=2020-01-01,2020-01-30 I am trying to filter the foods that were sold during a given time between a start date and an end date. In this case, between 2020-01-01 and 2020-01-30. I have a model called Food and it has a field called transaction_datetime. class Food(CustomMixin): ... other fields ... food_type = models.CharField( max_length=25, null=True, blank=True, choices=FOOD_TYPE_CHOICES, ) transaction_datetime = models.DateTimeField( null=False, editable=False, ) ... other fields ... I have a view setup as such: class FoodView(ListAPIView): serializer_class = FoodSerializer filter_backends = ( filters.OrderingFilter, filters.SearchFilter, filters.DjangoFilterBackend ) filter_class = FoodFilter ordering_fields = ( 'name', 'amount', 'transaction_datetime', '=food_uuid', ) ordering = ('-transaction_datetime',) search_fields = ordering_fields def get_queryset(self): return ( Food.objects.prefetch_related('ingredients').filter(deleted_at__isnull=True) The FoodFilter is configured as such. class FoodFilter(django_filters.FilterSet): food_type = django_filters.CharFilter(method='filter_by_food_type') transaction_datetime = django_filters.DateTimeFilter(method='filter_by_transaction_datetime') def filter_by_food_type(self, queryset, name, value): print("RAN") # printed when I call the appropriate endpoint as stated below value_list = [x.strip() for x in value.split(',')] return queryset.filter( food_type__in=value_list ) def filter_by_transaction_datetime(self, queryset, name, value): print("HELLLOOOO") # this does not show up at all when attempt to call endpoint to filter by transaction_datetime value_list = [x.strip() for x in value.split(',')] start_date = value_list[0] end_date = value_list[1] return queryset.filter(transaction_datetime__range=[start_date, end_date]) class … -
Is there any alternate way that is much quicker than append in python?
I have thousands of data that need to listed using django api in json format. when I try to append the data's to a list it takes more time. is there any alternate way and quickest way to get around this ? -
I want to pass variable from base template ( basic.html which have navigation and footer) to child template(index.html)
I was trying to pass my unicategory variable which I want to show in my navigation of all the templates which I extend (basic.html which contains footer and header) and index.html which is my home page. so the idea is this I have passed the variable in unicategory function and render it in basic.html to show all unique categories in my navigation bar of. i have extended basic.html in index.html and when i use loop to show the unicategory variable its does not working basic.html <nav>`{% for i in unicategory%} <li><a href="{% url 'Stores:categories' i.scategory %}">{{i.scategory}}<span> ( {{i.posts_count}} ) </span></a></li> {%endfor%}` </nav> basic views def basic(request): stores = stores_model.objects.all() unicategory = stores_model.objects.values('scategory').distinct().order_by().annotate(posts_count=Count('scategory')) context = {'stores':stores , 'unicategory':unicategory } return render(request,'Home/basic.html',context) i want to extend this template in index.html as header and i want to show this category on index page also. index.html {% extends 'Home/basic.html'%} {% block body %}------some front page code-----{% endblock %} index.views stores = stores_model.objects.all() context = {'stores':stores } return render(request,'Home/index.html',context) -
python code to zip and download a folder with images
I would like to download images that are uploaded in Django. Currently, I am zipping the folder and storing it in one of the Django folders first and then downloading it. After that, I delete the zipped folder which is in my Django app. Is it possible to zip a folder and directly download it without saving it in my Django folder. zip_path = os.path.join(settings.MEDIA_ROOT, str(project), str(project) + "_images.zip") def make_archive(source, destination): base = os.path.basename(destination) name = base.split('.')[0] format = base.split('.')[1] archive_from = os.path.dirname(source) archive_to = os.path.basename(source.strip(os.sep)) # print(source, destination, archive_from, archive_to) shutil.make_archive(name, format, archive_from, archive_to) shutil.move('%s.%s' % (name, format), destination) make_archive(src_path, zip_path) file_path = zip_path if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/force-download") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) os.remove(file_path) if "selected" in request.POST: shutil.rmtree(src_path) -
Django ajaxmixin image upload
I am absolutely new to Django. The following codes are from a Git project. Here is a great example of Ajax Creatview. I can work with it very well. How do I add self.request.FILES here, for uploading / saving images. I also addedenctype = "multipart / form-data" in the form. I added self.request.FILES to AjaxValidForm class but it didn't work. Any help will be appreciated. Thanks in advance. class SubscriberCreate(LoginRequiredMixin, AjaxCreateView): model = Subscriber form_class = SubscriberForm ajax_modal = 'billing/subscriber_form.html' ajax_list = 'billing/subscriber/subscriber_list.html' class AjaxContextData: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) filter = self.kwargs [filter.pop(key, None) for key in ['pk', 'id', 'uuid', 'slug']] # context['object_list'] = self.get_queryset().filter(**filter) context['%s_list' % self.model.__name__.lower( )] = self.get_queryset().filter(is_deleted=False).filter(**filter).order_by('-id') return context class AjaxValidForm: def form_valid(self, form): data = dict() context = self.get_context_data() if form.is_valid(): form.save() data['form_is_valid'] = True data['form_id'] = form.instance._meta.model_name data['html_list'] = render_to_string( self.ajax_list, context, self.request) data['message'] = 'Successful saved.' else: data['form_is_valid'] = False data['message'] = 'Form validation error!' data['html_form'] = render_to_string( self.ajax_modal, context, request=self.request) if self.request.is_ajax(): return JsonResponse(data) else: return super().form_valid(form) class AjaxCreateView(AjaxContextData, AjaxValidForm, CreateView): def get(self, request, *args, **kwargs): self.initial = self.kwargs self.object = None context = self.get_context_data() if request.is_ajax(): html_form = render_to_string(self.ajax_modal, context, request) return JsonResponse({'html_form': html_form}) else: return super().get(request, *args, **kwargs) -
Django Query "not in" M2M
I got these three models: class Crcheck(models.Model): crlist = models.ForeignKey("crlists.Crlist", on_delete=models.CASCADE) persons = models.ForeignKey("persons.Person", on_delete=models.CASCADE) ... | id | crlist_id | persons_id | | 41 | 2 | 64 | | 42 | 3 | 64 | class Cuslistprofile(models.Model): customer= models.ForeignKey("customers.Customer",on_delete=models.CASCADE) crlist = models.ManyToManyField("crlists.Crlist") ... class Crlist(models.Model): dbname=models.CharField(max_length=200) ... as a result of the M2M Django generates this table "cuslistprofiles_cuslistprofile_crlist" | id | cuslistprofile_id | crlist_id | | 9 | 4 | 2 | | 13 | 4 | 3 | | 14 | 4 | 5 | | 19 | 4 | 7 | what I want to achieve is to get all the crlist values that are in "cuslistprofiles_cuslistprofile_crlist" but missing in "crcheck". In this particular example I want to retrieve 5 and 7. How can I achieve that in Django ORM? Thanks in advanced -
Pip cannot install anything on ubuntu server
I had deleted an existing virtual environment. I created a new one and activated it. Now I am trying to install site packages using pip install -r requirements.txt But I keep getting the error Cannot fetch index base URL https://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement BeautifulSoup==3.2.1 (from -r requirements.txt (line 1)) Now I know that the packages are really old but this is running on python 2.7.6. I am also not able to install anything through pip. I have tried pip install numpy But it shows the same errors. As per the similar questions answered before the suggestion is to use https://pypi.python.org which I have already done but still facing these errors. Would love to hear your suggestions.