Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'redsquare.moduloMatriculas'" DJANGO
I'm trying to import a models.py file from moduloMatriculas in moduloFormaturas, however the error "ModuleNotFoundError: No module named 'redsquare.moduloMatriculas'" occurs redsquare means the name of the project, in the image it has a red square. Arquitetura Django import models -
Django custom user model meta overlaps when importing from another project
I'm remaking a script to sync data from an old python2 project to a new with python3. The way the last programmer made it work appears to be by importing both, the new and old models into a script in the old project using: sys.path.append("route to the new project") It works for importing every model except for a custom user model from the new project, when I try to work with it, like using UserProfile.objects.all() it crashes with: relation "user_userprofile" does not exist LINE 1: SELECT "user_userprofile"."id" FROM "user_userprofile" The right table is user_models_userprofile, because the app containing the model is "user_models" instead of "user". The app_label from the imported model shows "user", which is probably the default app_label when extending AbstractUser, it is probably ignoring the app_label attribute from my model and using the one from AbstractUser. Any ideas of how to make it work? Also sorry for my english. -
I need a better way to add a custom field to request.data | Django Rest Framework |
i usually put it in the initial def, but it give me errors when it try to get the api from the browser. what i usually use: def initial(self, request, *args, **kwargs): self.request.data['user'] = self.request.user super().initial(request, *args, **kwargs) the error i got: 'Request' object has no attribute 'accepted_renderer' -
Trying to install django to my virtual env
I am new to linunx and pipenv. I tried to install django on my new environment with "pipenv install django" and this happend: Installing django… Adding django to Pipfile's [packages]… ✔ Installation Succeeded Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… ✔ Success! Updated Pipfile.lock (4f9dd2)! Installing dependencies from Pipfile.lock (4f9dd2)… An error occurred while installing asgiref==3.2.5 --hash=sha256:3e4192eaec0758b99722f0b0666d5fbfaa713054d92e8de5b58ba84ec5ce696f --hash=sha256:c8f49dd3b42edcc51d09dd2eea8a92b3cfc987ff7e6486be734b4d0cbfd5d315! Will try again. An error occurred while installing django==3.0.4 --hash=sha256:50b781f6cbeb98f673aa76ed8e572a019a45e52bdd4ad09001072dfd91ab07c8 --hash=sha256:89e451bfbb815280b137e33e454ddd56481fdaa6334054e6e031041ee1eda360! Will try again. An error occurred while installing pytz==2019.3 --hash=sha256:1c557d7d0e871de1f5ccd5833f60fb2550652da6be2693c1e02300743d21500d --hash=sha256:b02c06db6cf09c12dd25137e563b31700d3b80fcc4ad23abb7a315f2789819be! Will try again. An error occurred while installing sqlparse==0.3.1 --hash=sha256:022fb9c87b524d1f7862b3037e541f68597a730a8843245c349fc93e1643dc4e --hash=sha256:e162203737712307dfe78860cc56c8da8a852ab2ee33750e33aeadf38d12c548! Will try again. 🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 4/4 — 00:00:00 Installing initially failed dependencies… ☤ ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 4/4 — 00:00:00 [pipenv.exceptions.InstallError]: File "/home/codrut/.local/lib/python3.7/site-packages/pipenv/cli/command.py", line 254, in install [pipenv.exceptions.InstallError]: editable_packages=state.installstate.editables, [pipenv.exceptions.InstallError]: File "/home/codrut/.local/lib/python3.7/site-packages/pipenv/core.py", line 1992, in do_install [pipenv.exceptions.InstallError]: skip_lock=skip_lock, [pipenv.exceptions.InstallError]: File "/home/codrut/.local/lib/python3.7/site-packages/pipenv/core.py", line 1253, in do_init [pipenv.exceptions.InstallError]: pypi_mirror=pypi_mirror, [pipenv.exceptions.InstallError]: File "/home/codrut/.local/lib/python3.7/site-packages/pipenv/core.py", line 862, in do_install_dependencies [pipenv.exceptions.InstallError]: _cleanup_procs(procs, False, failed_deps_queue, retry=False) [pipenv.exceptions.InstallError]: File "/home/codrut/.local/lib/python3.7/site-packages/pipenv/core.py", line 681, in _cleanup_procs [pipenv.exceptions.InstallError]: raise exceptions.InstallError(c.dep.name, extra=err_lines) [pipenv.exceptions.InstallError]: [] [pipenv.exceptions.InstallError]: ['Traceback (most recent call last):', ' File "/home/codrut/.local/share/virtualenvs/Django-B9r4LqTh/bin/pip", line 5, in <module>', ' from pip._internal.cli.main import main', "ModuleNotFoundError: No module named 'pip'"] ERROR: ERROR: Package installation failed... To mention that a few minutes ago I installed … -
A user can manually edit another user view from URL
I just noticed that a user can manually access another users update profile view by changing to the other users pk or username(as slug) in the URL. for instance http://127.0.0.1:8000/account/dashboard/18/updateprofile Lets say that is the users update profile url, if this user changes the pk to 19 and edit, the user with pk 19 profile will be edited, is this a bug or is this an error from my side? Thank you. -
Changed DB engine to MySQL. Now Django does not create tables
I have a Django app with a standard sqlite3 DB. Now I want to use MySQL. So I changed my DATABASES in settings.py, and it works well, but I can't run server because it says django.db.utils.InternalError: (1049, "Unknown database 'django'") So I created this DB in the client, and now it says django.db.utils.ProgrammingError: (1146, "Table 'django.Cat' doesn't exist") Seems like I have to create all tables by myself, which is the worst variant I can do. #settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '/path/to/db.conf', }, } } and #conf.db [client] database = django host = localhost user = DjangoUser password = password_you_cant_guess default-character-set = utf8 How to make Django create all tables I have? I even can't run python3 manage.py with any command because it gives my this exception. -
Send audio stream blobs data using sockets from javascript to pyhon django
Im trying to send real-time input microphone auido data from javascript to python django using websockets: function handleDataAvailable(event) { if (event.data && event.data.size > 0) { if (recordedBlobs.length >99){ recordedBlobs.shift() console.log(recordedBlobs) chatSocket.send(recordedBlobs); } recordedBlobs.push(event.data); } } const handleSuccess = function(stream) { recordedBlobs = []; mediaRecorder = new MediaRecorder(stream); //mediaRecorder.onstop = handleStop; mediaRecorder.ondataavailable = handleDataAvailable; mediaRecorder.start(10); // collect 10ms of data } navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(handleSuccess); And then in python i receive the data in the consumer.py: class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): print(text_data) How can i get the waveform of the audio received in python ? i can only get a string named 'blob' while printing text_data -
Django 3 multi-base not working when migrate
I use Django 3 with 3 apps: security, historian, bench. Each app has its own database. in the settings.py: DATABASE_ROUTERS = [ 'security.router.securityRouter', 'bench.router.benchRouter', 'historian.router.historianRouter', ] DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DB_DJANGO', 'HOST': 'LOCALHOST\\SQLEXPRESS', 'PORT': '1433', 'USER': 'user', 'PASSWORD': '******', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', } }, 'BdBench': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'BD_Bench', 'HOST': 'LOCALHOST\\SQLEXPRESS', 'PORT': '1433', 'USER': 'sa', 'PASSWORD': '5eCUr1tE', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', } }, 'BdBenchMeas': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'BD_Bench', 'HOST': 'LOCALHOST\\SQLEXPRESS', 'PORT': '1433', 'USER': 'user', 'PASSWORD': '******', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', } }, 'BdSecurity': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'BD_Security', 'HOST': 'LOCALHOST\\SQLEXPRESS', 'PORT': '1433', 'USER': 'user', 'PASSWORD': '******', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', } }, 'BdHistorian': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'BD_Historian', 'HOST': 'LOCALHOST\\SQLEXPRESS', 'PORT': '1433', 'USER': 'user', 'PASSWORD': '******', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', } }, } I use for each app: a router.py file: to security / router.py: class securityRouter(object): APPS = ['security', 'auth', 'sessions', 'contenttypes'] BD = 'BdSecurity' def db_for_read(self, model, **hints): if model._meta.app_label in self.APPS: return self.BD return None def db_for_write(self, model, **hints): if model._meta.app_label in self.APPS: return self.BD return None def allow_relation(self, obj1, … -
Django inlineformset_factory and ManyToManyField field, once again
first of all, sorry for my English! I have a little problem with "inlineformset_factory" and "ManyToManyField". Perhaps the option "inlineformset_factory" isn't the right choice. I have two classes, Prodotti and Categoria. In models.py are class Categoria(models.Model): ''' tabella delle Categorie dei prodotti ''' NomeCategoria = models.CharField(max_length=50,blank=True,null=True) class Prodotti(models.Model): ''' tabella Prodotti a catalogo ''' NomeProdotto = models.CharField(max_length=50,blank=True,null=True) CategoriaProdotto = models.ManyToManyField(Categoria, related_name='prodotti_categoria') I need a form to modify the name of a specific Categoria, es. Antiossidante, and eventually change the list of Prodotti that have this Categoria. I try a lot with "inlineformset_factory" and the use of "Prodotti.CategoriaProdotto.through" but I have problems with fields, only "id" is accepted. i.e. ProdottiFormset = inlineformset_factory(Categoria, Prodotti.CategoriaProdotto.through, fields=('id',)) But, changing the name of Categoria it isn't saved. This is my project: views.py def ModificaCategoria(request, pk): # recuperiamo la categoria da modificare, bisogna passare l'ID categoria = get_object_or_404(Categoria, pk=pk) ProdottiFormset = inlineformset_factory(Categoria, Prodotti.CategoriaProdotto.through, fields=('id',)) if request.method == "POST": form = CategoriaModelForm(request.POST, request.FILES, instance=categoria) formset = ProdottiFormset(request.POST, instance=categoria) if formset.is_valid(): formset.save() return render(request, "dopo_modifica_categoria.html") # return redirect(...) else: categoria = Categoria.objects.get(pk=pk) form = CategoriaModelForm(instance=categoria) formset = ProdottiFormset(instance=categoria) context = { "form": form, "formset": formset, } return render(request, "modifica_categoria.html", context) Template: {% extends 'base.html'%} {% block head_title %}{{ … -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet when loading wsgi.py
I have a problem with Django and wsgi that I cannot pinpoint. The app works fine on my local test server and it also works fine on a local apache WAMP setup (without any venvs). When deploying it to our Linux server again the local test server runs (as does makemigrations, migrate or check): python3 manage.py runserver /home/www-test/myapp-venv/lib/python3.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.8) or chardet (2.0.3) doesn't match a supported version! RequestsDependencyWarning) /home/www-test/myapp-venv/lib/python3.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.8) or chardet (2.0.3) doesn't match a supported version! RequestsDependencyWarning) Performing system checks... System check identified no issues (0 silenced). March 18, 2020 - 16:22:20 Django version 2.2.11, using settings 'myapp.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. python3 manage.py check /home/www-test/myapp-venv/lib/python3.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.8) or chardet (2.0.3) doesn't match a supported version! RequestsDependencyWarning) System check identified no issues (0 silenced). However when I try to deploy it with wsgi/Apache on the Linux machine I get Traceback (most recent call last): File "myapp/wsgi.py", line 20, in <module> application = get_wsgi_application() File "/home/www-test/.local/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/www-test/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/www-test/.local/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/www-test/.local/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.7/importlib/__init__.py", … -
Django - safely render HTML in template
I am building a django web application where the user can submit text via a tinymce editor. For that task I use the django-tinymce extension. The question: Is it secure to render the HTML in the template using the safe filter like so ? : {{ richtext | safe }} If not, how can it be made safe ? -
Whats the difference between models and models.Model in django?(and similarly for forms and forms.Form )
I know that "models" is a module of package django.db, But why we inherit like class Foo(models.Model): while the all required fields like CharField, IntegerField, etc. are part of models, what does the subclass Model do here exactly? I am new to OOP and Django so any resources and answers are heavily appreciated and welcomed. -
Django: failed to run gunicorn
I try to run gunicorn but it failed I have install gunicorn in my virtual env (pip install gunicorn) cd intensetbm_app/intensetbm-etool gunicorn intenseTBM_eTool.wsgi:application my project architecture: envs intensetbm_app | intensetbm-etool | | intenseTBM_eTool | | | wsgi.py | | | settings.py | | | ... | | manage.py | | ... intensetbm_static wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'intenseTBM_eTool.settings') application = get_wsgi_application() trace (partial): ... File "/home/test/intensetbm_app/intensetbm-etool/intenseTBM_eTool/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' [2020-03-18 15:00:20 +0000] [43251] [INFO] Worker exiting (pid: 43251) [2020-03-18 15:00:20 +0000] [43248] [INFO] Shutting down: Master [2020-03-18 15:00:20 +0000] [43248] [INFO] Reason: Worker failed to boot. -
No URL to redirect to
I am trying to create a page where these parameters can be filled by the user. This code allows the data to be stored in mysql but does not show the saved data. And shows "ImproperlyConfigured at /public/about/ No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model." MODELS class MedicalInfo(models.Model): BLOOD = ( ('A+', 'A+ Type'), ('B+', 'B+ Type'), ('AB+', 'AB+ Type'), ('O+', 'O+ Type'), ('A-', 'A- Type'), ('B-', 'B- Type'), ('AB-', 'AB- Type'), ('O-', 'O- Type'), ) @staticmethod def toBlood(key): for item in MedicalInfo.BLOOD: if item[0] == key: return item[1] return "None" patient = models.ForeignKey(User, on_delete=models.CASCADE, related_name="patiento") bloodType = models.CharField(max_length=10, choices=BLOOD) allergy = models.CharField(max_length=100) alzheimer = models.BooleanField() asthma = models.BooleanField() diabetes = models.BooleanField() stroke = models.BooleanField() comments = models.CharField(max_length=700) def __str__(self): return f'{self.user.username} Medinfo' def save(self): super().save() VIEWS.PY class MedinfoCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/public/medinfo.html' model = MedicalInfo fields = ['bloodType', 'allergy', 'alzheimer', 'asthma', 'diabetes', 'stroke', 'comments'] def form_valid(self, form): form.instance.patient = self.request.user return super().form_valid(form) HTML {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Medinfo </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> … -
is there any reason i cannot register and then login user in the same function using Angular and Django?
Using Angular and Django. When a user registers I want them to be automatically logged in and sent to their homepage. I have a registerUser function in my UserApiComponent that looks like: registerUser(){ this.userApiService.createuser(this.register).subscribe() this.user_cred = { username: this.register.username, password: this.register.password } console.log(this.user_cred) this.userauthcomponent.login(this.user_cred) } In my UserAuthComponent my login function is: login(user_cred){ this.authenticationService.login({'username': this.user_cred.username, 'password': this.user_cred.password}).subscribe( resp => { let response = resp; this.user_id = response.user_id this.router.navigateByUrl('/dashboard/'+this.user_id) }); } From my regular login page the login function works completely fine and I am able to login a user. From my registration page I am able to easily register a user. However, when I try to register AND login a user at one time so that the user does not have to login after registering I keep getting a bad request error: *core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "http://127.0.0.1:8000/users/api-token-auth/", ok: false, …} error: non_field_errors: ["Unable to log in with provided credentials."]* I know the credentials are correct because the console.log is outputting the correct info. I also tried just putting all the login logic inside of the registerUser function as follows: registerUser(){ this.userApiService.createuser(this.register).subscribe() this.user_cred = { username: this.register.username, password: this.register.password } this.authenticationService.login({'username': this.register.username, 'password': this.register.password}).subscribe( … -
Django: "django.contrib.gis.gdal.prototypes.ds" crashes with "attributeerror: symbol not found"
Running the latest Django (3.0.4) I am now getting this: File "[...]site-packages/django/contrib/gis/gdal/driver.py", line 5, in <module> from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi File "[...]site-packages/django/contrib/gis/gdal/prototypes/ds.py", line 71, in <module> get_field_as_integer64 = int64_output(lgdal.OGR_F_GetFieldAsInteger64, [c_void_p, c_int]) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ctypes/__init__.py", line 361, in __getattr__ func = self.__getitem__(name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ctypes/__init__.py", line 366, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: dlsym(0x101667060, OGR_F_GetFieldAsInteger64): symbol not found My Observations: I have [ellided] the path names which refer to Django in my virtual-environment. I observe that the module that is actually crashing is in /Library/Frameworks/Python.framework/ ... this on Macintosh OS/X Catalina. The version of Python that is installed on this computer is 3.6.4. (The version on the hosting service is considerably older ... 3.4.) Is this, as I suspect, a problem with the Python installation on this computer? (The most recent version that can be installed here is 3.7.7.) -
Django ForeignKey for multiple models with reverse relation
I'm currently working on a project where I have to assign values for certain instances while not affecting them. To give an example let's assume its a multi-service shop and we have a shopping cart where I have to put an Item order so I need ForeignKey to item ForeignKey to cart quantity the item but the item can be either product or service and cart can be a normal or special (two different models in both cases). I know how to achieve it but the thing that I couldn't obtain is the ability to call the item_order from for example product instance that its linked to. I'd be glad if anyone can either help me achieve the goal or show me another approach on the problem. Here is the exemplary code that hasn't given me the ability for revese access of item_order # https://docs.djangoproject.com/en/3.0/ref/contrib/contenttypes/#generic-relations class ValueBox(models.Model): class Meta: verbose_name_plural = 'ValueBoxes' # target is product or product group - can be later on expanded for future models item_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='target_content_type') item_id = models.PositiveIntegerField() item_object = fields.GenericForeignKey('target_type', 'target_id') # input is for example sales plan or brass plan its necessary to make it # flexible as there are … -
.NoReverseMatch: Reverse for 'author-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/author/(?P<pk>[0-9]+)$']
Many people have already ask similar question to this, but I still cannot figure out the solution unfortunately. I am doing a django tutorial from https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website . I compared my code with their's on Github but I do not see the difference. The current state of my code is here https://github.com/diveki/webdev/tree/master/django_projects/locallibrary it works well except for showing the details of the Author model. The error message I get is: django.urls.exceptions.NoReverseMatch: Reverse for 'author-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/author/(?P<pk>[0-9]+)$'] . I do not copy here all the code I wrote for this (unless you need it), but here is my models.py, urls.py from catalog, the relevant code from views.py and the templates: Part of my catalog/models.py: from django.db import models from django.urls import reverse # Used to generate URLs by reversing the URL patterns import uuid # Required for unique book instances class Author(models.Model): """Model representing an author.""" first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('died', null=True, blank=True) class Meta: ordering = ['last_name', 'first_name'] def get_absolute_url(self): """Returns the url to access a particular author instance.""" return reverse('author-detail', args=[str(self.id)]) def __str__(self): """String for representing the Model object.""" return '{0}, {1}'.format(self.last_name, self.first_name) catalog/urls.py: from … -
How to change multiple elements innerHTML using setinterval?
I'm working on certain app and I need to create kind of count down for each element. Unfortunately when I', passing the element to my function it does not work. Neverthless if I change the function a bit and just replace the element's innerHTML out of the setInterval it starts working. I'm totally out of any idea now. Appreciate for help :) const timeout is the element. const json_content = json_reader(reserved) for(x=0;x<json_content["key"].length;x++){ var tds = document.querySelectorAll(".display_content table td") for(let td of tds){ new Vue({ delimiters: ['[[', ']]'], el:td, data: { display: "test", seats_number: "0", }, methods:{ test(){ console.log("elo") } }, created: ()=>{ const td_date = td.innerText if(td_date.includes(json_content["key"][x])){ const td_hour = td.nextElementSibling const json_hour = json_content["value"][x]["times"] if(Object.keys(json_hour).includes(td_hour.innerText)){ const seats = json_content["value"][x]["times"][td_hour.innerText] const td_seat = td_hour.nextElementSibling const timeout = td_seat.nextElementSibling const seats_array = [] seats.forEach(element => { const seat_json = json_reader(element) seats_array.push(seat_json["key"]+":"+seat_json["value"]) }); this.seats_number = seats.length td_seat.innerHTML = "<span onclick='display_seats(this.nextSibling)'>"+[[this.seats_number]]+"</span>"+"<span class='seats' value='"+seats_array+"'></span>" counter(timeout) } } } }) } } and counter function: function counter(element){ var t = 10 setInterval(()=>{ element.innerHTML = String(t) t -= 1 },1000) -
Invalid block tag on line 66: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
Why is it giving me this strange error: Did you forget to register or load this tag? it was working fine but when i did some changes in this code it started this error... i was going through question related to this issue but could not find the solution.... <div class="container"> <div class="row"> <div class="pagination"> {% for item in post.object_list %} <!-- {% for item in post %}--> <div class="card my-3 text-white bg-dark mb-3" style="width: 18rem;"> <img src="/media/{{item.thumbnail}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.title}}</h5> <p class="card-text">{{item.intro}}</p> <!-- href={% url 'bicep' %}--> <a href="blog_detail/{{item.post_id}}" class="btn btn-primary">read more...</a> <!-- <a href="{% url 'blog_detail/pk' pk=item.post_id %}" class="btn btn-primary">read more...</a>--> </div> </div> {% if forloop.counter|divisibleby:4 %} </div> {% endif %} {% endfor %} -
Reset password after first successful login
I am building an web application using existing Auth features in Django where admin create user profile with username and password. Admin created user name and password will be given to user to login. So for security reasons I need to ask user to reset password (given by admin) after user's first successful login. To reset password, I will be displaying template where user should be entering only new password and new password again for confirmation. This new password will be updated in sqlite database. So whenever admin changes the users password. I need to ask users to reset password after first successful login. Here are the implementation I have done. models.py: Here I set boolean flag profile.force_password_change to TRUE when new user created. But profile.force_password_change is not setting to TRUE whenever existing user password changed or new user created. middleware.py: Whenever force_password_change set to TRUE, then I use middle-ware to redirect to change password view. I have written below code to set profile.force_password_change to TRUE whenever new user is created or user password is changed by admin. class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) force_password_change = models.BooleanField(default=False) def create_user_profile_signal(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) pass def password_change_signal(sender, instance, **kwargs): … -
django cache changed by the database status
I have viewset with cache like this on off by changing False -> True def maybe_decorate(condition, decorator): return decorator if condition else lambda x: x class TweetViewSet(viewsets.ModelViewSet): queryset = Tweet.objects.all().order_by('id') serializer_class = TweetSerializer filter_class = TweetFilter @method_decorator(cache_page(60*60*2)) @method_decorator(vary_on_cookie) @maybe_decorate(False,method_decorator(cache_page(60*60*2))) @maybe_decorate(False,method_decorator(vary_on_cookie)) Then now I have one idea. I can get the update time here SELECT UPDATE_TIME FROM information_schema.tables WHERE table_schema = DATABASE() and TABLE_NAME = 'tweet' I want to check this variable and switch on / off cache Is it possible?? or my idea is good practice?? -
DRF Serializer update method always has empty validated_data object when using PATCH + multipart/form-data
I've been banging my head about this one for a bit as I seem to be missing something obvious in this issue. First off, I have multiple parsers loaded for my DRF setup in settings.py: REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ), } Given the presence of the MultiPartParser I would presume that DRF should be parsing the body correctly. However in my ModelSerializer I am overriding the update handler to handle the files and attach them to the model, however all the fields are empty when I interate through them, even the basic ones like 'id' - however I know it must be interpreting the data, because the correct instance is loaded every time, in this case it's the user that is being updated. class UserSerializer(ModelSerializer): """ Serializer for the Logged in User """ avatar = VersatileImageFieldSerializer( sizes='member_avatar' ) background = VersatileImageFieldSerializer( sizes='member_background' ) class Meta: model = Member fields = ( 'id', 'email', 'username', 'language', 'bio', 'location', 'homepage', 'avatar', 'is_staff', 'groups', 'background', 'created', 'edited', 'last_login', 'slug', 'signature' ) read_only_fields = ['created', 'edited', 'slug'] def update(self, instance, validated_data): """ Update the user. :param instance: user instance :param validated_data: validated form data :return updated user """ updated_fields = … -
How can I create post?
This is my fist django project, so I have some problems to use form. I searched how to create post but I have problem. I don't know why posting is not work. Please help me... I want to save POST and Image FILE. views.py ` @login_required() def postFind(request): if request == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit = False) post.menu = True post.pub_date = timezone.datetime.now() post.up_date = timezone.datetime.now() post.user = request.user post.save() return HttpResponseRedirect(reverse('website:postCheck', args=(post.id))) else: form = PostForm() return render(request, 'postFind.html', {'form' : form}) ` postFind.html {% if user.is_authenticated %} <div class="form"> <form class="post-form" method="post" enctype="multipart/form-data" action="{% url 'website:postFind' %}"> {% csrf_token %} <div class="wrapper"> <div class="box"> <div class="js--image-preview"></div> <div class="upload-options"> <label> {{ form.image }} </label> </div> </div> <p id="info">Species</p> {{ form.species }} <p id="info">Location</p> {{ form.location }} <p id="info">Date</p> {{ form.date }} <p id="info">Feature</p> {{ form.feature }} <button type="submit" class="btn btn-default">Submit</button> <a class="btn btn-default" href="{% url 'website:homePost' %}" role="button" id="button">Cancel</a> </form> </div> {% endif %} form.py ` class PostForm(ModelForm): class Meta: model = Post fields = ['image', 'species', 'location', 'date', 'feature'] ` -
How can I use React.lazy with Django and Webpack 4?
I am building app with django on the backend and react on the frontend. I would like to use React.lazy, but I have some problems with Django, because it can not find other bundels except main.js which I have added to index.html template. This is my Webpack configuration: const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: __dirname + '/dist', filename: 'index_bundle.js' }, plugins: [ new HtmlWebpackPlugin() ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } }, { test: /\.css$/i, use: ['style-loader', 'css-loader'], }, { test: /\.(png|jpe?g|gif)$/i, use: [ { loader: 'file-loader', }, ], }, ] } }; Django view: def index(request): return render(request, 'frontend/index.html') index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="{% static 'frontend/favicon.ico' %}" type="image/x-icon"> <link href="https://fonts.googleapis.com/css?family=Oswald&display=swap" rel="stylesheet"> <title></title> <link rel="stylesheet" href="{% static 'frontend/bootstrap.min.css' %}" /> </head> <body> <div id="app"> <!-- React will load here --> </div> </body> <script src="{% static "frontend/main.js" %}"></script> </html> React app: class App extends Component { componentDidMount() { store.dispatch(loadUser()); } render() { return ( <Provider store={store}> <AppRouter /> </Provider> ); } } and AppRouter const AsyncHome = React.lazy(() => import(/* webpackChunkName: "Home" */ …