Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I got an Operational error after trying to register on a web i developed using django python
https://dpaste.com/BZ8VWDUTG OperationalError at /reg_form/ no such table: selection_user Request Method: POST Request URL: http://127.0.0.1:8000/reg_form/ Django Version: 3.1.2 Exception Type: OperationalError Exception Value: no such table: selection_user Exception Location: C:\Users\HP\Downloads\django implementation\Hostel-Management-System\venv\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute Python Executable: C:\Users\HP\Downloads\django implementation\Hostel-Management-System\venv\Scripts\python.exe Python Version: 3.7.7 Python Path: ['C:\Users\HP\Downloads\django ' 'implementation\Hostel-Management-System\hhms', 'C:\Users\HP\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\HP\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\HP\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\HP\AppData\Local\Programs\Python\Python37', 'C:\Users\HP\Downloads\django ' 'implementation\Hostel-Management-System\venv', 'C:\Users\HP\Downloads\django ' 'implementation\Hostel-Management-System\venv\lib\site-packages'] -
how to disappear html tags in django (safe tag not working properly)
I am making a blogging website like this I want to remove these tags (<p> <em>) which are being displayed in these cards page-html (before adding safe tag): <div class="container"> <div class="card-deck"> {% for post in top_posts %} <div class="card"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{post.title|truncatechars:14|safe}}</h5> <p class="card-text text-justify">{{post.content|truncatechars:190}}</p> <br> <p class="card-text"><small class="text-muted">{{post.timeStamp|timesince}}</small></p> <div> <a href="/blog/{{post.slug}}" class="btn btn-primary">ReadMore</a> </div> </div> </div> {% endfor %} </div> </div> page-html (after adding safe tag): <div class="container"> <div class="card-deck"> {% for post in top_posts %} <div class="card"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{post.title|truncatechars:14|safe}}</h5> <p class="card-text text-justify">{{post.content|truncatechars:190|safe}}</p> <br> <p class="card-text"><small class="text-muted">{{post.timeStamp|timesince}}</small></p> <div> <a href="/blog/{{post.slug}}" class="btn btn-primary">ReadMore</a> </div> </div> </div> {% endfor %} </div> </div> how page looks: help me to remove these italics and display the text in original cards style. -
Django's m2m_changed signal on User's groups is not triggered
I created an m2m_changed signal to automatically set is_staff attribute of users when they join/leave a specific group, but the signal is never fired. Here is the signal's definition : @receiver(m2m_changed, sender=User.groups.through) def moderator_group_is_staff(sender: Type[User], instance: Union[User, Group], action: str, reverse: bool, model: Union[Type[User], Type[Group]], pk_set: Set[int]): """Set `is_staff` attribute of users to `True` or `False` when they respectively join or leave the moderator's group.""" moderator_pk = Group.objects.get(name=settings.GROUPNAME_MODERATOR).pk # instance is User, pk_set is Groups' pk if not reverse and moderator_pk in pk_set: if action == "post_add": instance.is_staff = True if action == "post_remove" or action == "post_clear": instance.is_staff = False # instance is Group, pk_set is Users' pk elif reverse and instance.pk == moderator_pk: if action == "post_add": instance.user_set.update(is_staff=True) if action == "post_remove": User.objects.filter(id__in=pk_set).update(is_staff=False) if action == "pre_clear": instance.user_set.update(is_staff=False) I tried from django's admin interface and the manage.py shell, but the function was never called. Any idea ? -
Django all-auth allow users to login only if the user email address is verified
How do i override AllAuth default LoginView to allow users to login only if their email address is verified? -
I want to show JSON data in my Django template when Django's URL is roaded
I want to show JSON data in my Django template when Django's URL is roaded. My Django server structure is like polls(Django's parent app) has urls.py &views.py and templates has app has top.html. polls has app(Django's children app) has urls.py &views.py. I wrote urls.py of app from django.urls import path, include from . import views app_name = 'app' urlpatterns = [ path('index/', views.Top.as_view(), name='index'), ] views.py of app class Top(LoginRequiredMixin, TemplateView): template_name = 'app/top.html' login_url = '/login/' @csrf_exempt def index(request): if request.is_ajax: if request.method == 'POST': json_data = json.loads(request.body.decode("utf-8") dict['A'] = json_data[1]['A'] dict['B'] = json_data[1]['B'] else: dict = [] return render(request, 'app/top.html', dict) I wrote urls.py of polls urlpatterns = [ path('app/', include('app.urls')), path('admin/', admin.site.urls), ] I made test folder has test.html&test.js. I wrote test.html like <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script type="text/javascript" src="test.js"></script> </head> <body> <p>TEST</p> </body> </html> and test.js var info = [ { "A": "key", "B": "123, }, ]; const csrftoken = Cookies.get("csrftoken"); var xhr = new XMLHttpRequest(); var json = JSON.stringify(info); xhr.open("POST", "http://127.0.0.1:8000/app/index/"); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.send(json); I run Django server & opened test.html in Google browser.However Console of Google browser said POST http://127.0.0.1:8000/app/index/ 403 … -
Set up db_password for django and postgres in docker
I've a docker image with django 3.1 and postgresql. In the docker-compose.yml I wrote: version: '3' services: app: build: context: . ports: - "8001:8001" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8001" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=password depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=password In the Django app's settings.py I read the database password from the .txt file excluded from the .git ... DB_PASSWORD = '' with open('database_password.txt') as f: DB_PASSWORD = f.read().strip() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': DB_PASSWORD, } } ... What is the best practice to make Django and Docker securely read the same password from the same place? The most suitable information about this I found here: https://medium.com/swlh/setting-up-a-secure-django-project-repository-with-docker-and-django-environ-4af72ce037f0 The author offers to use the django-environ package for django. The docker part in this article descibed like this: If you specifed a different user and password in the DATABASE_URL variable in the .env file above, you should include them here (although this will compromise the security of the database, as the docker-compose.yml file will be committed to the repository). When it comes time to deploy the … -
How to create an image sitemap in Django
My model is the Station and the field holding the image url is the image I find difficulty on how to build my sitemaps.py file in order to be able to present also in sitemap.xml file the <image:loc> tag based on the image url. The source here : image sitemap just presents the xml format. I want to build a xml file like this based on the code written in sitemaps.py file. urls.py from .sitemaps import StationSitemap sitemaps = { 'station' : StationSitemap, } urlpatterns = [ path('sitemap.xml', sitemap, {'sitemaps': sitemaps}), ] sitemaps.py from django.contrib.sitemaps import Sitemap from stations.models import Station class StationSitemap(Sitemap): def items(self): return Station.objects.all() def location(self,item): return item -
I got an error name 'LOGIN_REDIRECT_URL' is not defined
I use django and when I put LOGIN_REDIRECT_URL in settings.py on the bottom, I got an error like this name 'LOGIN_REDIRECT_URL' is not defined What problems in my code? https://www.youtube.com/watch?v=3aVqWaLjqS4&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=7 I refer to this and I completely write same code. Please tell meeeeeeee! -
Django template loop many-to-many iteration query efficiency
Models: class ItemManager(models.Manager): def get_queryset(self): return super(AssetsManager, self).get_queryset().prefetch_related( models.Prefetch("assignments", queryset=Assignments.objects.select_related("userid"))) class Item(models.Model): objects = ItemManager() id = UnsignedAutoField(db_column='Id', primary_key=True) user = models.ManyToManyField('Owner', through='Assignments', through_fields=('itemid', 'userid')) @property def owner(self): return self.assignments.select_related("userid").last().userid class User(models.Model): id = UnsignedAutoField(db_column='Id', primary_key=True) item = models.ManyToManyField('Item', through='Assignments', through_fields=('userid', 'itemid')) class Assignments(models.Model): id = UnsignedAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') userid = models.ForeignKey('User', default=None, blank=True, null=True, on_delete=models.SET_DEFAULT) itemid = models.ForeignKey('Item', on_delete=models.SET_DEFAULT, related_name='assignments') In my template I am trying to iterate over the Item queryset while also displaying the owner. The problem is that a new SQL query will be made for every step of the loop. Template loop: {% if item_list %} {% for item in item_list %} {{item}} - {{item.owner}} {% endfor %} {% endif %} The view is a ListView where the queryset is "Item.objects.filter(Q(id__gte=1) & Q(id__lte=5))". The context_object_name is item_list. Using Django Debug Toolbar I notice the following: SELECT ••• FROM `Assignments` LEFT OUTER JOIN `User` ON (`Assignments`.`UserId` = `User`.`Id`) WHERE `Assignments`.`ItemId` IN (1, 3, 5, 2, 4) This query corresponds to {% if item_list %} Then a new query is made for every iteration: SELECT ••• FROM `Assignments` LEFT OUTER JOIN `User` ON (`Assignments`.`UserId` = `User`.`Id`) WHERE `Assignments`.`ItemId` = 1 ORDER BY `Assignments`.`id` DESC LIMIT 1 … -
Django REST endpoints for Watchlists feature
I wanted a system of multiple watchlists per user (upto 5) where users can add/remove products into individual watchlists. I have the following models is my models.py: class Product(models.Model): name = models.CharField(blank=False, null=False, unique=True, default=None, max_length=100) sku = models.CharField(blank=False, null=False, unique=True, default=None, max_length=100, verbose_name='Stock Keeping Unit') description = models.TextField(blank=True) price = models.FloatField(blank=True) class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) display_name = models.CharField(max_length=30) subscription = models.CharField(null=False, blank=False, choices=SubscriptionChoices.choices, default=SubscriptionChoices.SILVER, max_length=100) class Watchlist(models.Model): from .choices import WatchlistChoices profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product = models.ManyToManyField(Product) wl_num = models.CharField(null=False, blank=False, choices=WatchlistChoices.choices, default=WatchlistChoices.WL1, max_length=30) name = models.CharField(null=False, blank=False, max_length=20, default='NewWatchList') I have the following choices in a choices.py file: class WatchlistChoices(models.TextChoices): WL1 = 'WL1', _('Watchlist_1') WL2 = 'WL2', _('Watchlist_2') WL3 = 'WL3', _('Watchlist_3') WL4 = 'WL4', _('Watchlist_4') WL5 = 'WL5', _('Watchlist_5') I have put in the choices so that at any given time only the five predetermined watchlists can be used, hence limiting the number of watchlists per user to only 5. How can I build REST endpoints using DRF for the following tasks: Add/remove products into a specified watchlist Change the name of the watchlist Can this be done with class based views or does it need to be done with function based views? -
How to send request using a field in DjangoRestFramework UI
I am making a request from some external source, I am successfully able to make the request both manually and by passing the "ref_no" in my url, but I will like to have a way whereby I can put the "ref_no" in the DRF UI and make a post to the requested source and then get the data. I don't know if this is possible but I would be glad to get a way across this. views.py class Pay(APIView): def get(self, request, reference_id): url = f"https://api.paystack.co/transaction/verify/{reference_id}" payload = {} files = {} headers = { 'Authorization': 'Bearer SECRET_KEY', 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data= payload, files=files) return Response(response) urls.py from django.urls import path, include from .views import * urlpatterns = [ path('pay/<str:reference_id>', Pay.as_view(), name='pay'), ] -
I want to iterate a range of years using for loop in django
I want to display a set range of years using for loop with some start year to the current year and then after each passing years the current year will be that particular year. Example: start year is 2010 current year is 2020 It will display from year '2010' to '2020' So when 2021 comes the range will display from '2010' to '2021' my code is: import datetime def daterange(start, end, step=datetime.timedelta(1)): current_year = start while current_year < end: yield curr curr += step -
Not able to post the data in Django Restframework
I have added the experience details for the user using following models models.py class WorkExperienceData(BaseObjectModel): class Meta: db_table = 'workexperience' verbose_name = 'WorkExperience Data' user = models.ForeignKey(User, related_name="related_experience_detail", on_delete=models.PROTECT) company = models.CharField(max_length=500) designation = models.CharField(max_length=500) description = models.TextField(max_length=4000, default="") from_date = models.DateField(null=True) to_date = models.DateField(null=True, blank=True) reference_name_and_position = models.CharField(max_length=250) reference_mailid = models.EmailField(max_length=255, unique=True, db_index=True) My serializers are following Serializers.py class WorkExperienceSerialzer(BaseModelSerializer): hidden_fields_to_add = {"created_by": None, "user": None} def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(WorkExperienceSerialzer, self).__init__(many=many, *args, **kwargs) class Meta(BaseModelSerializer.Meta): model = WorkExperienceData fields = [ "company", "designation", "description", "from_date", "to_date", "reference_name", "reference_mailid", "user", "id", ] My views are following views.py class WorkExperienceListView(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): experience = WorkExperienceData.objects.all() serializer = WorkExperienceSerialzer(experience, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = WorkExperienceSerialzer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class WorkExperienceDetailsView(APIView): """ Retrieve, update or delete a snippet instance. """ def get_object(self, pk): try: return WorkExperienceData.objects.get(pk=pk) except WorkExperienceData.DoesNotExist: raise Http404 def get(self, request, pk, format=None): experience = self.get_object(pk) serializer = WorkExperienceSerialzer(experience, many=True) return Response(serializer.data) def put(self, request, pk, format=None): experience = self.get_object(pk) serializer = WorkExperienceSerialzer(experience, many=True, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def … -
How to get a better formatted JSON Response in DjangoRestFramework UI
I have an APIVIEW in DRF which I have written some views in it to get some Response, I would like to get a better formatted JSONResponse. Views.py class Pay(APIView): def get(self, request): url = "https://api.paystack.co/transaction/verify/262762380" payload = {} files = {} headers = { 'Authorization': 'Bearer SECRET_KEY', 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data= payload, files=files) return Response(response) This is a pictorial representation of the bad formatted JSONResponse I am getting which I would like to improve. Thanks -
How to import images from media_url to template.html in Django?
Well I am encountering a strange issue in my Django app. My app (in a loop) import an image into the media_url and then it goes to the next page and shows the image and goes back to first page. This was working very well yesterday. Today when I restart the server, the image goes to the media_url as before, but what I see in the next page is not what it is on the media_url and actually it is a picture that was imported before. here is the important part of the code: settings.py: MEDIA_ROOT = 'media//' # I test the MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media//' views.py: def scraping(request): .... template_name = "scraping.html" response2 = {'media_root': Config.MEDIA_ROOT, 'media_url': Config.MEDIA_URL} return render(request, template_name, response2) scraping.html <img src='{{media_url}}/pic.jpg//'> # I also tried {{media_url}}pic.jpg {{media_url}}/pic.jpg/ {{media_url}}//pic.jpg// ... It is surprisingly showing different images for each line Can you help me please? It seems that maybe! the media_url is not updating after each loop. I have no idea! -
how show favorite list in django
I have a list of favorites and I want to show them when I click on the interest button after I click on the list and my heart will be bold. The second part, ie filling the heart, is done correctly, but when I want to show the list, it does not show anything and gives the following error. Reverse for 'show_Book' not found. 'show_Book' is not a valid view function or pattern name. model.py class Book (models.Model): BookID= models.AutoField(primary_key=True) Titel=models.CharField(max_length=150 ) Author=models.ForeignKey('Author',on_delete=models.CASCADE) Publisher=models.ForeignKey('Publisher',on_delete=models.CASCADE) translator=models.ForeignKey('Translator',null='true',blank='true',on_delete=models.SET_NULL) favorit=models.ManyToManyField('orderapp.Customer',related_name='favorit', blank=True) view.py def show_Book(request,BookID): showBook=get_object_or_404(Book,BookID=BookID) is_favorite=False if showBook.favorit.filter(id=request.user.id).exists(): is_favorite=True return render (request , 'showBook.html', {'is_favorite':is_favorite,}) def favoritbook (request, BookID): showBook=get_object_or_404(Book,BookID=BookID) if showBook.favorit.filter(id=request.user.id).exists(): showBook.favorit.remove(request.user) else: showBook.favorit.add(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) def favoritlist(request): user=request.user favoritbooks=user.favorit.all() context={'favoritbooks':favoritbooks} return render (request,'favotritlist.html',context) url.py path('showbookstor/<int:id>', views.show_BookStor, name='show_BookStor'), path('books/favorit/<int:BookID>/', views.favoritbook, name='favoritbook'), path('books/favorit/', views.favoritlist, name='favoritlist'), showbook.html {% if is_favorite %} <li id="sell"><a href="{% url 'favoritbook' showBook.BookID %}">add to favorit <i class="fas fa-heart"></i></a> </li> {% else %} <li id="sell"><a href="{% url 'favoritbook' showBook.BookID %}"> delete favorit <i class="far fa-heart"></i></a> </li> {% endif %} favoritlist.html {% for Book in favoritbooks %} <section id="card" class="col-md-6 col-lg-3 col-sm-6 col-xs-12"> <a href="{% url 'show_Book' Book.BookID %}"><img src= {{Book.Image.url}}></a> <h1 id="bookname">{{Book.Titel}}</h1> <p>{{Book.Author}}</p> </section> {% endfor %} -
Django // How do I need to setup user data management?
I'm working on a pwa with django and I almost done all the front/backend and I'm now facing which might be the last part to put in place (I believe and hope so !) : User Data Management I already had a look at Django's documentation regarding user/group management and I think it is quite logical and understandable however I'm really stuck on how should I implement all of this according to my project ? And especially how should I manage user's data ? Today, the development part is already setup with models/data saving/editing. But there's no user dimension for now, everything created and stored in the database is "general" (I'm using SQLite3 mainly because it was easier to deal with for development and testing but I'm clearly not fixed to it and I can easily readapt parts of the code based on the chosen database and how it work, even more if other database are better adapted to what I am looking for). To give you a bit of context the application should allow anyone to create an account to access the app. When he user is logged on, he/she will be able to arrive on an interface with … -
Optimal Way to Add Dynamic Fields or Preload Initial Values for Django Models
So... I'm working on Django Project in which a question form will be presented to the user. The questions are all yes or no so it will be easy to do that on a database. NOT! for me at least. I've been scouring Google, Django Docs, et al. looking for an answer to this however the only answer I can think of is the one I will be presenting below. GOAL: Make a model class named EmployeeMedicalQuestions in which I will store all the responses sent by a user referencing a One-to-One Relationship with EmployeeProfile. PROBLEM: I have realized that to ask the same questions for all the users, I need to reinitialize the questions for each of them because of the One-to-One Relationship. With my novice experience in Django and Python, I really don't have any idea how to do this 'programmatically'. I also don't want to hard-code the questions (because they might change) as model.BooleanField() one-by-one because I'm too lazy to do that and defeats the purpose of 'dynamic' content. And it's boring. OPTIMAL SOLUTION: I have created a way to overcome this, though by programmatically creating multiple model.BooleanField() variables. Take a look at the code below: models.py … -
Is there any way to make a Cross Login authentication via external API from django view?
Is there any way to make a Cross Login authentication via external API from django view? I need to make request for login, then if this token exists, will be authenticated to the external API. I am googling for a very long time but could not find anything useful. Any help would be appreciated -
best free api for VIN decoder
try to find vin decoder but I did not find please Introduce one website that free and have document for VIN decoder thanks -
Django, don't localize datetimes in views
I'm having trouble understanding how timezones in Django works. Let's say I have a third party API that I get data from with a timestamp of: 2020-10-26 05:00:00 now, let's say that in my view I have a query that filters all of the records from Yesterday ( October 26th) if I have a user that looks at that endpoint in the states, he will see data from October 25th (because in his time zone he is still on the 26th) but I want him to see the data as if he was on the time zone of the original request so he can see this time stamp. -
Use nested dictionary as a datasource for Datatables
I'm new to JS and Django. I have a nested dict in python containing some data that I'd like display in Datatables in Django framework. The dict looks like: {'report': {'country': {'country1': {'POP Count': 15.0, 'POP Age': 2.0, 'Issues': 35.0}}, {'country2': {'POP Count': 16.0, 'POP Age': 1.0, 'Issues': 2.0}} {'city': {'city1': {'POP Count': 16.0, 'POP Age': 1.0, 'Issues': 4.06}}, {'city2': {'POP Count': 16.0, 'POP Age': 1.0, 'Issues': 3.099}} }}} The webpage has two datatables - per country and per city and I'm trying to use this dict above as the datasource in the following way: {{ report.country|json_script:"country_json" }} {{ report.city|json_script:"city_json" }} var country_json = JSON.parse(document.getElementById("country_json").textContent); var city_json = JSON.parse(document.getElementById("city_json").textContent); $('#CountryTable').DataTable({ "data": country_json, "column": [ { "data": "POP Count" }, { "data": "POP Age"} ] }) What I'm trying to achieve is for the Country Table to look like this: Country | POP Count | POP Age | Issues -------------------------------------- Country1| 15.0 | 2.0 | 35.0 Country2| 16.0 | 1.0 | 2.0 When I do this, the datatable goes wonky with all my leaf items merged as a string into a single column. I think the nested dictionary isn't being read properly. How do I get my nested dict get read … -
how to modify nested object field inside get_object
I have the following models: class Course(TranslatableModel): thumbnail = ResizedImageField(size=[342, 225], crop=['middle', 'center'], blank=True, null=True) # thumbnail = models.ImageField(blank=True, null=True) students = models.ManyToManyField(UserProfile, related_name='courses') created_by = models.ForeignKey(UserProfile, related_name='course_created', on_delete=models.CASCADE) languages = models.ManyToManyField(Language) categories = models.ManyToManyField(Category) default_language = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='def_language') price = models.FloatField(null=True, blank=True, default=0.0) user_group = models.ManyToManyField(UserGroup, related_name='courses', null=True, blank=True) date_creation = models.DateTimeField(auto_now_add=True, null=True, blank=True) translations = TranslatedFields( title=models.CharField(max_length=50, null=False), description=models.CharField(max_length=500, blank=True, null=True) ) and `class Module(TranslatableModel): thumbnail = models.ImageField(blank=True, null=True) course = models.ForeignKey(Course, related_name='modules', on_delete=models.CASCADE) avatar = models.ForeignKey(Avatar, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) evaluation = models.BooleanField(null=True) translations = TranslatedFields( title=models.CharField(max_length=50, null=False), description=models.CharField(max_length=500, blank=True, null=True) ) def __unicode__(self): return self.safe_translation_getter('title', str(self.pk))` the thing that i want to do is that when i do a get of a given course (example:website/api/courses/3) If the field of the module title is empty( means no translation was performed), instead of showing the empty field it returns the field with the original language. This is the code inside get_object: def get_object(self): """ Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ queryset = self.filter_queryset(self.get_queryset()) #print(queryset) # Perform the … -
I want to put data got in Django server into Elasticsearch
I want to put data got in Django server into Elasticsearch. Now I made application named app,I wrote codes in app/admin.py from django.contrib import admin from .models import User, Info class UserInfoAdmin(admin.ModelAdmin): list_display = ( '__str__', 'user', 'info', ) admin.site.register(User) admin.site.register(Info) in app/models.py from django.db import models from django.contrib.auth.models import User class User(models.Model): user_name = models.CharField(max_length=10) pass = models.CharField(max_length=20) class Info(models.Model): foreign_key = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name="foreign_key") adress = models.CharField(max_length=200) When I run Django server,username & password & adress info was saved in admin. I want to save these data Elasticsearch.I already installed elasticsearch-dsl-py,read README.(https://github.com/elastic/elasticsearch-dsl-py) However README has only Search Exaple and I cannot understand how to save data Elasticsearch via elasticsearch-dsl-py. Also should I write searching code of Elasticsearch in Search Example in app/models.py?Should I make another file in app directory? Please give me advices. -
DJANGO not receiving data with POST
I'm having an issue trying to send data with fetch to DJANGO. I want to send some data to django through fetch but when I debug I receive nothing in the post value, do you know what could be happening? This is my fetch call: const defaults = { 'method': 'POST', 'credentials': 'include', 'headers': new Headers({ 'X-CSRFToken': csrf_token, 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }), data:{'name':'A name'}, dataType:'json' } const response = await fetch (url, defaults) When I debug I get an empty querydict in the request.POST What am I doing wrong?