Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Strange TyperError put() missing 1 required positional argument: 'path'
I've been trying to test my PUT method in the following APITestcase: def test_story_delete(self): c = APIRequestFactory user = User.objects.get(username='test1') payload = {'storyName': 'changetest'} request = c.put(reverse('storyFunctions',args=[self.room.pk,self.story.pk]), format='json') force_authenticate(request,user=user) My URL: path('room/<int:pk>/story/<int:idStory>/adm', APIHstory.as_view(),name='storyFunctions'), And I'm keep receiving this error: TypeError: put() missing 1 required positional argument: 'path' I don't understand what is going on because i declared the path inside request. Can someone help me? -
How Do I Render Form Attributes Manually in Django?
I am trying to render the name attribute manually. {% for language in form.languages %} <div class="form-check"> <input class="form-check-input" id="{{ language.id_for_label }}" name="{{ language.field.name }}" type="checkbox"> <label class="form-check-label" for="{{ language.id_for_label }}">{{ language.choice_label }}</label> </div> {% endfor %} Everything gets rendered nicely except the name attribute of the input tag. form.languages is a ManyToManyField shown on my form as a ModelMultipleChoiceField using the following code in my forms.py. languages = forms.ModelMultipleChoiceField( queryset=Language.objects.all(), widget=forms.CheckboxSelectMultiple ) -
Creating an image field in Django Python, 2022
I'm learning programming (beginner level), and am currently working on a web app project in Python/Django. I would like to add an image field to my models, but the tutorials I find don't seem to work. Does anyone have simple, comprehensive steps to do it? I have run into the following problems: Conflicting PIL vs Pillow imports (I have deleted the PIL imports for now; I have Pillow installed, but not sure if I need to do anything else with it?) When I try to make a migration I get: 'NameError: name 'os' is not defined', which relates to my settings.py file, and which I'm not sure how to resolve. Thank you! -
How to add result from one query into another in Django
I am working on a page that passes trough some parameters. I hava a Projekt modell and a Projekt_szd_by_date model joined in a query. I like to do that to get data from another joined model (stressz_elegedettseg). The last is the model which I like to get data but it gives me this error: TypeError at /mpa/project_details/by_date/szd-bydate-szervezetielegedettseg/1/1/2022-02-02-2022-05-02 hasattr(): attribute name must be string The Projekt_sz_by_date modell contains a from_date and a to_date that I like to pass trough like this: http://localhost:8000/mpa/project_details/by_date/szd-bydate-szervezetielegedettseg/1/1/2022-02-02-2022-05-02 urls.py path('project_details/by_date/szd-bydate-szervezetielegedettseg/<int:projekt_id>/<int:projekt_bydate_id>/<slug:from_date>-<slug:to_date>', views.szd_by_date_szervezetielegedettseg, name='szd_by_date_szervezetielegedettseg'), views.py def szd_by_date_szervezetielegedettseg(request, projekt_id, projekt_bydate_id, from_date, to_date): projekt = Projekt.objects.raw('SELECT projekt_id, id FROM stressz_profile WHERE stressz_profile.projekt_id=%s', [projekt_id]) from_date = Projekt_szd_by_date.objects.raw('SELECT date_from AS from_date, id FROM stressz_projekt_szd_by_date WHERE stressz_projekt_szd_by_date.id = %s', [projekt_bydate_id]) to_date = Projekt_szd_by_date.objects.raw('SELECT date_to AS to_date, id FROM stressz_projekt_szd_by_date WHERE stressz_projekt_szd_by_date.id = %s', [projekt_bydate_id]) projekt_by_date = Projekt_szd_by_date.objects.raw('SELECT * FROM stressz_projekt_szd_by_date INNER JOIN stressz_projekt ON stressz_projekt.id = stressz_projekt_szd_by_date.id INNER JOIN stressz_elegedettseg WHERE stressz_elegedettseg.date BETWEEN "%s" AND "%s" AND stressz_projekt_szd_by_date.id=%s', [from_date], [to_date], [projekt_bydate_id]) context = { 'projekt': projekt, 'projekt_by_date': projekt_by_date, 'from_date': from_date, 'to_date': to_date, } return render(request, 'stressz/szd-bydate-szervezetielegedettseg.html', context) models.py class Projekt_szd_by_date(models.Model): def __str__(self): return str(self.projekt_szd) projekt_szd = models.CharField(max_length=250) projekt_parent = models.ForeignKey('Projekt', on_delete=models.CASCADE) company_name = models.ForeignKey('Company', on_delete=models.CASCADE) jogosult_01 = models.ForeignKey(User, on_delete=models.CASCADE) date_from = models.DateField(editable=True) date_to = … -
iOS can't play uploaded audio: JS MediaRecorder -> Blob -> Django Server -> AWS s3 -> JS decodeAudioData --> "EncodingError: Decoding Failed"
I am using Javascript MediaRecorder, Django, AWS s3 and Javascript Web Audio API to record audio files for users to share voice notes with one another. I've seen disbursed answers online about how to record and upload audio data and the issues with Safari/iOS but thought this could be a thread to bring it together and confront some of these issues. Javascript: mediaRecorder = new MediaRecorder(stream); mediaRecorder.onstop = function (e) { var blob = new Blob( chunks, { type:"audio/mp3", } ); var formdata = new FormData(); formdata.append('recording', blob) var resp = await fetch(url, { // Your POST endpoint method: 'POST', mode: 'same-origin', headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrf_token, }, body: formdata, }) } Django: for k,file in request.FILES.items(): sub_path = "recordings/audio.mp3" meta_data = {"ContentType":"audio/mp3"} s3.upload_fileobj(file, S3_BUCKET_NAME, sub_path,ExtraArgs=meta_data) ###then some code to save the s3 URL to my database for future retrieval Javascript: var audio_context = new AudioContext(); document.addEventListener("#play-audio","click", function(e) { var url = "https://docplat-bucket.s3.eu-west-3.amazonaws.com/recordings/audio.mp3" var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; request.onload = function () { audio_context.decodeAudioData(request.response, function (buffer) { playSound(buffer) }); } request.send(); }) Results in: "EncodingError: Decoding Failed" Note however that using the w3 schools demo mp3 url does play the recording: … -
How can i request for a class attribute extending the User Class in django
I always get this Error DoesNotExist at /file/new/1 StaffUser matching query does not exist. My models.py class StaffUser(User): department = models.ForeignKey(Dept, on_delete=models.RESTRICT) My Views.py def FileUploadForm(request, pk): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) folder = Folder.objects.get(id=pk) if form.is_valid(): form.save(commit=False) u = StaffUser.objects.get(username=request.user) form.instance.fileuser = u form.instance.folder = folder form.instance.department = u.department form.save() messages.success(request, f'File Successfully uploaded to {folder}!') return redirect('home') else: form = UploadFileForm() return render(request, "pages/fileup_form.html", {'form': form, 'pk':pk}) I want to get the department of the user and add to the database -
DRF: nested Serializer error on create argument after ** must be a mapping, not str
I have a model that connects a school model and a user model through a foreign key, and on creating if a student is being created I want the user foreign key to be set as the instance and also a school to be chosen by its id however i can't solve this error TypeError at /api/users/student_register/ django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() argument after ** must be a mapping, not str class User(AbstractBaseUser, PermissionsMixin): .... email = models.EmailField( is_superuser = models.BooleanField(default=False) last_login = models.DateTimeField( _("last login"), auto_now=True, auto_now_add=False) class School(models.Model): PROVINCE = ( ... ) SCHOOLTYPE = ( .... ) name = models.CharField(_("Name"), max_length=150, blank=False, null=True) abbr = models.CharField( _("Abbrivation"), max_length=10, blank=False, null=True) zone = models.CharField( _("Zone"), max_length=50, choices=PROVINCE) Schooltype = models.CharField( _("School type"), max_length=50, choices=SCHOOLTYPE) schoolemail = models.EmailField( _("School email"), max_length=254, blank=False, null=True) editable=False) def __str__(self): return self.name this applied model is what is connecting the user and the student model together and it is what i am using though the nested serializer to create the users class Applied(models.Model): class TYPES(models.TextChoices): STUDENT = "STUDENT", "Student" WORKER = "WORKER", "Worker" type = models.CharField(_("type"), choices=TYPES.choices, max_length=150, blank=False, null=True) user = models.ForeignKey(User, verbose_name=_( "useris"), related_name='useris', on_delete=models.PROTECT, blank=True, null=True) school = models.ForeignKey(School, verbose_name=_( 'school'), related_name="applied", on_delete=models.CASCADE, blank=True, … -
if condition is not working in django post request
I'm check null values from the request but creating record on null after put the condition in views you can check my code. if request.method == 'POST': category_id = request.POST['category_id '] text1 = request.POST['text1'] text2 = request.POST['text2'] text3 = request.POST['text3'] product = Product(category_id=category_id, text=text1) product.save() if text2 is not None: product = Product(category_id=category_id, text=text2) product.save() if text3 is not None: product = Product(category_id=category_id, text=text3) product.save() The text2 and text3 I'm sending null but creating in the database I'm not understanding why these are creating. Thanks -
Django - passing one model to another by pk in link
I'm making a site by using django. It has multiple tests with multiple questions each. I'd like to make question creation form which will have preset question depended on url. it's better explained in comment in views.py That's what I have already done; models class Test(models.Model): name = models.CharField(max_length=200) #questions = models.ManyToManyField(Question) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) def get_questions(self): return self.question_set.all() def __str__(self): return self.name class Question(models.Model): text = models.CharField(max_length=200, null=True) test = models.ForeignKey(Test, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add = True) def __str__(self): return self.text urls urlpatterns = [ path('', views.home, name='home'), path('test/<str:pk>/', views.test), path('test/<str:pk>/question-create/', views.QuestionCreateView, name='question-create'), ] forms from django import forms from django.forms import ModelForm from .models import Question, class QuestionCreationForm(ModelForm): class Meta: model = Question fields = '__all__' /// all except test which is set by pk in url views def QuestionCreateView(request, pk): form = QuestionCreationForm() if request.method == 'POST': test = Test.objects.get(id=pk) /// I would like to pass it to models to disallow user to choose to which test will question belong, i mean test should pe preset by <pk> in link form = QuestionCreationForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'exam/question_form.html', context) -
I have to determine if model has more than 4 objects or less
If Model has more than 4 than everything works fine. but if there is less than 4 .count() returns 0 posts_num = Post.objects.filter(author__id= self.kwargs["pk"]).count() print(posts_num) if posts_num >= 4: page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date')[:4] else: page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date')[:posts_num] current_user = self.request.user.id context["page_author_post"] = page_author_post -
How to add bootstrap scripts to django admin template?
I want to use some **Boostrap** elements into the **django admin** interface. For that purpose, I have overided the *admin/base.html* template. I want to add the links to bootstrap javascripts (the two lines of code you have to put just before the `` in order to use bootstrap) into that template. As it is out of any `{% block %}` in the original *admin/base.html*, is there a nice way to do that without copying the entire section ? -
Django makemessages : Unexpected translations
Two of my friends and I are using django makemessages to translate our website. When they use it on their PC, everything goes well. However, when I run the command python manage.py makemessages on my PC, it works but many lines in the .po file change when they should not. We all use PyCharm, django 3.1.6 and have the same configurations. I have tried to reinstall them all several times to no avail. I don't understand why makemessages is different on my PC compared to theirs. Some examples : The lines below are added to my django.po file while it concerns variables : #: .\site\views_ajax.py:181 msgid "landfill_hydric_state__name" msgstr "" #: .\site\views_ajax.py:199 msgid "landfill_quality__name" msgstr "" Lines containing a '%' are all modified : "Choice of geology for the \"%(parameter_name)s\" parameter<br>of the " "\"%(study_name)s\" study" Becomes : "Choice of geology for the \"%(parameter_name)s\" parameter<br>of the \"%" "(study_name)s\" study" The line specifying the language moves : "Language: es\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "X-Generator: Poedit 2.4.1\n" Becomes : "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: es\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "X-Generator: Poedit 2.4.1\n" An unexpected fuzzy appears on a word that is never … -
Add dynamic data in a demo chart.js file of a django template
I'm using the "start bootstrap4" template for my Django project. I want to edit my own data in the sample chart. I need to change it in the chart-pie-demo.js file I used gspread and pandas to convert my google sheet into a list of dictionaries. My google sheet is shown as the following list: (It's a very long list, so I only list a few lines) mylist= [{'StartDate': '2021-10-02', 'ID': 11773, 'Name': Mike, 'Days':66 }, {'StartDate': '2021-10-03', 'ID': 15673, 'Name': Jane, 'Days':65}, {'StartDate': '2021-10-03', 'ID': 95453, 'Name': Jane, 'Days':65}, {'StartDate': '2021-10-03', 'ID': 15673, 'Name': Mike, 'Days':65}, ... {'StartDate': '2021-10-5', 'ID': 34653, 'Name': Jack, 'Days':63}] The above list is defined in my views.py My chart-pie-demo.js file: var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Direct", "Referral", "Social"], datasets: [{ data: [55, 30, 15], backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'], hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], }, options: { maintainAspectRatio: false, tooltips: { backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, yPadding: 15, displayColors: false, caretPadding: 10, }, legend: { display: false }, cutoutPercentage: 80, }, }); I want to count the number of rows that has "Mike" in name, the … -
Django DateField ordering logic in case of equal DateField values
I'm trying to understand what is the ordering logic of django of DateField in case the dates are equal? I've got a model that has a DateField and DateTimeField (irrelevant fields taken out). class Ad(models.Model): title = models.CharField(max_length=50) content = models.TextField() created_at = models.DateField(default=timezone.now) created_time = models.DateTimeField(default=timezone.now) The ordering for the model is as such: class Meta: ordering = ['-created_time', '-created_at'] Note that previously I didnt have the created_time = models.DateTimeField(default=timezone.now) at all and sorted only via -created_at. I added the additional DateTimeField just for testing purposes and it didnt affect the outcome of the DateField ordering in any way. Here you can see the order how the objects were created in DB: And this is the order how the objects are actually ordered on the ListView page: The slug field in DB can be used as reference in order to understand which object in the template corresponds to which object in the DB. As you can see the first DateTimeField order works as expected, however the ordering by DateField is not the same as the order in the DB. What is more interesting that if I will go to my UpdateView and update the "Summernote" objects content (not messing … -
Internal server error when deployed django project to heroku
I am getting a Internal service error after I had uploaded my project and deployed using heroku . I have tried a lot of times to upload it and it is not working and I don't know why it is so . I am a beginner in django. Please help me . this is my build log after the project was deployed -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the same version as the last build: python-3.9.10 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.9.10 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory '/tmp/build_4274e684/static' in the STATICFILES_DIRS setting does not exist. 128 static files copied to '/tmp/build_4274e684/staticfiles', 20 unmodified. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 90.4M -----> Launching... Released v12 https://blogging-site-dev.herokuapp.com/ deployed to Heroku this is my setttings.py """ Django settings for bloggingsite project. Generated by 'django-admin startproject' using Django 3.2.2. … -
How to view message created when API request submited in admin view django
I want messages to be shown when a POST method is called (from another source). How can I do that using the messages framework django? I tried using templates and calling the view from the api view but nothing works. I can only log the messages but not view them because I dont have the proper "request". Is there a way to view messages when there is no request specified? Should I maybe use django.shortcuts render? My admin view that handles form: (admin.py) class AdminView(admin.ModelAdmin) [...] And API view that handles the request: (views/api.py) def create(self, request, pk=None): json_data = json.loads(request.body) if json_data['status'] == 201: messages.warning(request ,"test message") return Response(json_data['body'], status = status.HTTP_201_CREATED) So when another source calls POST method (i'm sure it works. The only thing that does not is the messages), I want the admin view to show the message. urls: url(r'^invoices/(?P<pk>[0-9]+)/$', views.InvoiceDetail.as_view(), name='invoice-detail'), base.html: {% block messages %} {% if messages %} <ul class="messagelist">{% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li> {% endfor %}</ul> {% endif %} {% endblock messages %} Messages are set just like it is said in https://docs.djangoproject.com/en/4.0/ref/contrib/messages/#module-django.contrib.messages And they work, because I have also … -
Django why getting MultiValueDictKeyError?
here is my code: if request.method == "POST": forms = GoogleAuthFroms(request.POST or None) if forms.is_valid(): code = request.POST["auth_code"] context = { 'forms':forms, } return render(request,'members/security.html',context) This line of code code = request.POST["auth_code"] throwing this error MultiValueDictKeyError at /security/ 'auth_code' -
django_filters recursive filtering
so I have a django filter that looks like this: class ModelFilter(FilterSet): user_name = CharFilter(method="some_method") boss = ModelChoiceFilter(...) My model looks simillar to this: class Employee(Model): username = Charfield(...) boss = ForeignKey("self", ''') So an employee can be the boss of another employee. Now, this filter will return the correct queryset based on what values the user is searching for. Let's say we have three objects: O1= Employee(usename="u1", boss=None) O2= Employee(usename="u2", boss=O1) O3= Employee(usename="u3", boss=O2) If I apply the above mentioned filter on this data, and search for boss=O1 I will get the Object O2 as a result. I want to add a new boolean field in the filter, let's say "with_subordinates", that will return the whole "tree" relationship if it is true. So for instance if I would search for: boss=O1, with_subordinates=True, the resulte should be O2 and O3. Basically, with this new option, the filter should recursively show the employees, of previous employees and so forth. Is there a way to achieve something like this? -
Blocking access to html page while user edits
I have a Django web app for booking golf competition times for members. Once logged in, all users have ability to edit player names for each time. These are then manually reset for the following week after the competition. The issue is if more than 1 user edits at the same time, it will save last instance and others will not realize. I have the list of times, (with 4 name slots each), on one html page with an edit button for each time, which leads to a separate html page for editing those 4 names. Is there anyway of blocking a html page once opened by 1 user? Or a thought I had was to create a button next to "Edit", which changes color and text, (green to red, and "Open" to "Edit in progress" for example), for a set period or until "save" button clicked on update page. Here is the relevant code- Models.py class Post(models.Model): time=models.CharField(max_length=50) player1=models.CharField(max_length=50, default="Player 1") player2=models.CharField(max_length=50, default="Player 2") player3=models.CharField(max_length=50, default="Player 3") player4=models.CharField(max_length=50, default="Player 4") def __str__(self): return self.time Views.py def teetimes(request): posts=Post.objects.all() name=CompNames.objects.get(id=1) return render(request, 'memtees/teetimes.html', {'posts':posts, 'name':name}) def add(request): if request.method=='POST': time=request.POST['time'] player1=request.POST['player1'] player2=request.POST['player2'] player3=request.POST['player3'] player4=request.POST['player4'] Post.objects.create(time=time,player1=player1,player2=player2,player3=player3,player4=player4) messages.success(request,'New Time has been added') … -
how to convert string into RSA privatekey python
i'm building a django social media app, and i'm trying to achieve end-to-end encryption, by using rsa keys. when a user signs up an RSA publickey/privatekey is generated then the private key is symmetrically encrypted and stored in the database. the problem with this when i retrieve the private key it's type is str, which the module rsa can't read. the original type when it was generated was rsa.key.PrivateKey here is a snippet from models.py: class Post(models.Model): privatekey = models.BinaryField() publickey = models.BinaryField() and the signup view: def register(request): if request.method == 'POST': form = UserRegister(request.POST) ver = verification(request.POST) if form.is_valid() and ver.is_valid(): form.username = request.POST.get('username') form.password1 = request.POST.get('password1') form.password2 = request.POST.get('password2') try: form.save() except: messages.warning(request, f'there is an error') return render(request, 'users/register.html', {"form": form}) username = form.cleaned_data.get('username') new_user = authenticate(username=form.cleaned_data['username'],password=form.cleaned_data['password1'],) login(request, new_user) publickey, privatekey = rsa.newkeys(2048) profile = request.user.profile profile.publickey = publickey password = request.POST.get('password1') profile.privatekey = encryption_decryption(str(privatekey), password, 'e') profile.save() response = redirect('complete-profile') privkey = encryption_decryption(request.user.profile.privatekey, password, 'd') response.set_cookie('key', privkey, max_age=None) return response else: form = UserRegister() ver = verification() return render(request, 'users/register.html', {"form": form, 'ver': ver,}) the type problem is in th encryption_decryption function, it's responsible for encryptingthe private key and restoring it (decrypting it) when the … -
Best way to pass the logged in user to the backend in Django
I'm new to Django and I've correctly created a login/register and my account page. Now my problem is that no matter which user is logged in when it goes to my account page, the URL will also be ./account Is there a way to pass which user is requesting the page and change the URL according to it but always pointing to the same template? For instance, if the user logged in has username john clicking on my account it redirects to ./account/john but shows the same template. Basically I would like that the URLs reflect the user logged in Currently, I manage the My account page as below. navbar.html {% if user.is_authenticated %} <li class=""> <a href="{% url 'account' %}"> <i class='bx bxs-user-detail icon' ></i> <span class="text nav-text">My profile</span> </a> </li> urls.py from django.urls import path, include from . import views urlpatterns = [ path('account', views.account_user, name="account"), ] -
How to improve Django REST response processing time?
In a Django/DRF project, I am trying to improve the performance of an API endpoint that takes in a JSON file and creates model objects in the database from it. This JSON can be very large, spamming hundreds or thousands of entries. The view is using DRF's ViewSet class as the base. I wrote a unit test with a fixture with around 800+ entries (so 800+ model objects) to investigate potential bottlenecks in the flow. By timing a few steps that I thought would be critical I found this: 1) Time to create: 37.771371603012085 2) Time to check objects errors: 52.56421709060669 3) Time to create response: 0.499253511428833 4) Time Django processing response: 81.24804949760437 Time taken: 172.08289170265198 I can't use bulk_create because of multi-table inheritance This is calling full_clean() on each object Serialization of objects is irrelevant After my function return Response(...), all this time is spent on Django's backend How can I improve step 4? I don't understand what takes so long to process the response and spit it back out. -
django web site URLS gets "?next=" randomly after deployed to heroku
after deploying django app on heroku the url after every form submittion or link in site been press resulting with "?next=" inserts into the URL address, i dont understand from where it comes and why heroku keep inserting them in a random way, running the application localy just working perfectly. i've deleted the application from heroku and upload it again, the fault persists. there's no http errors what so ever. if i keep submiting the form eventually will works. for example: pressing the log button in the django admin console results with this URL: https://appname.herokuapp.com/admin/login/?next=/admin/login/admin/, hitting it quite a bit will finnaly make it work with the correct url display: https://mishnayot.herokuapp.com/admin/. switching from heroku postgres to AWS RDS postgres didn't help. help will be very appreciated. -
how to add manytomany fields to filter search in django
I have written a search API for my website in django rest framework. It's an API in which you can set some parameters in the url and get a search result. what I need is to be able to search by genre. What it means is I need the API to be able to do a search like /api/search/?search=1&search_fields=filmGenre. but write now if I send a request to this url I get a FieldKey error with the following message: Related Field got invalid lookup: icontains here is my code: # models.py class Film(models.Model): filmID = models.AutoField(primary_key=True) title = models.CharField(max_length=150) duration = models.PositiveIntegerField() typeOf = models.IntegerField(validators=[MaxValueValidator(3), MinValueValidator(1),]) rating = models.FloatField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),]) releaseDate = models.DateTimeField(null=True) filmGenre = models.ManyToManyField(Genre) class Genre(models.Model): genreID = models.AutoField(primary_key=True) nameOf = models.CharField(max_length=100, unique=True) # serializers.py class FilmSerializer(serializers.ModelSerializer): class GenreFilmSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('nameOf', 'genreID',) read_only_fields = ('nameOf', 'genreID',) class CelebrityFilmSerializer(serializers.ModelSerializer): class Meta: model = Celebrity fields = ('nameOf', 'celebID',) read_only_fields = ('nameOf', 'celebID',) filmGenre = GenreFilmSerializer(read_only=True, many=True) filmActor = CelebrityFilmSerializer(read_only=True, many=True) filmDirector = CelebrityFilmSerializer(read_only=True, many=True) class Meta: model = Film fields = [ "filmID", "title", "price", "duration", "typeOf", "numberOfFilminoRatings", "filminoRating", "rating", "releaseDate", "detailsEn", "salePercentage", "saleExpiration", "posterURL", "posterDirectory", 'filmGenre', 'filmActor', 'filmDirector' ] # views.py … -
Encrypt Django project
I have a project (django) running in our office in server. There are some people who have access in server. But I want to do something so that other people (who have access in server) can not read, or write, or edit, or do anything in my project (django)'s source code. Server is running using Ubuntu OS.