Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a django custom user model when database and user data already exists (migrating app from PHP-Symfony)?
I am migrating a legacy application from PHP-Symfony to Python-Django, and am looking for advice on the best way to handle Users. User information (and all app related data) already exist in the database to be used, so currently upon django models are built and the initial migration is run as python manage.py makemigrations app followed by python manage.py migrate --fake-initial. I need to create a custom User model, or extend the default django user, to handle custom authentication needs. Authentication is handled through Auth0 and I have created the (functioning) authentication backend following their documentation. The goal is for all current users to be able to log in to the web app once conversion is complete, though a mandatory password reset is probably required. I would like all other current user info to still be available. The issue currently is the User information from the existing database is not connected to the default Django User model. I have attempted to extend the default django user model by passing the default User model as a one-to-one relationship in the legacy app User model, but am getting 'duplicate entry __ for key user_id' errors when attempting to apply the migration modifying … -
convert mysql queries to django models
i stuck on the sql requetes that carry the foreign keys, because i want to convert the following request: select date_cours , pseudo from users inner join course on users.idusers = course.users_idusers with the select_related method but I do not understand how it works even by reading the documentation. -
How could i create a web application in django that copies the content from certain blogs and automatically puts them in my blog
I have created a web application "blog" in django and I would like to do content parsing on certain thematic blogs and automatically publish them on my blog, but I have no idea how and what I should do. -
rejected push caused by pkg-ressources==0.0.0
i'm trying to deploy django app on heroku app and when i'm pushing i get always error like: Collecting pkg-resources==0.0.0 (from -r /tmp/build_f2ffd131f3795550686efbc08630b8bd/requirements.txt (line 9)) remote: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_f2ffd131f3795550686efbc08630b8bd/requirements.txt (line 9)) (from versions: ) remote: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_f2ffd131f3795550686efbc08630b8bd/requirements.txt (line 9)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected and i'm sure on my requirements.txt i don'have this package #requirements.txt certifi==2019.6.16 chardet==3.0.4 defusedxml==0.6.0 dj-database-url==0.5.0 Django==2.2.3 django-debug-toolbar==2.0 gunicorn==19.9.0 idna==2.8 oauthlib==3.0.2 Pillow==6.1.0 psycopg2==2.8.3 PyJWT==1.7.1 python3-openid==3.1.0 pytz==2019.1 requests==2.22.0 requests-oauthlib==1.2.0 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.2.0 urllib3==1.25.3 whitenoise==4.1.3 -
Import custom modules from in script launched from Django
I am trying to process an uploaded file to Django server. When I receive it I launch a python script that processes the file (I need to do it this way instead of with classes, so please do not tell me to do it from a class). My Django structure is the following: Project web_server: settings ... url.py ... S2T: this is my app where I have my views views.py apps.py ... src: here I have my custom modules, I will focus on 2: pipeline master.py classes misc.py From the views I launch a python script: sb_info = subprocess.run(['python', 'src/pipeline/master.py', '/tmp'], stdout=subprocess.PIPE, universal_newlines=True) This works nicely, but when the script is launched I get the following error: File "src/pipeline/master.py", line 10, in from src.classes.misc import path_to_dest ModuleNotFoundError: No module named 'src' The problem is that that file does exits. I have checked using os.listdir() and the master.py does see the src module, this is the output that I get: [temp.txt, db.sqlite3, pycache, S2T, .idea, manage.py, src, wdir.txt, .git, web_server] I have tried a lot of things that I have seen in stackoverflow, for example: declaring the package in INSTALLED_APPS using import .src moving src inside S2T I want to state … -
django rest framework IntegrityError
I have three models: contain, container and integration. Container and Containe inherit from the Product model. There are manyToMany relationship with integration. class Contain(Product): typeCard = models.ForeignKey(TypeCard, related_name="typeOfCad", on_delete=models.CASCADE) state = models.ForeignKey(StateCard, related_name="stateCard", on_delete=models.CASCADE) def __str__(self): return self.serialNumber class Container(Product): coffret = models.ForeignKey(Product, related_name="coffrets", on_delete=models.CASCADE) cards = models.ManyToManyField(Contain, through ="Integration") class Integration(models.Model): Box = models.ForeignKey(Container, on_delete=models.CASCADE) Card = models.ForeignKey(Contain, on_delete=models.CASCADE) date_integration = models.DateField(auto_now_add=True) date_desintegration = models.DateField(blank=True, null=True) class ContainSerializer(serializers.ModelSerializer): class Meta: model = Contain fields = ProductSerializer.Meta.fields + ('typeCard', "state") class UraContainerSerializer(serializers.ModelSerializer): class Meta: model = UraContainer fields = ProductSerializer.Meta.fields + ("name",'ura_coffret','cards') class IntegrationSerializer(serializers.ModelSerializer): Card = ContainSerializer() class Meta: model = Integration fields = ('id', 'Box', 'Card', "date_integration", "date_desintegration") def create(self, validated_data): cards_data = validated_data.pop('uraCard') integration = Integration.objects.create(**validated_data) for card_data in cards_data: Contain.objects.create(integration=integration, **card_data) return integration But i have an error : IntegrityError at /api/products/integration/ null value in column "Card_id" violates not-null constraint DETAIL: Failing row contains (4, 2019-07-30, 2, null, null). I don't uderstand why i have this error. -
How can i link user.object to object's object?
I have a model where users can add patients and every patient can have many images. so when making the upload images form how can I link the form to the patients? Here is my models.py class Patient(models.Model): FirstName = models.CharField(max_length=264) LastName = models.CharField(max_length=264) Adress = models.TextField(blank=True, null=True) Telephone_no = PhoneNumberField(blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='patients') birth_date = models.DateField(blank=False,) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) Notes = models.TextField(blank=True, null=True) def __str__(self): return str(self.FirstName) + " " + str(self.LastName) def get_absolute_url(self): return reverse('patient_detail', kwargs={"pk": self.pk}) # The ImageModel for multiple images class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.ImageField(upload_to = user_directory_path , verbose_name = 'Image') views.py # The view for analysing images def AnalyseView(request): if request.method == 'POST': form = forms.ImageForm(request.POST) if form.is_valid(): image = form.save(commit=False) messages.success(request,"image added successfully!") image.save() return HttpResponseRedirect(reverse_lazy('patients:patient_detail', kwargs={'pk' : image.patient.pk})) else: form = forms.ImageForm() return render(request, 'patients/analyse.html', {'form': form}) so how can I link that to the patients as the upload view is accessed by a button in the patient_detail view? btw I can upload images from the admin interface only for now. -
How to create a django listing with Select2 and Formset?
I have two tables: Tables I need to create a component that lists the tables and presents itself as follows: FrontEnd Result I use "Django == 2.2" and "django-select2 == 7.1.0". The Models that create the three tables are below Model "Grupo" class Grupo(models.Model): nome = models.CharField(max_length=60) id_condominio = models.ForeignKey( Condominio, on_delete=models.CASCADE, ) class Meta: db_table = 'grupo' def __str__(self): return self.nome Model "Grupo Unidade" class GrupoUnidade(models.Model): id_grupo = models.ForeignKey( Grupo, on_delete=models.CASCADE, ) id_unidade = models.ForeignKey( Unidade, on_delete=models.CASCADE, ) class Meta: db_table = 'grupo_unidade' def __str__(self): return self.nome Model "Unidade" class Unidade(models.Model): id_condominio = models.ForeignKey( Condominio, on_delete=models.SET_NULL, null=True ) tipo = models.ForeignKey( TipoUnidade, on_delete=models.CASCADE, ) unidade = models.CharField(max_length=12) class Meta: db_table = 'unidade' I've used the formset before but I don't know how to create this relationship and view. I would like to know how to relate and create this listing. -
Django. Search in multiple models
Help to unite search in several models. I have two models Apartment and Houses. These models have the same strings State. According to them, I customize the search in views.py. It looks like this: views.py def search(request): queryset_list = Houses.objects.order_by('-list_date') if 'state' in request.GET: state = request.GET['state'] if state: queryset_list = queryset_list.filter(state__iexact=state) context = { 'queryset_list': queryset_list, } return render(request, '/search-templates/search.html', context) As a result, I see Houses from the selected region. I understand that the search is conducted in the model Houses. It works great! queryset_list = Houses.objects.order_by('-list_date') Question: How to combine search? Show objects from two models Apartment and Houses. Thank you in advance! -
how can I limit the count of returned objects from a related manager in django
I have two models Category and Product the wanted behavior is to return all categories with and each category should include 10 products I tried to return all categories without limiting the products returned objects then I used the slice filter in the templates, but I am not sure if this is efficient for big scale and I am not sure if Django will lazy-load the products. is the way I am using is efficient or I should limit the products when querying the categories using Category.objects.all() ? -
How to change button inside a django table to text after it has been accessed
So, this is my first project with Django, and for the first time I am using the Django-Tables2. I have a Django table with three columns, last column contains add button for each row which when clicked takes me to another page where I can select options. on submitting the options, the mapping gets saved in database and user gets redirected to the tables page again. Here I want to change the "add" button to "Done". def edit_item(request, pk): item = get_object_or_404(BAReg, id=pk) if request.method == "POST": form = ProcessForm(request.POST or None, instance=item) if form.is_valid(): processes = form.cleaned_data.get('process') print(processes) for country in processes: issue = ProcessReg() issue.ba = item.ba issue.regulation = item.regulation issue.process = country issue.save() return redirect('secondpage') else: form = ProcessForm(request.POST,instance=item) return render(request, 'addbutton.html', {'form': form}) def secondpage(request): ba = request.session.get('ba') print(ba) table = PersonTable(BAReg.objects.filter(regulation=ba)) RequestConfig(request).configure(table) context = {'table': table} return render(request,'secondpage.html/',context) class PersonTable(tables.Table): Process = tables.LinkColumn('edit_item',text='Add Process', args=[A('pk')]) class Meta: model = BAReg template_name = 'django_tables2/bootstrap4.html' <form method='post' action=''> {% csrf_token %} {{ form.as_p }} <input type='submit' value='submit'> </form> {% load render_table from django_tables2 %} {% block content %} <!-- <form method="POST"> --> {% render_table table %} <!-- {{ form.as_p }} --> <!-- <button type="submit" style="margin-left: 680px">Submit</button> </form> … -
How to Fix adding a User to a Group using Django REST framework(API)
I'm trying to build a savings API where A user can get the list of groups available and join the group as long as it as not exceeded the maximum number of members. I've tried a series of approach but it seems not to work, anytime I try to add a user to a group, it seems like it trying to add the whole user properties. I made a group model and connected it to the user model via a ManytoMany field since a user can join many groups and a group can house many users. Where my problem lies in the serializer, any time I try to add a user groups.model class Groups(models.Model): name = models.CharField(max_length = 50, unique = True) group_id = models.UUIDField(default = uuid.uuid4, editable = False) max_no_members = models.PositiveIntegerField() savings_amount = models.PositiveIntegerField() savings_type = models.CharField(max_length = 10, default = 'Monthly') description = models.TextField(blank=True) begin_date = models.DateField() created_date = models.DateTimeField(auto_now_add=True) searchable = models.BooleanField(default = True) members = models.ManyToManyField(User, related_name='group_members') created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete =models.CASCADE,related_name='group_admin' ) def __str__(self): return self.name groups.serializer #List of Memebers class GroupMembersListSerializer(serializers.HyperlinkedModelSerializer): # users = UserSerializer(many=True, read_only = True) class Meta: model = Groups fields = ['members','name'] #Join a Group class JoinGroupSerializer(serializers.ModelSerializer): users_to_join = … -
Wagtail add custom comments feature to blog (probably with orderable)
I mean, I need something that will let me hook comments to wagtail page, probably using Orderable. I want to use this model to store comments (My users logs in using google auth, so yeah, I can handle ownership of comment): # Comment model class Comment(models.Model): text = models.TextField() author = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) As you can see below I tried to make it work like in this question, but on form sumbit it throws: AttributeError at /first-post/ 'NoneType' object has no attribute 'attname' Here's my BlogPage - Each instance of this page represents one post in blog: # Standard blog page with text/images etc. class BlogPage(Page): date = models.DateField(auto_now=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) miniature = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='miniature' ) body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ('gallery', blocks.StreamBlock( [ ('image', ImageChooserBlock()), ], label='image gallery' )), ]) content_panels = Page.content_panels + [ MultiFieldPanel([ ImageChooserPanel('miniature'), FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Blog information"), StreamFieldPanel('body'), ] def serve(self, request): from .forms import CommentForm if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.page_id = self.id comment.save() return redirect(self.url) else: form = CommentForm() return render(request, self.template, { 'page': self, 'form': form, … -
Is it necessary to run Django behind a reverse proxy when deployed on Kubernetes
Historically, it's always been good practice to launch any wsgi app behind a reverse proxy. So, it felt natural to me, when launching on Kubernetes, to throw up a 2 container pod, one running an nginx reverse proxy, the other running the Django application. Is this just wasted resources when providing ingress via an nginx ingress controller? Is there any benefit at all to running an additional reverse proxy in this scenario? -
I'm missing something editing database record with Django and Python
I'm new to Django and Python and I want to be able to edit a database record with a model form. It is frustrating as I know I've missed something that will be obvious but I've spent hours trying to work out what it is. I've looked at some posts and they give me an idea but I've missed something in the reading. I'm running Windows 10 desktop, python 3.7. The closest post to what I'm trying to do is this one but I'm still missing something. how to edit model data using django forms (what should the XXX look like in the recommended answer) I've tried various combinations of pk in my_get_name with no success. I appreciate any help and guidance for yourselves. The error I get is: NameError at /proj1/employees/update/EMP0001 name 'EmpID' is not defined Request Method: GET Request URL: http://localhost:8000/proj1/employees/update/EMP0001 Django Version: 2.2.1 Exception Type: NameError Exception Value: name 'EmpID' is not defined and the error occurs in views.py where I define my_instance views.py from .models import emp_table from .forms import EmpDetailForm def my_get_name(request, pk): # error occurs on the next line my_instance = emp_table.objects.get(id=EmpID) if request.method == 'POST': form = EmpDetailForm(request.POST, instance=my_instance) if form.is_valid(): # process … -
Django unable to change name for url pattern
I'm trying to refactor some of my code so that it is consistent, i.e. the name: path('create_project', ProjectCreateView.as_view(), name='create-project'), I have also changed it in my template: <a href="create-project"> <img src="{% static 'project_portal/image/icon_add_circle.png' %}" alt="Add" width="32"> </a> but now I get the following: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/si/create-project/ Raised by: project_portal.views.ProjectDetailView How can changing a "_" to "-" break the code? -
Django: How to add a print button to objects to print some (special) fields of a model instance
I know this might seem to be quite similar to Django admin overriding - adding a print button The answer there is to use django-object-actions, which I already tried but it looks a bit too complex for such an simple task. I would prefer to use "just Django" I would like to create a printable view of some fields of a Django models instance. Let's say I want to print an users Name Last Name Number What I image is something like this: Clicking on a print button, shown at the list view: An preformatted and easy to print website opens which contains the data: What I have so far I added the button by using the following code: class MyModelAdmin(admin.ModelAdmin): list_display = ('number', 'name', 'last_name', ..., 'account_actions') ... def account_actions(self, obj): return format_html( '<form method="post" action="/print_view.htm"> \ <input type="hidden" name="name" value="{}"> \ <button type="submit" name="action">Print</button> \ </form>', obj.name ) account_actions.short_description = 'Actions' account_actions.allow_tags = True So my idea is to send the data which I want to get printed to another Website (via POST, on the same server). I would extract the data from the request then and create a printable view. My question is: Is it possible to … -
Server side rendering in Django does not work when view is loaded into iframe on different domain
My Django app has a view that will be loaded into iframes on different domains. To allow this I'm using @xframe_options_exempt. The static parts of the template are loaded properly in the iframes, but for some reason the parts of the template that have to be rendered are not showing up. When I load the iframe on the same origin everything works fine, so do I have to include something similar like @xframe_options_exempt as a template tag inside my template? -
deploing django app to heroku: application error
I'm trying to deploy my project to heroku. I'm new to django and heroku so I'd appreciate any help. All went smoothly up until opening the heroku app with the application error procfile web: gunicorn count_project.wsgi requirements.txt dj-database-url==0.5.0 Django==2.2 django-heroku==0.3.1 gunicorn==19.9.0 psycopg2==2.8.3 pytz==2019.1 sqlparse==0.3.0 whitenoise==4.1.3 runtime.txt python-3.7.3 message after running heroku logs --tail 2019-07-30T13:03:42.277475+00:00 heroku[web.1]: Starting process with command `gunicorn count_project.wsgi` 2019-07-30T13:03:46.087651+00:00 heroku[web.1]: State changed from starting to crashed 2019-07-30T13:03:46.065132+00:00 heroku[web.1]: Process exited with status 127 2019-07-30T13:03:46.018957+00:00 app[web.1]: bash: gunicorn: command not found 2019-07-30T13:03:46.000000+00:00 app[api]: Build succeeded 2019-07-30T13:03:58.852793+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=countthewords.herokuapp.com request_id=77fd8632-f1ec-4f12-9271-3f9c42dc19d3 fwd="95.102.233.42" dyno= connect= service= status=503 bytes= protocol=https 2019-07-30T13:04:00.698445+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=countthewords.herokuapp.com request_id=f05da2fd-0222-4ef6-a005-b4dcbd0993ce fwd="95.102.233.42" dyno= connect= service= status=503 bytes= protocol=https -
How do I configure a Joomla site on the same port where a Django site is running with Apache
I am using mod_wsgi and the OS is Ubuntu 16.04. This is how my apache configuration file looks like: <VirtualHost 172.16.146.130:80> Alias /static /var/www/html/myapp/static <Directory /var/www/html/myapp/static> Require all granted </Directory> <Directory /var/www/html/myapp/inventoryms> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-home=/var/www/html/myapp/env python-path=/var/www/html/myapp WSGIProcessGroup myapp WSGIScriptAlias / /var/www/html/myapp/inventoryms/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined I would like to add a Joomla site running on the same port than the Django app that has been already configured with Apache. -
Show two tables specific column data into one list?
I have two tables Customer and Subscription in which Customer has the list of customers and Subscription contains the Customer and Packages. In the customer list i want to show how many packages each customer has. Subscription Model class Subscription(models.Model): client = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True, related_name="subscriptions") package = models.ForeignKey(Package, on_delete=models.SET_NULL, blank=True, null=True) valid_start_date = models.DateTimeField() valid_end_date = models.DateTimeField() usage_count = models.IntegerField(null=True) status = models.CharField(max_length=20) transaction = models.BigIntegerField(blank=True, null=True, default=0) created_at = models.DateTimeField() updated_at = models.DateTimeField() Customer Model class Customer(AbstractBaseUser): first_name = models.CharField(max_length=250, blank=True, null=True) last_name = models.CharField(max_length=250, blank=True, null=True) email = models.EmailField(unique=True, blank=True, null=True) mobile_number = models.BigIntegerField(blank=True, null=True) password = models.CharField(max_length=1000, blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) profile_picture = models.ImageField(upload_to="user_data/profile_picture", blank=True) address = models.CharField(max_length=500, blank=True, null=True) country = models.ForeignKey(Countries, on_delete=models.SET_NULL, blank=True, null=True) state = models.ForeignKey(States, on_delete=models.SET_NULL, blank=True, null=True) city = models.ForeignKey(Cities, on_delete=models.SET_NULL, blank=True, null=True) pincode = models.IntegerField(blank=True, null=True) number_of_logins = models.IntegerField(blank=True, null=True) is_active = models.BooleanField(default=True) gcm = models.CharField(max_length=250, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) USERNAME_FIELD = "email" Expected Result : I want to show the package field data from Subscription Model into the list of Customer model. Actual Result : Only Customer field data -
duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=() already exists
good day!A separate page was created to change the password, when you enter the password and repeat it and click on the "change password" button, a duplicate key value violates unique constraint "core_user_username_key" error appears DETAIL: key (username) = already exists how to solve this error? forms.py class CallcenterPasswordChange(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput(), label='Новый пароль') password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля') def clean(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='Повтор нового пароля не совпадает', ) return self.cleaned_data class Meta: model = User fields = ('username', 'first_name', 'last_name', 'password1', 'password2') views.py class CallcenterPasswordChangeView(AbsCallcenterView): template_name = 'callcenter/password_change.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) patient_pk = kwargs.get('patient_pk') patient = get_object_or_404(Patient, pk=patient_pk) initial_data = model_to_dict(patient.user) context['form'] =CallcenterPasswordChange(initial=initial_data) context['patient_pk'] = patient_pk context['patient'] = patient return context def post(self, request, **kwargs): context = super().get_context_data(**kwargs) patient_pk = kwargs.get('patient_pk') patient = get_object_or_404(Patient, pk=patient_pk) form = CallcenterPasswordChange(request.POST) context['form_user'] = form context['patient'] = patient if form.is_valid(): form.save() else: return render(request, template_name=self.template_name, context=context) -
Exception at /openid/callback/login/ this login is not valid in this application in Django
I was trying to make an SSO using keycloak and Django application. My login is working fine as after logged into keycloak I've seen the user session is existed there. But the problem is that, it's not going to the secured page rather it's showing this error : raise Exception('this login is not valid in this application') Exception: this login is not valid in this application And if I reload this then it shows another error: OpenID Connect authentication has failed Error message is: Invalid response invalid_grant. Query content was: This is my code: settings.py INSTALLED_APPS = [ #....... 'bossoidc', 'djangooidc', 'test', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'bossoidc.backend.OpenIdConnectBackend', # ... ] auth_uri = "http://localhost:8080/auth/realms/test" client_id = "test" public_uri = "http://localhost:8000" from bossoidc.settings import * configure_oidc(auth_uri, client_id, public_uri) OIDC_PROVIDERS['KeyCloak']['behaviour']['scope'] = ['openid', 'profile', 'email'] test/views.py def index(request): return HttpResponse('index. <a href="/secure">Secure</a>') @login_required def secure(request): return HttpResponse('Secure page. <a href="/openid/logout">Logout</a>') urls.py urlpatterns = [ url(r'', include('test.urls')), url(r'^admin/', admin.site.urls), url(r'openid/', include('djangooidc.urls')) ] test/urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^secure$', views.secure, name='secure'), ] I'm using this plugin for open-id connection: boss-oidc . My python version is Python 3.6.8, Django But there is also some issues after i run this install command for bossoidc pip … -
Django Max count of foreign key set
class Blog(models.Model): pass class Article(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) b = Blog.objects.filter(...) Given b, is it possible to find with a single query the highest count of associated articles? I could do that by iterating: max_count = 0 for blog in b: if b.article_set.count() > max_count: max_count = b.article_set.count() Is there a more efficient way that uses the ORM/SQL? -
Django database access optimization: Efficient creation of many-to-many relationships (between existing objects)
I'm using Django 2.2 with a PostgreSQL database. I have two models: Gene and Annotation and need to create and link (many-to-many) thousands of Genes and Annotations at the same time. class Gene(models.Model): identifier = models.CharField(max_length=50, primary_key=True) annotation = models.ManyToManyField(Annotation) class Annotation(models.Model): name = models.CharField(max_length=120, unique=True, primary_key=True) I already found a way to create the objects very efficiently: Gene.objects.bulk_create([Gene(identifier=identifier) for identifier in gene_id_set]) This is my Django-docs-inspired way to create relationships: relationships = { 'gene1': ['anno1', 'anno2'], 'gene2': ['anno3'], ... } for gene in relationships: gene = Annotation.objects.get(pk='gene1') gene.annotation_set.set([Annotation.objects.get(pk=anno) for anno in relationships[gene]) But this is very clumsy: It hits the database 4 times! Is there not a better way, using Django-built-in-tools or raw SQL queries? The many-to-many table (myapp_gene_annotation) looks like this: id gene_id annotation_id 1 gene1 anno1 2 gene1 anno2 3 gene2 anno3 ...