Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render database values in template django
i have created app student from this i have to access database values on templates i have done the changes and apply migrations but it shows No changes detected in app 'student' , when i visit the localhost/phpmyadmin/ i only get the text from html file but not getting database values i want output like this: the student here, name, department, class, on web page 1)models.py file `from django.db import models class Student(models.Model): roll_no = models.TextField() name = models.TextField(max_length = 40) stud_class = models.TextField() department = models.TextField() ` 2)views.py file from django.shortcuts import render from django.shortcuts import render from django.http import HttpResponse from .models import Student def student_show(request): student = Student.objects.all() #order_by('roll_no') return render(request,'student/student1_show.html', {'student':student}) -
Assign URL to some specific words of a paragraph in dynamically rendered template from the data stored in Database
I have a Django blog app which shows the posts that I have created using a ClassBased DetailView. I want to assign different URLs to the different words in the paragraph just like Wikipedia. If it was a static page, it would have been solved easily but is it possible to assign <a> tags/URL values to the different words. Is there any method to do so? -
Django+MySQL - "Authentication plugin 'caching_sha2_password' cannot be loaded"
When running the command: python manage.py runserver I'm getting the following error: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n") These are the relevant settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'polls', 'USER': 'root', 'PASSWORD': '<my-password>', 'HOST': 'localhost' } } I've seen solutions that went around the problem, such as in this thread. They suggest changing the engine to mysql.connector.django, however the engine recommended by django is mysqlclient and therefore I would like to use it. Other suggestion were to use naive password instead of sha2. I'd rather not go with this solution for security reasons. Versions: mysql 8.0.17 for Win64 on x86_64 (MySQL Community Server - GPL) python 3.7.4 Django 2.2.4 mysqlclient 1.4.4 -
NoReverseMatch at /1/dischargedetails/
I am trying to create multiple forms in one template page(dischargedetails.html) using different views. Each form model is having foreignkey Ipd, when i am trying to submit forms ending up with error "Reverse for 'create-investigation' with keyword arguments '{'ipd_id': ''}' not found. 1 pattern(s) tried: ['(?P\d+)/investigation/$']" , models.py : class Investigation(models.Model): id = models.AutoField(primary_key = True) ipd = models.ForeignKey(Ipd,on_delete = models.DO_NOTHING) name = models.CharField(max_length=60) report = models.TextField(max_length=500) date = models.DateField(("Date"), default=datetime.date.today) class Procedure(models.Model): id = models.AutoField(primary_key = True) ipd = models.ForeignKey(Ipd,on_delete = models.DO_NOTHING) report = models.TextField(max_length=500) date = models.DateField(("Date"), default=datetime.date.today) time = models.TimeField( blank=True,default=now) urls.py : re_path(r'^(?P<ipd_id>\d+)/investigation/$', my_patient.create_investigation, name='create-investigation'), re_path(r'^(?P<ipd_id>\d+)/dischargedetails/$', my_patient.discharge_detail, name='discharge_details'), views.py: @login_required def discharge_detail(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method =="POST": procedure = ProcedureForm(request.POST) if procedure.is_valid(): procedure.save() return HttpResponseRedirect(request.path_info) else : return HttpResponse(procedure.errors.as_data()) else : prolist=Procedure.objects.all().filter(ipd=ipd_id) procedure = ProcedureForm() return render(request, 'dischargedetails.html',{'object':object,'procedure':procedure,'prolist':prolist}) @login_required def create_investigation(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method=="POST": investigation = InvestigationForm(request.POST) if investigation.is_valid(): inves = investigation.save(commit = False) inves.object = object inves.save() return HttpResponseRedirect(request.path_info) else: return HttpResponse(investigation.errors.as_data()) else : investigationlist = Investigation.objects.all().filter(ipd=ipd_id) investigation = InvestigationForm() return render(request, 'dischargedetails.html',{'object':object,'investi':investigation,'investilist':investigationlist}) template <form method="post" action="{% url 'create-investigation' ipd_id=ipd.ipd_id %}" enctype="multipart/form-data"> -
Websocket disconnecting while running chat app from Django Channels tutorial
I'm building the chat app from Django Channels tutorial inside my django project. I successfully completed Tutorial Part 1 But when I get to the part of "Enable a channel layer" in Tutorial Part 2 I get a ConnectionRefusedError. In my_project/settings.py file I got INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stream_django', 'channels', 'debug_toolbar', 'messaging_app', ] WSGI_APPLICATION = 'my_project.wsgi.application' ASGI_APPLICATION = 'my_project.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } CELERY_BROKER_URL = 'redis://localhost:6379' In my_project/routing.py got from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import messaging_app.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( messaging_app.routing.websocket_urlpatterns ) ), }) In my_project/urls.py have urlpatterns = [ ... path('chat/', include('messaging_app.urls')), ... ] and in my_project/messaging_app/urls.py have urlpatterns = [ path('', views.index_chat, name='index_chat'), path('<str:room_name>/', views.chat_room, name='chat_room'), ] In my_project/messaging_app/routing.py got from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/chat/<str:room_name>/$', consumers.ChatConsumer), ] In my_project/messaging_app/consumers.py from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) I tried to run $ python3 manage.py shell >>> import channels.layers >>> channel_layer = channels.layers.get_channel_layer() … -
Django project and application data model
I have to build several web-panels and I'm using django. Each panel is a Django Application, so I have: datalake_backend __init__.py models.py : IAV_PANEL __init__.py models.py : AMAZON_FUSE_PANEL __init__.py models.py : Currently the command: ./manage.py makemigrations skips the models defined into datalake_backend/models.py I defined the installed application as follow: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'datalake_backend' 'datalake_backend.IAV', 'datalake_backend.AMAZON_FUSE_REVENUE' ] and it's falling to find datalake_backend. It this not possibile or am I missing something? Perhaps need I to defined a new application which holds the datalake_backend common logic and service? Something like: datalake_backend __init__.py models.py : IAV_PANEL __init__.py models.py : AMAZON_FUSE_PANEL __init__.py models.py : DATALAKE_BACKEND __init__.py models.py : In this case, I wonder why there is a models.py file into the project folder. Any link, suggestion or other pointers are welcomed. -
How can i custom a model that insert form data in a list that will show as one field in Django admin?
I am new to Django, and am trying to set a model that takes all the data that is implemented by the end-user, and insert them in a list and save it in the database, so I can see the data of each end-user in a separated list in Django admin. I tried to use super() to initialize the models.Model but what happened is that I wrote super(models.Model).init(self) and then ran it, it gave me an error saying that the relation attribute is missing class Topic(models.Model): def __init__(self,email,age,relation): super(models.model).__init__(self) self.email = email self.age = age self.relation = relation self.data = [] def submit(self): self.data.append(self.email) self.data.append(self.age) self.data.append(self.relation) def __str__(self): return "{}".format(self.data) def __rper__(self): return self.data ## this is the other code that I tried but it gave me an error saying email isn't defined ## class Topic(models.Model): email = models.CharField(max_length = 264,unique = True) age = models.IntegerField() relation = models.CharField(max_length = 264,unique = True) def submit(self): data = list(email,age,relation) def __str__(self): return "{}".format(Topic.submit()) def __rper__(self): return self.__str__() this error is for the second code, hope you guys will help and thank you so much. >>> from form.models import Topic >>> t = Topic(email = "naser@gmail.com",age = 20,relation = "single") >>> t.submit() … -
How to make the appearance of form in django?
I am trying to make a form but it is not showing me. Instead it is giving me error UnboundLocalError at /withdraw/ local variable 'form' referenced before assignment How to resolve this issue? views.py @login_required def withdraw(request): if request.method == 'POST': form = Withdrawapayment(request.POST) if form.is_valid(): form.save() messages.success(request, f'Your request has been submitted.') return redirect('balance') context = {'form': form} return render(request, 'nextone/withdraw.html', context) models.py class WithdrawPayment(models.Model): payment = models.DecimalField(max_digits=100, decimal_places=2) class Meta: verbose_name_plural = 'Withdraw Payment' forms.py class Withdrawpayment(forms.ModelForm): class Meta: model = WithdrawPayment fields = ['payment'] -
How to implement log rotation in Django so that the files that are "rolled over" have custom names?
I want to implement logging in Django such that: 1] After a log file size exceeds a certain threshold, a new log file is generated and written to. 2] The name of this new file should be customisable. As an example, the log file name could be current_date_and_time-app_name.log 3] [Optional] The file that has reached the size limit is zipped and stored. How do I go about doing this? I tried using the RotatingFileHandler class but it rewrites old logs and also does not give the flexibility to change the log name. Here is the code that I have written: BASE_DIR_APP = os.path.dirname(os.path.abspath(__file__)) DIR_LOGS = os.path.join(BASE_DIR_APP, 'logs') current_time = datetime.now().strftime("%b-%d-%Y_%H-%M-%S--%f") U_LOGFILE_SIZE = 1 * 1024 U_LOGFILE_COUNT = 2 logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { 'format': '%(name)-12s %(levelname)-8s %(message)s' }, 'file': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'console' }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'file', 'maxBytes': U_LOGFILE_SIZE, 'backupCount': U_LOGFILE_COUNT, 'filename': os.path.join(DIR_LOGS, current_time + '.log') } }, 'loggers': { '': { 'level': 'DEBUG', 'handlers': ['console', 'file'] } } }) -
Couldn't find that process type (web) deploying Heroku
In logs there is message about no running process. The output from heroku ps:scale web=1 is Couldn't find that process type (web). Procfile: web: gunicorn radio.wsgi --log-file - wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'radio.settings') application = get_wsgi_application() project structure: radio/ ├── player/ ├── radio/ ├── static/ ├── Procfile ├── requirements.txt └── runtime.txt -
M2M field was required and then changed to blank=True
I've got 2 models Task and TaskType. Task could have several types and they are required. Now new requirements dictate that types are unnecessary and should be removed. I set blank=True in Task field called types and run migration. Actually migration was created but didn't applied to DB. class TaskType(Base): name = models.CharField(max_length=50) class Task(Base): ... # initially there was only one parameter - TaskType types = models.ManyToManyField(TaskType, blank=True) ... -
Django: unable to create Generic Foreign key object
I'm using Django 2.x I have two models class DynamicUrlObject(models.Model): content_type = models.ForeignKey(ContentType, null=True, on_delete=models.SET_NULL) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') domain = models.CharField(max_length=255) and class MyModel(models.Model): name = models.Char(max_length=50) my_obj = fields.GenericRelation(DynamicUrlObject, related_query_name='my_obj') I have an object of MyModel and want to create a record for DynamicUrlObject and link same to the MyModel model. I'm doing it something like dy_obj = DynamicUrlObject.objects.get_or_create( content_object=my_existing_obj, domain='http://example.com' ) my_existing_obj.my_obj = dy_obj my_existing_obj.save() But this is not creating a record for DynamicUrlObject and gives an error as django.core.exceptions.FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. -
In my django admin change_list, there are names with diacritics. How to order them properly?
I'm using it with Python 3.6.5. In my Django 2.1 app, I have a model object like this: class Person(models.Model): name = models.CharField(max_length=64) with some names presenting diacritics. In my admin.py, I have: from django.contrib import admin from .models import Person class PersonAdmin(admin.ModelAdmin): ordering = ['name'] admin.site.register(Person, PersonAdmin) So, this is the default order I got when accessing my change_list admin view: Joseph Josué José Éderson but I need them to show up in this order: Éderson Joseph José Josué Also, I have a sort key to do this trick when I have a list: import locale def sort_key_BR(): locale.setlocale(locale.LC_ALL, "pt_BR.UTF-8") return locale.strxfrm names = ['Joseph', 'Josué', 'José', 'Éderson'] names.sort(key=sort_key_BR()) for n in names: print(n) # Éderson Joseph José Josué Worth to mention, in my project's settings.py, I already have: LANGUAGE_CODE = 'pt-BR' What is the proper way to inform a sort key rather than the default to ordering in Django models? Rather what is a proper way of doing this? -
Simple way to make a file available to user for download
I have a template xls file in the media folder. I want that the user can easily download this file from the page. What is a simple way of doing this? I could not find any simple reliable way of doing this. Sorry, I'm new to Django. My urls.py: urlpatterns = [ ... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) template: ... <a href="#">Download Template</a> -
PostGIS OSM import: the number of features is -1
Disclaimer: it's too specific: anybody can reproduce this with a blank Django project which used gdal, and a download of a file here. I'm using Gdal for Django to check what's inside an OSM file. I've tried to download a dozens files from Geofabrik here. From all those files (osm and pbf) I'm using this small script to get some informations: from django.contrib.gis.gdal import DataSource ds = DataSource(r'C:\blabla\data\mayotte-latest.osm.pbf') for l in ds: print('name: "%s", geom_type.name: %s ' % (l.name, l.geom_type.name)) print(" fields: %s, field_widths: %s" % (l.fields, l.field_widths)) print(" l.num_feat: %s, l.extent: %s" % (l.num_feat, l.extent)) print(" l.field_widths: %s, l.field_precision: %s" % (l.field_widths, l.field_precisions)) print(" l.field_types: %s" % (l.field_types, )) for feat in l: print(feat.get('NAME'), feat.geom.num_points) else: print(" ... no points") And with all files (no exception), I get something very close to: name: "points", geom_type.name: Point fields: ['osm_id', 'name', 'barrier', 'highway', 'ref', 'address', 'is_in', 'place', 'man_made', 'other_tags'], field_widths: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] l.num_feat: -1, l.extent: (44.85604, -13.1491, 45.45754, -12.46832) l.field_widths: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], l.field_precision: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] l.field_types: [<class 'django.contrib.gis.gdal.field.OFTString'>, <class 'django.contrib.gis.gdal.field.OFTString'>, <class 'django.contrib.gis.gdal.field.OFTString'>, <class 'django.contrib.gis.gdal.field.OFTString'>, <class 'django.contrib.gis.gdal.field.OFTString'>, <class … -
How to get user in Django signals
How can you get the user who is saving record in django signals? I am using signals to fill in data when a user marks completed = True via a form. I was hoping something like instance.User or instance.CustomUser.username would work, but it just throws errors that these don't exist in Maintenance model. models.py from django.db import models from accounts.models import CustomUser from django.contrib.auth import get_user_model from django.urls import reverse from django.conf import settings from django.db.models.signals import post_save from django.utils.timezone import utc import datetime from django.utils import timezone class Maintenance(models.Model): device = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,) customerTag = models.CharField(max_length=50,) maintenanceItem = models.CharField(max_length=35,blank=True,) maintenanceDescrip = models.TextField(max_length=300,blank=True,) maintenanceNotes = models.TextField(max_length=300,blank=True,) dateCreated = models.DateTimeField(auto_now_add=True,) dateDue = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, editable=True) dateCompleted = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, editable=True) completed = models.BooleanField(default = False) createdBy = models.CharField(max_length=35,blank=True,) completedBy = models.CharField(max_length=35,blank=True,) def __str__(self): return str(self.maintenanceItem) def get_absolute_url(self): return reverse('equipmentdashboard',) def check_complete(sender, instance,**kwargs): hasCompleteDate = instance.dateCompleted if not (hasCompleteDate is None): return else: isComplete = instance.completed if isComplete == True: completed_By = ? Maintenance.objects.filter(id = instance.id).update(completed = True, dateCompleted = timezone.now(), completedBy = completed_By,) post_save.connect(check_complete, sender = Maintenance) -
Celery Redis instance filling up despite queue looking empty
We have a Django app that needs to fetch lots of data using Celery. There are 20 or so celery workers running every few minutes. We're running on Google Kubernetes Engine with a Redis queue using Cloud memorystore. The Redis instance we're using for celery is filling up, even when the queue is empty according to Flower. This results in the Redis DB eventually being full and Celery throwing errors. In Flower I see tasks coming in and out, and I have increased workers to the point where the queue is always empty now. If I run redis-cli --bigkeys I see: # Scanning the entire keyspace to find biggest keys as well as # average sizes per key type. You can use -i 0.1 to sleep 0.1 sec # per 100 SCAN commands (not usually needed). [00.00%] Biggest set found so far '_kombu.binding.my-queue-name-queue' with 1 members [00.00%] Biggest list found so far 'default' with 611 items [00.00%] Biggest list found so far 'my-other-queue-name-queue' with 44705 items [00.00%] Biggest set found so far '_kombu.binding.celery.pidbox' with 19 members [00.00%] Biggest list found so far 'my-queue-name-queue' with 727179 items [00.00%] Biggest set found so far '_kombu.binding.celeryev' with 22 members -------- summary ------- Sampled … -
Django-ORM - selecting the last record by date for each attribute
I have constructed the following query "chain": survey_results = OrganisationSurveyResult.objects.filter(user=user) survey_results = survey_results.filter( created_date__in=survey_results.values( 'user', 'organisation_survey' ).annotate( latest_created_date=Max('created_date') ).values( 'latest_created_date' ) ).annotate( module=F('organisation_survey__survey__module'), score=F('survey_result__normalized_score'), rank=F('survey_result__rank_class'), ).values( 'module', 'score', 'rank', 'created_date' ) Which returns the following entries when iterated: {'created_date': datetime.datetime(2019, 8, 14, 15, 10, 54, 214754, tzinfo=<UTC>), 'module': UUID('151cb049-65c5-4278-8133-610859be6f34'), 'score': 95, 'rank': 'Low'} {'created_date': datetime.datetime(2019, 8, 14, 15, 10, 54, 220694, tzinfo=<UTC>), 'module': UUID('7c5848eb-3090-4819-8eac-166367ab0e65'), 'score': 91, 'rank': 'Low'} {'created_date': datetime.datetime(2019, 8, 14, 15, 10, 54, 226334, tzinfo=<UTC>), 'module': UUID('b894c988-af3d-4ecb-a2a1-c42225b64b71'), 'score': 100, 'rank': 'Low'} {'created_date': datetime.datetime(2019, 8, 14, 15, 10, 54, 232898, tzinfo=<UTC>), 'module': UUID('22edce11-f78e-4b2e-a1de-1ecc7f0518c9'), 'score': 59, 'rank': 'Medium'} The request-response cycle for this API endpoint is 51-89ms. The DB query time is 24-38ms. It was originally 1280ms as I was using a prefetch_related method and looping. It's also passed all tests. It has four record entries for a single user (there are only four modules). Each date in the list of entries is also the last SurveyResult for that module and user. Happy so far. However, my next step is for each of the above entries in the list, I need to obtain the following: for survey_result in survey_results.iterator(): resource = Resource.objects.filter(module=survey_result['module'], rank_class=survey_result['rank']) So, I am adding an extra 4 … -
How to save model with foreign key
I am making Django scraping application where I want to keep scraped properties and rooms from bookingdotcom. Whilst scraping I need that the flat would be linked for a property which already exists in the DB. The thing is that I am novice with django and I am not sure how to save flat record which links to the property. def process_item(self, item, spider): if not item: spider.crawler.stats.inc_value('empty_item_parsed') raise DropItem("Dropping empty item") bdc_room = BDCRoom() #How to save it so it links to property, which already exists in the database. bdc_room.bdc_property = BDCProperty().pk bdc_room.name = item["flat_name"] bdc_room.created_datetime = item["date_time"] bdc_room.save() try: bdc_property = BDCProperty.objects.get(name=item["listing_name"]) print("Listing already exist") return item except BDCProperty.DoesNotExist: pass bdc_property = BDCProperty() bdc_property.name = item["listing_name"] bdc_property.created_datetime = item["date_time"] bdc_property.address = item["address"] bdc_property.rating = item["rating"] bdc_property.review_count = item["review_count"] bdc_property.available_rooms_count = item["availability_count"] bdc_property.save() return item -
How to remove SMTPAAuthenticationError caused by changing of EMAIL_HOST_USER?
How to show the logged in user email address whenever I send email to bilalkhangood6@gmail.com? Although every time it shows me another email address(bilalkhangood4@gmail.com) who is not logged in. I used user.request.email to send email from those user who is logged in. After changing EMAIL_HOST_USER, it gives me SMTPAuthenticationError at /ViewSendEmail/ (535, b'5.7.8 Username and Password not accepted settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_SSL = False views.py from django.contrib.auth.models import User def ViewSendEmail(request): send_mail('Hello from Bilal Khan', 'Hello there, This is an automated message.', request.user.email, #FROM ['bilalkhangood6@gmail.com'], #TO fail_silently=False) return render(request, 'nextone/email_send.html') -
Nested Serializer not showing up
I am trying to update my serializers in my drf project to be shown in a nested way. The two models in question are Image and Gallery, images are related to Galleries. I tried following https://www.django-rest-framework.org/api-guide/relations/#nested-relationships, but i am not entirely sure why it is not working. Below is models.py class Gallery(models.Model): title = models.CharField(max_length=30) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True, blank=True) modified_on = models.DateTimeField(auto_now=True, blank=True) def __str__(self): return self.title class Image(models.Model): gallery_id = models.ForeignKey(Gallery, on_delete=models.CASCADE) img = models.ImageField(upload_to='images/') created_on = models.DateTimeField(auto_now_add=True, blank=True) serializers.py class ImageSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Image fields = ["gallery_id", "img", "created_on", "id"] class GallerySerializer(serializers.HyperlinkedModelSerializer): image = ImageSerializer(many=True, read_only=True) def validate(self, data): # Check if user id is equal object id before creation or if SuperUser request = self.context.get("request") if request.user.id != data["author"].id and request.user.is_superuser is not True: raise ValidationError("Unauthorized User Post") return data class Meta: model = Gallery fields = ["title", "author", "created_on", "modified_on", "image", "id"] Expecting outcome would be [ { "title": "test_1", "author": "http://127.0.0.1:8000/api/users/2/", "created_on": "2019-08-19T09:13:45.107658Z", "modified_on": "2019-08-19T09:13:45.107731Z", "image": [ { "gallery_id": "http://127.0.0.1:8000/api/galleries/24/", "img": "http://127.0.0.1:8000/media/images/angga-tantama-background-art-minimalism.jpg", "created_on": "2019-08-20T09:17:31.790901Z", "id": 6 }, { "gallery_id": "http://127.0.0.1:8000/api/galleries/24/", "img": "http://127.0.0.1:8000/media/images/art-vector-background-illustration-minimalism-angga-tantam-2.jpg", "created_on": "2019-08-20T09:31:40.505035Z", "id": 7 } ] "id": 24 }, { "title": "test_2", "author": "http://127.0.0.1:8000/api/users/2/", "created_on": "2019-08-20T09:42:09.448974Z", "modified_on": … -
Inserting a record into a table's ManyToMany field while using multiple databases
My project uses Django's builtin multi-database support and I am trying to synchronize data in 2 different databases by taking a record from one database and inserting it into another one. I have tried to do this in the usual way using the add method of the RelatedManager, but it did not work and did not insert the record in the intermediary table in the second db, but rather did that in the default db. Here is how I did that: I have a Person model which has a ManyToMany field to Dbs model: ... class Person(models.Model): ... tenant_dbs = models.ManyToManyField(to=Dbs, blank=True) and Dbs model which contains a single column with the names of the databases a person can have access to: ... class Dbs(models.Model): person_id = models.CharField(primary_key=True, max_length=20 ) So I want to get some Person, Dbs and intermediary records from the default database and copy them all to another database (let's assume its name is 'secondary'). So I do the following: from core.models import Person from .models import Dbs # here I take the objects from default db as I did not mention any other # db manually and save them in the 'secondary' db. This works fine … -
Django, long filter query
I cant understand why it works like this, for example: Query1 Q( Q(groups__name=CONST_DEALER) & Q(additional_info__address__district=address.district) ) lead time: 2sec Query2 Q(Q(Q(groups__name=CONST_SELLER) | Q(groups__name=CONST_GROWER)) & Q(minor_user__major__additional_info__address__district=address.district) ) lead time: 2sec but when I unites them(i need to unites them) Q( Q( Q(groups__name=CONST_DEALER) & Q(additional_info__address__district=address.district) ) | Q( Q(Q(groups__name=CONST_SELLER) | Q(groups__name=CONST_GROWER)) & Q(minor_user__major__additional_info__address__district=address.district) ) ) lead time: 80sec!!!!!! tell me how to make a quick request -
Slugify not saving title as slug Django 2: NoReverseMatch error
Can't seem to get the slug field to save because I am getting the error NoReverseMatch. Reverse for 'blog_detail' with arguments '(5, '')' not found. 1 pattern(s) tried: ['blogpost/(?P<pk>[0-9]+)/(?P<slug>[^/]+)$'] Could someone look over my code please as I am having trouble finding the problem? urls.py path('blogpost/<int:pk>/<str:slug>', news_views.BlogPostDetailView.as_view(), name='blog_detail'), models.py class BlogPost(models.Model): title = models.CharField(max_length=190, null=True) slug = models.SlugField(max_length=190, editable=False, unique=True, blank=True, default='') def save(self, *args, **kwargs): self.slug = slugify(self.title, allow_unicode=True) super().save(*args, **kwargs) def get_absolute_url(self): kwargs = { 'pk': self.pk, 'slug': self.slug, } return reverse('blog_detail', kwargs=kwargs) views.py class BlogPostDetailView(DetailView): context = { 'blog': BlogPost.objects.all(), } model = BlogPost template_name = 'blog/blog_detail.html' slug_field = 'slug' slug_url_kwarg = 'slug' homepage.html <a href="{% url 'blog_detail' blog.pk blog.slug %}">{{ blog.title }}</a> -
How to filter against URL with foreign key field in Django REST, overwriting get_queryset method correctly
I am trying to filter my queryset against an url with django REST but can't really get it to work. I want to pass a string in the URL (a project name). According to this string, which is a foreign key, I want to filter my queryset (BuildingGroup). I don't want to use query params but a url filter. I followed the docs but there is not so much on it on the site. This is what I am trying: class ListBuildingGroupProject(ListAPIView): serializer_class = BuildingGroupSerializer filter_fields = 'project' def get_queryset(self): project = self.kwargs['project'] building_groups = BuildingGroup.objects.filter(project=project) result = building_groups.order_by('-creation_date') return result The line building_groups = BuildingGroup.objects.filter(project=project) throws me a KeyError for project. Here are my models. Note that BuildingGroup has one Project. A project can belong to many BuildingGroups. class BuildingGroup(models.Model): description = models.CharField(max_length=500, null=True, blank=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now=False) class Project(models.Model): project_name = models.CharField(max_length=120, primary_key=True, unique=True) start_date = models.DateTimeField(auto_now=False, null=True, blank=True) end_date = models.DateTimeField(auto_now=False, null=True, blank=True) and here my URL: path('project/<str:project_name>', ListBuildingGroupProject.as_view(), name='building-group-project'), Help is so much appreciated! Thanks in advance!