Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pylint "unresolved import" error in visual studio code
I am using the following setup MacOS Mojave Python 3.7.1 Visual Studio Code 1.30 Pylint 2.2.2 Django 2.1.4 I want to us linting to make my life a bit easier in visual studio code however, every import i have states "unresolved import". Even on default django imports (i.e. from django.db import models). I presume it is because it is not seeing the virtual environment python files. Everything works just fine but but it's starting to get annoying. The interpreter choices i have are all system versions of python. It does not seem to see my virtual environment python at all (it is not in the same directory as my workspace, so that part makes sense). If i setup the python.PythonPath in the settings.json file, it just ignores it and does not list my virtual environment path as an option. I also tried setting it up in my global python settings but it also does not show up. Has anyone run into this issue and know a quick fix to get it working? Thanks, jAC -
Concatenate string and UUID in Django Template
I am trying to concatenate the UUID of a record with a base URL to create a scannable QR code that will link to the direct record on the website. When trying to concatenate the two it fails and yields nothing. The relevant part is device.id which is a UUID for the device. I've string |stringformat:"s" as well and that didn't work. I don't know what the best practice to do this is and am struggling. <div class="row"> <div class="col-xs-12 text-center"> {% with "http://127.0.0.1:8000/ims/device/"|add:device.id as deviceurl %} {% qr_from_text deviceurl size=25 %} <p class="small text-center">{{deviceurl}}</p> {% endwith %} <p class="small text-center">{{ device.id }}</p> </div> </div> -
Django admin search icon become SO BIG after install django cms on top of django
I have install django and create django project. everything was working fine untill i install django-cms than my django project and django cms project is getting weird for exam the search icons become so big. I think it is conflict between django cms and django css style or something. Can anyone recommend me any solution to this? thank you -
Infinite scroll with django not loading next pages upon scrolling down
Intro: I am using this https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html to add infinite scroll with django. Just in case anyone wants the detailed code its on Github.It is a very simple code https://github.com/sibtc/simple-infinite-scroll The issue: I have a total of 8 posts. I can see 3 posts in my homepage. Ideally as soon as I scroll down more 3 posts should show. I know the views are fine as the print statement in the view works and it is showing only 3 posts. Usually if there is a problem loading infinite scroll the More link should show. But that is not showing as well. Where am I going wrong What I have done so far: In my static folder. I made a folder called js and added 3 files in it infinite.min.js, jquery-3.1.1.min.js, jquery.waypoints.min.js I copied the code exactly from the github in my files Below is my view: class Homepage(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(Homepage, self).get_context_data(**kwargs) all_posts = Post.objects.all() page = self.request.GET.get('page', 1) paginator = Paginator(all_posts, 3) try: posts = paginator.page(page) print(posts) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context['post_list'] = posts return context Below is my base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta … -
How to create auto generated membership id in django
I want to create an auto-generated membership id of a user in the profile table based on the current date and username. User table has OneToOneField relationship with the profile table. So when I create a user, I have to put username in the registration form. The signals.py creates a profile row in the table for the user. I want when the profile is created it would have a membership id which is the mix of current date and username. My code is as follow: singlas.py from django.db.models.signals import post_save, pre_save from .models import Ext_User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=Ext_User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) models.py class Profile(models.Model): user = models.OneToOneField(Ext_User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics', null=True, blank=False) membership_id = models.CharField(max_length=50, default='', null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' I have got some guideline to user pre_save into signals.py but don't understand how to figure out. -
How to overwrite the urlconf without specifying a "path.to.urls"?
Both django-hosts and this solution (Django: Overwrite ROOT_URLCONF with request.urlconf in middleware), advises to use Middleware to override the URLConf by specifying the path for the urlconf. However, that would require a file with the variable "urlpatterns". Instead, what I'm trying to do is that, loading the urlpatterns based on the subdomain/project. So I'm looking for someway to do it without generating a file everytime someone update the pages' URL and writing it to a file "urls_subdomain.py". Here's the reference to the request middleware by django: https://docs.djangoproject.com/en/2.1/topics/http/urls/#how-django-processes-a-request -
Custom discrete slider in Python/Django or D3
I'm working on a custom survey app for a small company intranet and would like to design custom sliders. I need to have discrete sliders that can indicate values from 1-5 but would allow you to select your level based on hover over and click actions. I've found discrete sliders for Python via matplotlib as well as D3, but nothing like this. I'd like it to look something like this: Is this kind of front end implementation better left to working in d3, or is a better course of action is to write a wrapper for the existing slider class in Python? Open to any and all suggestions, but I'm sticking with Django as the framework for the app. -
Celery executes a task after calling task.delay() for 3-5 times
I am using celery in django project. I have tried using rabbitmq and redis backend but neither does work. Used celery version is 3.1.26.post2. I have to call 2, 3 sometimes 5 times task.delay() to see the task running. -
Django send_mail() with FormView
I'm looking for a way to render all of my submitted form data in message using the send_mail() function. I'm thinking there has to be a way that I can render the entire submitted form data sort of like { 'form': form} instead of calling all of the different models. Any help showing me how to refactor this is greatly appreciated. class PMPIndex(ListView, FormView, SuccessMessageMixin): template_name = 'pmp/index.html' model = Post form_class = CustomProjectBuildRequestForm success_url = reverse_lazy('home') success_message = "Form successfully submitted!" def form_valid(self, form): form.save() context = { 'first_name': form.cleaned_data.get('first_name'), 'last_name': form.cleaned_data.get('last_name'), 'email': form.cleaned_data.get('email'), 'phone': form.cleaned_data.get('phone_number'), 'zip_code': form.cleaned_data.get('zip_code'), 'project_title': form.cleaned_data.get('project_name'), 'project_description': form.cleaned_data.get('project_description'), 'contact_method': form.cleaned_data.get('preferred_contact_method'), } template = get_template('custom_project_request_email_template.html') content = template.render(context) send_mail( 'New Custom Project Request', html_message=content, message=content, from_email=context['email'], recipient_list=['kyle@postmyproject.com'], fail_silently=False, ) return super(PMPIndex, self).form_valid(form) -
Django - load context data leaflet
I've been working in a geodjango app to include a map for a search function in a spatial table, learning from tutorials, so far I know of a method to load serialized data in leaflet by creating a function based view assigning an url and importing that url as a GeoJSON.AJAX variable, I've been trying to change that method to then try to figure out a way to pass the data in my search function: Views file: def map_dide(request): return render(request, 'b_dide_uv/map_did.html') def info_uvs(request): uv = serialize('geojson', D_uvs.objects.all()) return HttpResponse(uv, content_type='json') Template: function uvs(map,options){ var dataset = new L.GeoJSON.AJAX("{% url 'info_uvs' %}",{ }); dataset.addTo(map); } I've been trying to insert the serializing and passing it as context in the map_dide function: def map_dide(request): uv_ini = serialize('geojson', D_uvs.objects.all()) return render(request, 'b_dideco_uv/mapa_did.html', {'uv':uv}) but when I assign it in the javascript in the template it gives me an error, so far I tried: var uv_data = JSON.parse('{{uv|safe}}') function uvs(map,options){ var dataset = new L.GeoJSON.AJAX(uv_data,{ }); dataset.addTo(map); } but I got an "SyntaxError: missing ) after argument list" in the console I also tried the L.geoJson, and the L.GeoJSON function but it the same result what others methods to insert serialized data in … -
'ManagementForm data is missing or has been tampered with' Issue
I am stuck with this error and I don't know what to do... I followed the Django documentation here I would like also to create a new Player object when I fill the empty extra form. Hope someone is familiar with ManagementForm My files: views.py from django.shortcuts import render, redirect from skeleton.models import Player from django.contrib.auth.decorators import login_required from .forms import PlayerForm from django.forms import modelformset_factory # Create your views here. @login_required(login_url="/accounts/login/") def team_area(request): PlayerFormSet = modelformset_factory(Player, fields=('first_name', 'last_name'), extra=1) if request.method == "POST": player_formset = PlayerFormSet( request.POST, request.FILES, queryset=Player.objects.all().filter(team=request.user.team),) if player_formset.is_valid(): player_formset.save() return redirect('team_area:home') else: player_formset = PlayerFormSet(queryset=Player.objects.all().filter(team=request.user.team)) return render(request, 'team_area/team_area.html', {'player_formset': player_formset}) team_area.html {% extends 'base_layout.html' %} {% block content %} <h1>Area Squadra</h1> <form method="post" action=""> {% csrf_token %} {{ formset.management_form }} {% for player_form in player_formset %} {% for field in player_form %} {{ field.label_tag }} {{ field }} {% endfor %} <br> {% endfor %} <input type="submit" value="Aggiorna"> </form> {% endblock %} -
Django: Province Choice Field dependant on State ChoiceField
I've a registration form that ask users to choose their department (like USA States), province, and district. In spanish: "departamento", "provincia", "distrito". I can populate these from our Peru table, that contains this information in three different columns. But I need to limit user's options so they choose a valid combination. However, in the final form Users can choose invalid convinations of "departamento", "province" and "distrito". For example, taking USA cases, a user could select: -departamento: "California". -provincia: "Dallas". -district: "Carrolton". models.py ### User Profile ### class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # birth_date = models.DateField(null=True, blank=True) dni = models.CharField(max_length=30, blank=True) # phone_number = models.CharField(max_length=15, blank=True) shipping_address1 = models.CharField(max_length=100, blank=False) shipping_address2 = models.CharField(max_length=100, blank=False) shipping_department = models.CharField(max_length=100, blank=False) shipping_province = models.CharField(max_length=100, blank=False) shipping_district = models.CharField(max_length=100, blank=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class Peru(models.Model): departamento = models.CharField(max_length=100, blank=False) provincia = models.CharField(max_length=100, blank=False) distrito = models.CharField(max_length=100, blank=False) def __str__(self): return self.departamento + " - " + self.provincia + " - " + self.distrito forms.py class ProfileForm(ModelForm): def __init__(self, district_list, province_list, department_list, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['shipping_district'] = forms.ChoiceField(choices=tuple([(name, name) for name in district_list])) self.fields['shipping_province'] = forms.ChoiceField(choices=tuple([(name, name) for name in province_list])) self.fields['shipping_department'] = forms.ChoiceField(choices=tuple([(name, name) … -
Error while deploying my django app on Heroku
When I run the command : heroku run python manage.py migrate I get the following error : /app/.heroku/python/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.""") Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 60, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) .... File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/foodtasker/urls.py", line 15, in <module> url(r'^restaurant/sign-in/$', auth_views.loginView.as_view(template_name='restaurant/sign_in.html'),name="restaurant-sign-in"), AttributeError: module 'django.contrib.auth.views' has no attribute 'loginView' I can't figure out the source of this error and I wish to solve it so I can deploy my app on Heroku. -
How to fix ERR_SSL_PROTOCOL_ERROR
We are trying to implement SSL certification that we go from goDaddy to our website. We are using gunicorn and Django for the server. This is what we currently have implemented and we are thinking we need ciphers or TLS and have tried getting it to work but that also failed. gunicorn TerraSolutions.wsgi:application \ --name TerraSolutions \ --bind 0.0.0.0:443 \ --certfile=certificate.crt \ --keyfile=private_key.crt \ --workers 5 \ --log-level=info \ --log-file=/code/logs/gunicorn.log \ --access-logfile=/code/logs/gunicorn-access.log This is gunicorn config. We are using certificate.crt and private_key.crt we got from goDaddy -
Unable to find newly saved instances in database
I'm making a stock portfolio app as a personal project. I have a form StockSymbolForm used for buying stocks. It has the fields: username, stock_symbol, and stock_qty. I've set username to be the current user that's currently using the app - so they only need to fill stock_symbol and stock_qty. After a valid form is submitted, I go to my admin page to check, but I don't see my new stock_symbol and stock_qty added to my model. Here's my code: views.py: class PortfolioStockListView(ListView): model = StockPortfolio template_name = 'stocks.html' def post(self, request): current_user = StockPortfolioUser.objects.filter(username=request.user).first() if request.method == 'POST': symbol_form = StockSymbolForm(request.POST, initial={'username': current_user}) if symbol_form.is_valid(): symbol_form = StockSymbolForm(request.POST, instance=current_user) model_instance = symbol_form.save(commit=True) model_instance.timestamp = timezone.now() model_instance.save() return redirect('/') else: return render(request, 'stocks.html', {'symbol_form': symbol_form}) else: symbol_form = StockSymbolForm() return render(request, 'stocks.html', {'symbol_form': symbol_form}) models.py: class StockPortfolioUser(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) usercash = models.PositiveIntegerField(default=100000) class StockPortfolio(models.Model): username = models.ForeignKey(StockPortfolioUser, on_delete=models.CASCADE) stock_symbol = models.CharField(max_length=5) stock_qty = models.PositiveIntegerField(default=0) forms.py: class StockSymbolForm(ModelForm): class Meta: model = StockPortfolio fields = ('stock_symbol' , 'stock_qty') labels = {'stock_symbol': 'Stock Symbol', 'stock_qty': 'Quantity'} How do I save the model instance properly? and why is it not saving at the moment? -
Django looping through JSONField to create form, won't post
I'm looping through a JSON field in my model 'Attrs_Dynamic' which are used to create the form on my template: <form action="." method="POST" id="form" > {% csrf_token %} <div class="form-group"> {% for key,value in exception.Attrs_Dynamic.items %} {% if 'Date' in key %} <label for="{{key}}_input">{{key}}:</label> <input type="date" value="{{value}}" name="{{key}}_input" id="{{key}}_input" /> <br /> <br /> {% elif 'Comments' in key %} <label for="{{key}}_input">{{key}}:</label> <input type="text" value="{{value}}" name="{{key}}_input" id="{{key}}_input" /> <br /> <br /> {% else %} <label for="{{key}}_input">{{key}}:</label> <input type="text" value="{{value}}" name="{{key}}_input" id="{{key}}_input" /> <br /> <br /> {% endif %} {% endfor %} </div> <input type="submit" value="Submit"> </form> My view where this is applicable looks like: if request.method == 'POST': for key, value in request.POST.items(): print(key, value) I can't get it to properly print the data, it only prints the CSRF token. Where am i going wrong? -
Ignore one field in a django model
I have a django model that has the following four fields: class File: id = models.PrimaryKey() name = models.CharField() is_active = models.BooleanField() data = models.JSONField() The data field is massive, perhaps 5MB per entry. Is there a way I can hide that field when I do an ORM query without having to specify all the fields I want to view each time? Something like: File.objects.all() # exclude data field File.objects.values('id', 'data') # include the data field -
django.db.utils.OperationalError: FATAL: database "dbname" does not exist
I'm trying to deploy my Django app on docker ,but when i run the container it shows: psycopg2.OperationalError: FATAL: database "NUTEK" does not exist my docker-compose.yml file: version: '2.1' services: web: restart: always build: ./web expose: - "8000" links: - postgres:postgres - redis:redis volumes: - /usr/src/app - /usr/src/app/static nginx: restart: always build: ./nginx/ ports: - "80:80" volumes: - /www/static links: - web:web postgres: restart: always image: postgres:10.6 ports: - "5432:5432" redis: restart: always image: redis:latest ports: - "6379:6379" my Dockerfile: FROM python:3.6.6-onbuild CMD ["python", "manage.py","run server"] the settings.py file of my Django app: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'NUTEK', 'USER': 'postgres', 'PASSWORD': 'root', 'HOST': 'postgres', 'PORT': '5432', } } my .env file: SECRET_KEY='secret' DB_NAME=NUTEK DB_USER=postgres DB_PASS=root DB_SERVICE=postgres DB_PORT=5432 i've searched on issues on the github repository of docker-libraries/postgres and stackoverflow and i found that i should create the database : docker run -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=root -e POSTGRES_DB=NUTEK postgres but that didn't help also ,hope someone can help . -
How to see application logs in Django Rest Framework?
In tests I am making an api call, which returns 400. It is expected, but I can't find a way to debug this. Does django keep logs in a file somewhere? Or can I enable showing logs please? res = self.client.post(self.url, data=payload, format='json') print(res) // <Response status_code=400, "application/json"> I knot something went wrong but how do I debug the server? Thanks -
AttributeError: 'function' object has no attribute '_meta'
I'm receiving that error from the title when I add the line from .forms import Opret_kunde_form into my views.py and it's driving me insane. I have no idea how to fix this. Full traceback > Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001E23A239400> Traceback (most recent call last): File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 396, in check for pattern in self.url_patterns: File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\kr85m\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in … -
How i can fix my vitualenv problem with python
I was trying to create my first django project i installed the virtualenv and after that i wrote this code : ~$ virtualenv --python-python3 firstdjango and my terminal said ''Usage: virtualenv [OPTIONS] DEST_DIR virtualenv: error: no such option: --python-python3' what should i do? -
how do i start everything over with django?
i'v bin working with django recently as a beginner and i was struggling with how to learn django and i fucked everything up so i decided i should start over i tried to uninstall django and install it again but nothing worked i tried to make a new directory on my windows and still nothing worked is there anyway to reset my installation and restart my whole software? here's how i started learning: i went to youtube and followed a free course and followed along with it i then downloaded a book from a website and tried to follow along with it with my old project then i finally took the decision to delete everything i don't know how to restart all my work tried to uninstall django and work with a new project but it keeps giving me errors . tried to delete all the files from my last project didn't work tried to move my old files to new directory didn't work tried to delete all code contained in the old project's files get screwed what do i do guys? i'm clearly crying in the bathroom with my laptop with me please help -
Using Annotate & Artithmetic in a Django Subqeury
I am trying to improve my understanding of the Django queryset syntax and am hoping that someone could help me check my understanding. Could this: total_packed = ( PackingRecord.objects.filter( product=OuterRef('pk'), fifolink__sold_out=False ).values('product') # Group by product .annotate(total=Sum('qty')) # Sum qty for 'each' product .values('total') ) total_sold = ( FifoLink.objects.filter( packing_record__product=OuterRef('pk'), sold_out=False ).values('packing_record__product') .annotate(total=Sum('sale__qty')) .values('total') ) output = obj_set.annotate( sold=Subquery(total_sold[:1]), packed=Subquery(total_packed[:1]), ).annotate( in_stock=F('packed') - F('sold') ) be safely reduced to this: in_stock = ( FifoLink.objects.filter( packing_record__product=OuterRef('pk'), sold_out=False ).values('packing_record__product') .annotate(total=Sum(F('sale__qty')-F('packing_record__qty)) .values('total') ) output = obj_set.annotate( in_stock=Subquery(total_sold[:1]), ) Basically, I am trying to move the math being completed in the outer .annotate() into the queryset itself by using the fk relationship instead of running two separate querysets. I think this is allowed, but I am not sure if I am understanding it correctly. -
Returning many objects on html page - Django 2.0
I am returning the "comentarios" objects of the database through a for, but since the display of these objects takes up a lot of space in the html page, I would like to know how to divide the objects into more lists or into a hidden space, since when they pass from seven comments they exceed the size of the body. template.html {% extends 'baseR.html' %} {% load static %} {% block title %} Comentários - SMILE 3D {% endblock %} {% block tamanho %} 2000px {% endblock %} {% load bootstrap %} {% block main %} <div class="row b2"> <div class="col-1"></div> <div class="col-10"> <h3 style="color:royalblue; font-weight:bold;">Pregão: </h3> <hr> <h2>{{msg}}</h2> <br> <ul style="list-sytle:none;"> <div class="container pregoes"> <li style="list-style:none;"> <p><strong>Dono: </strong><a href="{% url 'perfil-geral' pregoe.usuario.id %}" class="cNome">{{pregoe.usuario}}</a></p> <p><strong>Tipo do pregão: </strong>{{ pregoe.tipo }}</p> <p><strong>Dente: </strong>{{ pregoe.dente }}</p> <p><strong>Cor: </strong>{{ pregoe.cor }}</p> <p><strong>Escala: </strong>{{ pregoe.escala }}</p> <p><strong>Material: </strong>{{ pregoe.material }}</p> <p><strong>Observações: </strong>{{ pregoe.extra }}</p> <p><strong>Preço inicial: </strong>R${{ pregoe.preco }}</p> <p><strong>Data de registro: </strong><em>{{ pregoe.data }}</em></p> <p><strong>Prazo: </strong><em>{{ pregoe.prazo }}</em></p> </li> </div> <br> <hr> **<h3>Comentários: </h3> {% for comentario in comentarios %} <div class="container" style="background-color:gainsboro; padding-bottom:2px; padding-top:10px;"> <a href="{% url 'delete-comentario' comentario.id %}"><i class="far fa-times-circle" style="float: right;"></i></a> <a href="{% url 'perfil-geral' comentario.user.id %}" … -
Join unrelated models and delete duplicate from the queryset
I really need help here. I have the two tables below. As you can see they are completely independent (No relationship between the two). class People(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=35) phone_number = models.CharField(null=True, blank=True, max_length=15) created = models.DateTimeField(auto_now=False, auto_now_add=True) class Blacklist(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=35) phone_number = models.CharField(blank=True, max_length=15) How do I proceed to accomplish below : * I have a list of phone numbers from "Blacklist" table. I want to be able to check if "phone_number(s)" field from table "People" is identical to any "phone_number" in "Blacklist". If it is identical, DELETE duplicate "phone_number" from "People" table. I have spent a few days and have not found the correct way to do it. I am using PostgreSQL database. Any help would be much appreciated.