Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / Models / Admin / Problem with the foreign key : __str__ returned non-string (type tuple)
I have already tried multiple solutions find on other topics but nothing works. I have a problem the foreign key in Django Admin. Impossible to see a records or add a new record. I have a table convertion_factor with no NULL values. see postgreSQL config This is my model : class convertion_factor(models.Model): foodID = models.ForeignKey('food_name', on_delete=models.CASCADE) measureID = models.ForeignKey('measure_name', on_delete=models.CASCADE) conversionFactorValue = models.FloatField() convFactorDateOfEntry = models.DateField(auto_now=False, auto_now_add=False) In order to views the data in Django Admin, you have to add def __str__(self): to the model. Ok let's do that : class convertion_factor(models.Model): foodID = models.ForeignKey('food_name', on_delete=models.CASCADE) measureID = models.ForeignKey('measure_name', on_delete=models.CASCADE) conversionFactorValue = models.FloatField() convFactorDateOfEntry = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return self.conversionFactorValue Now when I go to Django Admin and I click on the model convertion_factor I can see the table just fine but when I try to click on a record to edit it, I have this error : TypeError at /admin/kalo/convertion_factor/19505/change/ Exception Type: TypeError at /admin/kalo/convertion_factor/19505/change/ Exception Value: __str__ returned non-string (type float) I have the impression this is an error due to the foreign key because with my others models without a foreign key, everythings work just fine. In the function def __str__(self): I have tried : return … -
XAMPP Error: Apache Shutdown unexpectedly error
I am first time using XAMPP Apache, when I click start, Apache shut down unexpectedly, and when I click on the error logs, it gives me all the log errors as shown in the picture below which I am not sure what to do, can anyone help me? Log error: Apache XAMPP Stop -
New users can't login sessions in Django
I have created a user registration form, when I try to register new user it brings back the same form while I redirected it to home page. And I try to log in, I get None, so it displays in the template 'Wrong username or password.'. However, the super user that I created through the command line after I first installed django, is able to login with no problem. views.py from .models import * from .forms import OrderForm, CustomerForm, CreateUserForm from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required def registerPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': form_value = CreateUserForm(request.POST) if form_value.is_valid(): form_value.save() user = form_value.cleaned_data.get('username') messages.success(request, 'Account was create for {}'.format(user)) return redirect('login') form_value = CreateUserForm context = {'form_key':form_value} return render(request, 'accounts/register.html', context) def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': username_value=request.POST.get('username') password_value=request.POST.get('password') user = authenticate(request, username=username_value, password=password_value) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username or Password is incorrect') context = {} return render(request, 'accounts/login.html', context) forms.py from django.db import models from django.forms import ModelForm, fields from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class … -
converting input value into negatives before saving
Please I have the model and the view below but I want a situation in which any value entered in the quantity field would be saved as a negative number in my database. views.py def post(self, request): receiveform = ReceiveForm(request.POST or None) stockform = StockForm(request.POST or None) if request.method == 'POST': if receiveform.is_valid() and stockform.is_valid(): receiveform.save() stockform.save() messages.success(request,('Data save succefully')) return redirect('dashboard') else: print(receiveform.errors) receiveform = ReceiveForm(request.POST or None) context = { 'receiveform':receiveform, 'stockform':stockform, } return render(request, 'storesapp/receives.html', context) models.py class Receives(models.Model): date = models.DateField(default=now) category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.IntegerField(default='0', blank=True, null=True) -
Error running WSGI application, within pythonanywhere
Good day to all, I was having some issues trying to host my django webapp within pythonanywhere and I keep getting the following errors within the server. Sorry in advance I'm a beginner when it comes to programming WSGI File: # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/HumBen/AMC_Inventory/venv/src/src/settings.py' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'src.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application stockmgmt = get_wsgi_application() ###### or, for older Django <=1.4 #import django.core.handlers.wsgi #application = django.core.handlers.wsgi.WSGIHandler() Server error: 2021-10-27 22:59:31,228: Error running WSGI application 2021-10-27 22:59:31,233: ModuleNotFoundError: No module named 'src' 2021-10-27 22:59:31,233: File "/var/www/humben_pythonanywhere_com_wsgi.py", line 16, in <module> 2021-10-27 22:59:31,233: application = get_wsgi_application() 2021-10-27 22:59:31,233: 2021-10-27 22:59:31,233: File "/home/HumBen/AMC_Inventory/venv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-10-27 22:59:31,233: django.setup(set_prefix=False) 2021-10-27 22:59:31,233: 2021-10-27 22:59:31,233: File "/home/HumBen/AMC_Inventory/venv/lib/python3.9/site-packages/django/__init__.py", line 19, in setup 2021-10-27 22:59:31,234: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-10-27 22:59:31,234: 2021-10-27 22:59:31,234: File "/home/HumBen/AMC_Inventory/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ 2021-10-27 22:59:31,234: self._setup(name) 2021-10-27 22:59:31,234: 2021-10-27 22:59:31,234: File "/home/HumBen/AMC_Inventory/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup 2021-10-27 22:59:31,235: self._wrapped = Settings(settings_module) 2021-10-27 22:59:31,235: 2021-10-27 … -
How to change Django model from class using boolean
I have the location class in my models.py class Location(models.Model): ... orderplaced = models.DateTimeField(auto_now_add=True, blank=True) ordersent = models.BooleanField(default=False) order_sent_time = models.DateTimeField(auto_now=True, blank=True) How do I make it so that the boolean ordersent controls the if order_sent_time is blank or not I tried using if ordersent: order_sent_time = models.DateTimeField(auto_now=True, blank=True) else: order_sent_time = models.DateTimeField(null=True, blank=True) How can I get the boolean to affect order_sent_time? -
Connect Heroku deployed MySQL database to Django
I want to make connection with my MySQL database which is deployed on Heroku. However, after setting parameters for database I am getting this error: django.db.utils.OperationalError: (1044, "Access denied for user '*mu username*'@'%' to database '*name of my database*'") In my settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*name of my database*', 'USER': '*my username*', 'PASSWORD': '*my password*', 'HOST': 'eu-cdbr-west-01.cleardb.com', 'PORT': '3306', } } -
Django - Communicate with persistent process
We have a legacy C library that can be used to communicate with a custom local server, and we have written command-line and GUIs tools with it. Now we would like to create a web interface using the library so users can just use the tools via a web browser instead of needing to install them locally. I have experience with Django, and this seems mostly plausible. However, there is one big hang up. In order for the C library to communicate with the local server, it must open up a per-instance connection for each user before transmitting data (and then closing the connection when the session is over). And to keep track of this session, it returns a void pointer that must be used for all library calls using this connection. And since it's a C void pointer, it's a pointer to a particular memory location in the process, and the session can only be used in the process it was created. This causes problems with Django because (as far as I know) I can't guarantee each request in different Django views for a session will be handled within the same process. One potential method for handling the problem … -
Why request,POST.get(var) is returning "NONE" value for radio input?
This is my code: a_selected = request.POST.get(q.text) it is returning "NONE" value I am using Django 3.0 -
how to store this data into a django session
so i have this code that stores favorite properties in to a database, how can i make that stores the properties into a session instead of using the database the json data of this view comes from a javascript that send data to the view when a (add)button is clicked views.py def updateFavoritos(request): response_json = request.body inmuebleId = None if response_json: data = json.loads(request.body) inmuebleId = data['id'] inmueble = Inmueble.objects.get(id=int(inmuebleId)) favorites, created = Favorito.objects.get_or_create(inmueble=inmueble) print('respuesta') favs = Favorito.objects.all() contexto = { 'id':inmuebleId, 'favoritos':favs, } return render(request, 'favorites.html', contexto) html code that show the favorite properties {% for favorito in favoritos %} <div class="col-lg-6 col-xl-4"> <div class="feat_property"> <div class="thumb"> <img class="img-whp" src="{{ favorito.inmueble.imagen.url }}" alt="fl1.jpg"> <div class="thmb_cntnt2"> <ul class="listing_gallery mb0"> <li class="list-inline-item"><a class="text-white" href="#"><span class="flaticon-photo-camera mr5"></span> 22</a></li> <li class="list-inline-item"><a class="text-white" href="#"><span class="flaticon-play-button mr5"></span> 3</a></li> </ul> </div> </div> <div class="details"> <div class="tc_content"> <h4><a href="page-listing-single-v8.html">{{ favorito.inmueble.nombre }}</a></h4> <p>251 SW 6th Ln Florida City, FL</p> <ul class="prop_details mb0"> <li class="list-inline-item"><a href="#"><span class="flaticon-bed"></span> <br>4 Cuartos</a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-bath"></span> <br>5 Baños</a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-car"></span> <br>1 Garage</a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-ruler"></span> <br>1200 M2</a></li> </ul> </div> <div class="fp_footer"> <ul class="fp_meta float-left mb0"> <li class="list-inline-item"> <a href="#"> <small><del class="body-color">$2,800/mo</del></small><br> <span class="heading-color fw600">$2,300/mo</span> </a> </li> </ul> <ul class="fp_meta … -
Best way to set a referral code in django across all URLs
I wonder what's the best way to set a session id across all URLs without changing URL patterns and views. Is this a good idea to create one URL located at the top in urls.py, set a session id in the view and redirect to the url without referral code? Let me give you an example: Setting a top-level url to catch any link with referral code urlpatterns = [ re_path(r'^(.*)/ref/<str:ref_code>/$', views.set_ref_code), path('', views.index, name='index'), path('news/', views.news_list, name='news_list'), Set referral code in the session and redirect to url without referral code def set_ref_code(request, ref_code): url = request.path redirect(url) I am not sure that this example works. This is only an example to explain my idea. Maybe there is a better solution to set referral id across all the web application? -
Django Rosetta TypeError at /en/rosetta/files/project/
I want to add rosetta to my project.I installed version 0.9.7 (tried 0.9.5) and added to INSTALLED_APPS 'rosetta'. I have error: TypeError at /en/rosetta/files/project/ expected str, bytes or os.PathLike object, not NoneType My urls.py from django.conf import settings from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = i18n_patterns( path('admin/', admin.site.urls), path('cart/', include('cart.urls', namespace='cart')), path('order/', include('order.urls', namespace='order')), path('social-auth/', include('social_django.urls', namespace='social')), path('rosetta/', include('rosetta.urls')), path('', include('shop.urls', namespace='shop')), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL) Python == 3.8.10 Django == 3.2.7 -
ACCOUNT_USERNAME_VALIDATORS not throwing error, or working as validation
I have a very weird bug, When I try to set the setting ACCOUNT_USERNAME_VALIDATORS in base.py (used for my dev,staging, and production environments) it doesn't actually do it. It's not even throwing an error if I incorrectly set the value. base.py This is for my dev environment ACCOUNT_USERNAME_VALIDATORS = ('accounts.validators.custom_username_validators') Validators.py I created a simple validation to see if it works with another validator provided by django. from django.contrib.auth.validators import ASCIIUsernameValidator custom_username_validators = [ASCIIUsernameValidator()] This is to show that the way I reference the validators code is correct. Tree . ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── Pipfile ├── Pipfile.lock ├── Procfile ├── README.md ├── accounts │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ ├── validators.py │ └── views.py ├── config │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings │ ├── settings1.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── docker-compose.yml ├── manage.py ├── pages │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── context_processors.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── posts │ … -
Enforcing permissions through a related model in Django Rest Framework
I'm working on building out permissions for an API built with Django REST Framework. Let's say I have the following models: from django.db import models class Study(models.Model): pass class Result(models.Model): study = models.ForeignKey(Study) value = models.IntegerField(null=False) I have basic serializers and views for both of these models. I'll be using per-object permissions to grant users access to one or more studies. I want users to only be able to view Results for a Study which they have permissions to. There are two ways I can think of to do this, and neither seem ideal: Keep per-object permissions on Results in sync with Study. This is just a non-starter since we want Study to always be the source of truth. Write a custom permissions class which checks permissions on the related Study when a user tries to access a Result. This actually isn't too bad, but I couldn't find examples of others doing it this way and it got me thinking that I may be thinking about this fundamentally wrong. Are there existing solutions for this out there? Or is a custom permissions class the way to go? If so, do you have examples of others who've implemented this way? -
Django filter by many-to-many field doesn't work
There is a model of Article and it has many-to-many categories field. I want to filter it by that field but it doesn't work as i expected. For example: MyModel.objects.filter(categories__id__in = [0, 1, 2]) it gets model with categories 0 and 1 even if it hasn't category with id 2. i tried something like this: MyModel.objects.filter(Q(categories__id = 0) & Q(categories__id = 1) & Q(categories__id = 2)) but it even doesn't work. it doesn't even gets model if it has all of this categories. By the way, i don't want to use more than 1 filter method So, is there any solution for me? Thanks. -
Rules in views for custom user types
in my app I created two types of users by one-to-one relations. class Teacher(models.Model): user = models.OneToOneField(AuthUser, primary_key=True, on_delete=models.CASCADE) ... class Student(models.Model): user = models.OneToOneField(AuthUser, primary_key=True, on_delete=models.CASCADE) ... in views now I'm checking user role as follows: student = Student.objects.get(pk=request.user.id) teacher = Teacher.objects.get(pk=request.user.id) but it throws an exception, which better way should I use it? -
Deploy django app with gunicorn and nginx. ERROR supervisor: child process was not spawned
I'm trying to deploy my django app in a digital ocean droplet. I'm using nginx and gunicorn following this tutorial This is how gunicorn_start looks like #!/bin/sh NAME="PlantArte" DIR=/home/paulauzca/PlantArte USER=paulauzca GROUP=paulauzca WORKERS=3 BIND=unix:/home/paulauzca/run/gunicorn.sock DJANGO_SETTINGS_MODULE=project.settings DJANGO_WSGI_MODULE=project.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME\ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- This is PlantArte.conf file #!/bin/sh [program:PlantArte] command=/home/paulauzca/bin/gunicorn_start --daemon user=paulauzca startsecs=0 autostart=true autorestart=true redirect_stderr=true environment=PYTHONPATH=$PYTHONPATH:/home/paulauzca/bin/python stdout_logfile=/home/paulauzca/logs/gunicorn-error.log Following the tutorial I run sudo supervisorctl status PlantArte And I always get PlantArte RUNNING pid 3566, uptime 0:00:00 With 0 second runtime. Which is weird. If I go into gunicorn-error.log I get supervisor: couldn't exec /home/paulauzca/bin/gunicorn_start: EACCES supervisor: child process was not spawned I've tried the "solutions" to this problem I've found on the internet but there is not much information about this... -
Django and SuspiciousFileOperation:Detected path traversal attempt
I find myself in an odd situation only when deployed (debug == false): My model throws a path traversal attempt exception. I want to create a directory for every file uploaded and save the file within the directory (some.zip) used in example. In my dev environment I have no problems and everything works just fine. models.py: class Template(models.Model): def get_folder(self, filename): filename_PATH = Path(filename) template_dir = filename_PATH.stem return Path(settings.TEMPLATES_FOLDER).joinpath(template_dir, filename) name = models.CharField("template", max_length=32, unique=True) file = models.FileField("templatefile", upload_to=get_folder, null=True, max_length=260, storage=OverwriteStorage()) class OverwriteStorage(FileSystemStorage): #this is actually above def get_available_name(self, name, max_length=None): self.delete(name) return name forms.py: class TemplateAdminForm(forms.ModelForm): def __init__(self,*args,**kwargs): super().__init__(*args, **kwargs) class Meta: model = Template fields = ["name", "file", ] def clean(self): cleaned_data = super().clean() upFile = Path(str(cleaned_data["file"])) if upFile.suffix == ".zip": path = self.instance.get_folder(cleaned_data["name"]) logging.error(f"{path}") unpack_zip(path) ## works! the directory is created/filled else: raise forms.ValidationError("unknown file type ...") logging.error("DONE!") # I see this output return cleaned_data ## signal to see when the error might be happening: @receiver(post_save, sender = Template) def testing(sender, **kwargs): logging.error("we never get here") settings.py: TEMPLATES_FOLDER = PATH(MEDIA_ROOT).joinpath("TEMPLATES") but: ERROR:django.security.SuspiciousFileOperation:Detected path traversal attempt in '/opt/project/media_root/TEMPLATES/some/some' WARNING:django.request:Bad Request: /admin/appName/template/add/ -
How to get categories in django
I have a django programme of diffrent categories of books and I want to get the books in a particular category. I can do this using django, but when using rest framework I get stuck at various points.I have the following blocks of code: models.py class Category (models.Model): name = models.CharField(max_length=20, db_index=True) slug = models.SlugField(max_length=40, unique=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name serializers.py class categories_serializer(serializers.ModelSerializer): class Meta: model = Category fields = "__all__" views.py class product_CategoryView(generics.ListCreateAPIView): serializer_class = categories_serializer def get_queryset(self): return { "categories": Category.objects.all() } ================ class Book(models.Model): categories = models.ManyToManyField(Category) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="book_owner") name = models.CharField(max_length=150) slug = models.SlugField(max_length=255, blank=True, null=True) product_class = models.CharField(max_length=50) image = models.ImageField(upload_to="images/books/") .... Whenever I try to access the category using path(book/category', views.book_CategoryView.as_view(), name="book_category"),, I encounter the following error: AttributeError at /book/category Got AttributeError when attempting to get a value for field `name` on serializer `categories_serializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'name'. I don't understand why I am getting the error. How do I go about this? -
http.client - ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
def checkUrl(url): p = urlparse(url) conn = http.client.HTTPConnection(p.netloc) conn.request('HEAD', p.path) resp = conn.getresponse() return resp.status < 400 all_urls = URL.objects.all() for u in all_urls: my_url = u.url result = checkUrl(my_url) print(result) There are 3090 urls in model "URL". It works but after object 2895, the error occurs: ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host How to fix it? -
Heroku Django - I need to run collectstatic for every change I make in development
I have successfully deployed my web app to heroku. Now I want to continue development on the local host I get from 'python manage.py runserver', but it doesn't reload the CSS until I do 'python manage.py collectstatic'. (I have tried F5 and Ctrl+F5). Before deployment it would automatically reload all css on refresh. Here is my settings.py file: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.2.7. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path import environ # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env() environ.Env.read_env() # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ '192.168.1.6', '127.0.0.1', 'mahmoudhamdyportfolio.herokuapp.com' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
Do I really need to accommodate both GET and POST request formats in a django form?
I'm new to django but something I don't understand is the need for accommodating both the GET and POST request types when developing a form. Please refer to code below from django docs: from .forms import NameForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'name.html', {'form': form}) The reason this confuses me is because I have developed a GET based form and it is working and I have no need for the POST portion above? See below: # views.py def simplifier_form(request): form = LabelForm() return render(request, "simplifier.html", {"form": form}) # forms.py class LabelForm(ModelForm): labels = forms.ModelChoiceField( queryset=Label.objects.all(), to_field_name='label_name', widget=forms.Select(attrs={'class': 'labels'}), ) class Meta: model = Label fields = ['labels'] -
Use IntegerChoices in model Meta class
I'm creating some constraints in my Meta class that reference an IntegerChoices enum. The issue I'm having is that I can't seem to figure out how to reference that IntegerChoices enum. class MyModel(models.Model): States = models.IntegerChoices('States', 'PROGRESSING INSTALLED DELETED') state = models.PositiveSmallIntegerField(choices=States.choices, help_text='Defines the cluster\'s current state') class Meta: constraints = [ models.CheckConstraint(check=models.Q(state__in=States), name='cluster_state_valid'), ] self.States isn't working, no self object. MyModel.States isn't working either since MyModel isn't fully instantiated at this point. Any advice/recommendation would be appreciated, thanks! -
how to link django signals and ajax
I am trying to implement a data collection system using iot devices. currently the data transmission is through an API using django REST framewokrs. That works excellent I would like to know some approach so that a trigger is generated when it receives data and these on the user's website are refreshed using ajax. maybe the use of signals but would not know how to bind that signal with ajax. I am somewhat newbie to javascript. some path should I follow? -
AttributeError: 'WSGIRequest' object has no attribute 'get' heroku
Am having a get request but it's failing on heroku with this error : AttributeError: 'WSGIRequest' object has no attribute 'get' I have failed to get the root cause of it Below is my view : class PostDetail(generics.GenericAPIView): """Blog post details""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly,) lookup_field = 'slug' def get_post_object(self, slug): post = get_blog_by_slug(slug) return post def get(self, request, slug): post = self.get_post_object(slug) if not post: return response.Response({ 'errors': _('Sorry, Blog post with the specified slug does' 'not exist') }, status=status.HTTP_404_NOT_FOUND) # track views of a viewed blog post. ip_address = get_ip_address(request) obj = CustomIPAddress.objects.create(address=ip_address) post.address_views.add(obj) serializer = self.serializer_class(post, context=request) return response.Response(serializer.data, status=status.HTTP_200_OK) Methods am calling above : def get_blog_by_slug(slug: str): """Get post by slug.""" try: obj = Post.objects.get(slug=slug) return obj except Post.DoesNotExist: return None def get_ip_address(request): """get ip address.""" try: client_ip, is_routable = get_client_ip(request) if client_ip is None: return uuid.uuid4() else: return client_ip except AttributeError: return uuid.uuid4() except: return uuid.uuid4() Am wondering why on local it's working but on heroku server am getting this error.