Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use ListField in django models.py while using DJONGO as engine in settings.py
my json data seems like this {"Batch Year":1998-1999,"Roll Nos":["36","125"],"Student Names":["xyz","xxy"],"Project Name":"IMPLEMENTATIONOF NETWORK SECURITY BY VIRTUAL PRIVATE NETWORK (VPN)","Project Supervisor":"abc","External Supervisor":"aaa","Co-Supervisor":"None","Project Id":155} for this data i defined ListFields in models.py for Roll Nos and Student Names but when i was using admin panel to add data im my database i am facing error "Exception Value: A Formless Field cannot be modified from Django Admin." please help me to solve this error. Thanks in advance i am using django 2.2 djongo as Engine settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'fypcis_db', } models.py from future import unicode_literals from djongo import models import djongo Create your models here. class students(models.Model): batch_year = models.IntegerField(db_column='Batch Year') # Field name made lowercase. roll_nos = djongo.models.ListField(db_column='Roll Nos',default=True) # Field name made lowercase. student_name = djongo.models.ListField(db_column='Student Names',default=True) # Field name made lowercase. project_name = models.CharField(max_length=250, db_column='Project Name',default=True) # Field name made lowercase. project_supervisor = models.CharField(max_length=250, db_column='Project Supervisor',default=True) # Field name made lowercase. external_supervisor = models.CharField(max_length=250,db_column='External Supervisor',default=True) # Field name made lowercase. co_supervisor = models.CharField(max_length=250,db_column='Co-Supervisor',default=True) # Field name made lowercase. project_id = models.IntegerField(db_column='Project Id') # Field name made lowercase. -
Retrieve data from django-rest to show in a form
I have two classes linked with a ForeignKey. My first class is "Categories", with "ID" and "Name" properties. The second class is "Documents", with "ID", "Title" and "User" properties, the last one is linked with a category defined in the first class. I'm developing the front-end based on Vue, so I want to know how to retrieve data from django-rest to show it in a form. For example, when a user adds a new doc, he must choose between all category options. Note that categories will be common to all documents. Example: Categories = [{"ID": 0, "Name "Sports"}, {"ID": 1, "Name": "Music"}] Form to add a new document: Title: XXXX Category: Sports, Music models.py from django.db import models class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) class Documents(models.Model): id = models.AutoField(primary_key=True) title= models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) -
Django No module named 'static_root'
I am trying to create a local bootstrap file for rendering a website using Django. When setting up the static files directory, I modified the settings and now I keep getting the error "ModuleNotFoundError: No module named 'static_root'" If I try to comment out the static_url or staticfiles_dirs declarations, the error doesn't go away. The settings.py file looks as follows: settings.py: """ Django settings for static_root project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'a7d*homo^rqx96v5z0^m_ppb%w=wn^ap52p^v5*e(dp-)bheft' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'static_root', 'app.apps.AppConfig', 'nested_admin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = 'static_root.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', … -
Does load balancing make sense on a single hardware server?
This might be a case of not actually understanding how load balancing works, but bear with me... I'm currently in the process of designing a web app, and have a single hardware server available to me. Most of the architectures I've come across use Nginx as a load balancer in front of multiple servers (with Nginx proxying to the different ports). My question is this: I'd quite like to use Docker to containerise Nginx and a few instances of the Django application I'm going to be running (as well as the database), but is it worth having multiple instances of an application running on a single hardware server? The server can run a few instances of the Django app on different ports, but surely load balancing is about distributing the stress across hardware, in which case there would be no point? I think a part of the confusion is the fact that 'server' can mean either hardware or software. It would be really great if someone with a better understanding could clear this up for me! Many thanks -
Advice on site development (combine static HTML files already coded with Django project)
I would like some advice on what to do on this project and clarify some ideas. I am unclear how the set of static HTML web-pages I developed (previously to starting development on Django) can be combined with the Django project. I assume templates are relevant, is it possible to pass coded HTML into template?. or can a urls be mapped simply to static HTML pages(?stored within the Django project). For the site I'm developing, At the start I coded some pages in plain HTML,CSS and Javascript. These are static, I have not used a content management system. These are stored in Folder-A in subfolders : Content,Styles,Scripts,Images. - Then for backend I chose Django, and now added another folder called Webapp to folder-A. Reading through DJango tutorials I've made a project for website within webapp, intending to have a separate app for a comments section, an app for a feedback form, and an app for a contact-to-email form. Have done the initial configuration and Installed MySql. It seems the database is hooked up to the Djgano project now. I can access first view I made + admin site after using runserver command. From what I have understood so far, the … -
how to post django form with javascript edit element?
I create a page with text inside a element: <form id='myform' action="save/" method="POST"> <td id='test'>test</td> <td><input type="text" size="20" id="test2" name="test2"></td> </form> and I change this element by javascript function: <script language="javascript"> function edit() { var x= document.getElementById('test'); x.innerHTML='<input type="text" name="test1" id="test1" value="test">'; } </script> now I submit current form with post method, I get value test2 is OK: print(request.POST['test2']) but when I get value test1 (javascript generate new input element), it show Exception : print(request.POST['test1']) MultiValueDictKeyError at /~/save/ 'test1' Request Method: POST Django Version: 2.0.5 Exception Type: MultiValueDictKeyError Exception Value:'test1' can anyone helps me? very thanks! -
PATCH method in django-rest returns 400 BAD REQUEST
I've been trying to setup my API to handle PATCH requests, but I keep getting the 400 BAD REQUEST response. I can't seem to figure out what I need to change in order for it to work. The get method is working the way it's supposed to, but the PATCH is evading me. serializers.py class HeroCounterSerializer(serializers.ModelSerializer): class Meta: model = HeroCounters fields = ('ct1', 'ct2', 'score', 'pk') views.py class HeroCounterViewSet(viewsets.ModelViewSet): queryset = HeroCounters.objects.all() serializer_class = HeroCounterSerializer @detail_route(methods=['GET', 'PATCH']) def counter_list(self, request, pk=None): if request.method == 'GET': # retrieve an object by pk provided hero = Hero.objects.get(pk=pk) herocounters = HeroCounters.objects.filter(ct1=hero).distinct().order_by('score')[:10] herocounters_json = HeroCounterSerializer(herocounters, many=True) return Response(herocounters_json.data) elif request.method == 'PATCH': instance = HeroCounters.objects.get(pk=pk) request.data['HeroCounters'] = HeroCounters.id # pass in the instance we want to update serializer = HeroCounterSerializer(instance, data=request.data) # validate and update if serializer.is_valid(): serializer.save() serializer_dict = serializer.data serializer_dict["message"] = "Settings updated successfully." return Response(serializer_dict, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Iterate inside template of json.dumps(), preformated tags in template
I have finally successfully listed as a "tree" nested JSON response, rendered via template. But at cost. I can't iterate through ids and values (context passed to template) in template. As for non nested JSON responses, i can iterate in template and manupulate any id and value i want. but when i try to do this with nested JSON response (JSON inside JSON), can't do anything. Non-nested JSON scenario code and effect: views.py def about(request, host_id): hostname = Host.objects.get(pk=(host_id)) response = requests.get( 'https://{}:1769/api/v1/about'.format(hostname), verify='cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxx'}, ).json() context = {'response': response, 'hostname': hostname} return render(request, 'itpassed/json.html',context) json.html [...] {% if response %} {% for id, value in response.items %} <p><b>{{ id }}:</b> <br> {{ value }}</p> {% endfor %} {% else %} <p>No IDs are available.</p> {% endif %} [...] effect in browser: version: 3.4 level: system: unix server_time: 1560423771000 server_utc: 2 Nestes JSON scenario code and effect: views.py def transfers(request, host_id): hostname = Host.objects.get(pk=(host_id)) response = requests.get( 'https://{}:1769//api/v1/transfers?fields=PART%2CDIRECT%2CTYPE[...]&limit=100'.format(hostname), verify='cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxx'}, ).json() response = json.dumps(response, indent=3) context = {'response': response, 'hostname': hostname} return render(request, 'itpassed/json_nest.html', context) json_nest.html [...] {% if response %} <pre>{{ response }}</pre> {% else %} <p>No IDs are available.</p> {% … -
Site displays broken images and missing data if added more cities (OpenWeatherMap API)
I'm following PrettyPrinted video tutorial of creating a Weather App using Django. I am sure I followed all the steps but I kept getting problems when displaying more than one city. https://github.com/RomeoEncinares/Weather I've tried doing it all over again but arrive at the same problem. views.py code import requests from django.shortcuts import render from .models import City def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&APPID=b98fdc7ba13c80b36da38711c2100544' city = 'London' cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city' : city.name, 'temperature' : r['main']['temp'], 'description' : r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } weather_data.append(city_weather) print(weather_data) context = {'weather_data' : city_weather} return render(request, 'weather/weather.html', context) Models.py code from django.db import models class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' Admin.py code from django.contrib import admin from .models import City admin.site.register(City) html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.css" /> </head> <body> <section class="hero is-primary"> <div class="hero-body"> <div class="container"> <h1 class="title"> What's the weather like? </h1> </div> </div> </section> <section class="section"> <div class="container"> <div class="columns"> <div class="column is-offset-4 is-4"> <form method="POST"> <div class="field has-addons"> <div class="control is-expanded"> <input class="input" type="text" placeholder="City Name"> </div> … -
How does `parent` field in this model change when we comment and reply, please explain it?
I am reading some codes and I have difficult time understanding Comment.objects.filter(parent=self), codes below: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() parent = models.ForeignKey('self', null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return f'[{self.user}] commented on [{self.object_id}]' @property def children(self): return Comment.objects.filter(parent=self) This is a comment, reply app. This is my understanding about this, please correct me if I am wrong. children property are replies of comments in Django app. Practically, if I actually comment on a post like this is a nice post, the parent field in this model will be equal to this instance of comment, namely this is a nice post, and if someone reply to this comment as thank you for comment, then again that parent would be changed with this instance of comment. I am pretty confused. Can you elaborate it further please thank you ? -
How to use reverse url within app to point to a template of a different app?
I have two apps: simulation_api and building_data. Each one has templates and urls. The urls I import in my main configuration. In my template of simulation_api I would like to set a link to my detail view of building data. This is what I am trying (in my template of simulation_api) which throws me an error (django.urls.exceptions.NoReverseMatch): {% for item in simulations.project.buildinggroup_set.all %} <a href="{% url "detail_building_group" item.id %}">{{ item.description }}</a> {% endfor%} The for loop works, the problem is the url that I am trying to reverse. I am reversing it like this in my models of building_data: class BuildingGroup(models.Model): name = models.CharField(max_length=500, null=True, blank=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) def get_absolute_url(self): return reverse("detail_building_group", kwargs={"id" : self.id}) I think the problem is somehow that I reverse the url in one app but it is not recognised in the template of the other app. But maybe it's also something else... Anyone has an idea? Thanks so much in advance! Very much appreciated! Not sure if it is useful, but here my simplified model for the simulation: class Simulation(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) my urls of building_data app_name = 'buildings' urlpatterns = [ path('list/building-group/<int:id>/', DetailBuildingGroupView.as_view(), name="detail_building_group"), ] -
Combination of swup, scrollmagic and fancybox result in a non-functional fancybox gallery, has anyone experienced that please?
this is my first question on stackoverflow, hopefully somebody can help. I'm building a django powered website and can't seem to get my fancybox gallery to work properly when swup is enabled(handles page transitions), or at least I suspect that that's related. My setup: django with photologue images parallax headers handeled by scrollmagic page transitions handeled by swup Problem: clicking a thumbnail opens the image fullscreen with no fancybox controlls, however, for a fraction of a second before the image is displayed and while its being loaded, the fancybox controls/arrows/x are there. But the result after click is a fullscreen image without navigation, the url also now points to that image with /.jpg which i think is the url generated by photologue. Most strange now: cligking a thumbnail, clicking the back button, then clicking the thumbnail again and again clicking the back button results in the image opened in a fancybox overlay as expected! :( What I've tried: - If i move the jQuery declaration in base.html to the end, fancybox works but my parallax and nabar links stop working. - if I disable swup or scrollmagic, fancybox works fine - different versions of fancybox seem to have the same … -
problem downloading product form django template
Am having two models product and order ,If a product is downloadable and is ordered user can be able to download it in user profile, am stuck here can anyone help. product model class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) name = models.CharField(max_length=120) description = models.CharField(max_length=500,null=True,blank=True) download = models.FileField(upload_to=download_loc,storage=FileSystemStorage(location=protected_loc),null=True,blank=True) price = models.DecimalField(max_digits=60,decimal_places=2) sale_price = models.DecimalField(max_digits=60,decimal_places=2,null=True,blank=True) slug= models.SlugField() def __str__(self): return self.name and the order model class Order(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) date_ordered = models.DateTimeField(auto_now=True) def get_cart_items(self): return self.items.all() def get_cart_total(self): return sum([item.product.price for item in self.items.all()]) def __str__(self): return '{0} - {1}'.format(self.owner, self.ref_code) am trying to pass the download part from product mode if the order it contains the product to download it should be downloaded to user profile. userprofile views.py def check_product(user,product): if product in user.profile.ebooks.all(): return True else: return False def my_profile(request): my_user_profile = Profile.objects.filter(user=request.user).first() my_orders = Order.objects.filter(is_ordered=True, owner=my_user_profile) product = Product.objects.filter(download=True) if product: downloadable = check_product(request.user,product) context = { 'my_orders': my_orders, 'product':product, #'downloadable':downloadable } return render(request, "profile.html", context) and the profile template {% for order in my_orders %} <tr> <td>{{ order.date_ordered }}</td> <td>{{ order.ref_code }}</td> <td> {% for item in order.items.all %} {{ item.product.name }} {% endfor %} </td> … -
How to exit the function to make a list consisting of links to apartments?
It is necessary to refine the kufar_parser function (task.py file), to which a link to the kufar.by API and parameters to be passed to the get request is passed (the link and basic parameters are defined in main.py). The output of this function should be a list consisting of links to apartments (links in str).I can not understand how to display a list of links to apartments at the output of the function main.py from task import kufar_parser def get_params(**kwargs) -> dict: '''Returns the parameters by which the website is looking for ads.''' params = { 'cat': 1010, 'cur': 'USD', 'gbx': 'b:27.479209899902344,53.829230976746196,27.699966430664066,53.9764838398327', 'cmp': 0, 'prc': f'r:150,300', 'size': "300", 'sort': 'lst.d', 'typ': 'let', 'oph': 1 } for param in kwargs: if param in params: params[param] = kwargs[param] return params def get_api_url() -> str: '''Returns the link by which the frontend accesses the site for ads.''' return "https://re.kufar.by/api/search/ads-search/v1/engine/v1/search/raw" if __name__ == '__main__': params = get_params() api_url = get_api_url() links = kufar_parser(api_url, params) print(links) task.py import requests def kufar_parser(api_url: str, params: dict) -> list: api_url = "https://re.kufar.by/api/search/ads-search/v1/engine/v1/search/raw" params = { 'cat': 1010, 'cur': 'USD', 'gbx': 'b:27.479209899902344,53.829230976746196,27.699966430664066,53.9764838398327', 'cmp': 0, 'prc': f'r:150,300', 'size': "300", 'sort': 'lst.d', 'typ': 'let', 'oph': 1 } res = requests.get(api_url, params=params) … -
PostgreSQL explain datetime timezone conversion
I'm saving to db DateTime like: 2019-02-25T11:30:26+03:00 Then in DB it looks like this: 2019-02-25 08:30:26.000000 +00:00 Converted to UTC. OK. And then, when I want to get this DateTime back in local time I have to .annotate(check_time_local=Trunc('check_time', 'second', tzinfo=timezone('Etc/GMT+3'))) which will be converted to a query like: DATE_TRUNC('second', "table"."dt_field" AT TIME ZONE '-03') AS "check_time_local" And getting from DB: 2019-02-25 11:30:26 In Django: 2019-02-25 11:30:26 -0300 Why not +3? Why -3? -
Why isn't my 'extend' working in html file in django?
This is getting really irritating. I don't know what I am doing wrong and what is wrong because literally I get no errors. But this is the problem. My other html files in not being displayed on the main.html file. These are the three file: 1)main.html {% load static %} <link href="{% static 'tinymce/css/prism.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <!DOCTYPE html> <head> <title></title> </head> <html> <body> {% block nav_bar %} {% endblock %} {% block tutorial_blocks %} {% endblock %} <script src="{% static 'tinymce/js/prism.js' %}"></script> </body> </html> 2)tutorial_blocks.html {% extends 'center/main.html' %} {% block tutorial_blocks %} {% for x in tutorials %} <div class="col s12 m6 l4"> <div class="card blue-grey darken-1"> <div class="card-content white-text"> <span class="card-title"><b>{{ x.tutorial_title|safe }}</b></span> <p><font color="black">{{ x.tutorial_content|safe }}</font></p> <p>Uploaded: <i>{{ x.tutorial_published }}</i></p> </div> <!-- <div class="card-action"> <a href="#">Visit</a> </div> --> </div> </div> {% endfor %} {% endblock %} 3)nav_bar.html {% extends 'center/main.html' %} {% block nav_bar %} <nav> <div class="nav-wrapper"> <a href="/" class="brand-logo">Tutorials!</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a href="/">Home</a></li> <li><a href="/register">Register</a></li> <li><a href="/login">Login</a></li> </ul> </div> </nav> {% endblock %} Whenever I run the server I receive a blank white page.However if I do it like this, it works: {% load static %} <link href="{% … -
Troubles with adding migrations on Heroku , Django app
I ran into a problem with migration on Heroku. I made few model changes locally, migrated it smoothly locally as well – no problems. When I re-deployed my app on Heroku (app was already there with old pre-migration DB) and ran migrations I got following output: python manage.py makemigrations on ⬢ boatsproject-eu... up, run.2252 (Free) Migrations for 'articles': articles/migrations/0018_auto_20190613_1240.py - Add field change_date to comment - Add field change_date to heading - Alter field change_date on article - Alter field title on article - Alter field author on comment Migrations for 'boats': boats/migrations/0028_auto_20190613_1240.py - Add field change_date to boatimage - Add field change_date to boatmodel - Alter field boat_name on boatmodel These are new changes to apply And finally migrate: heroku run -a boatsproject-eu python manage.py migrate Running python manage.py migrate on ⬢ boatsproject-eu... up, run.7674 (Free) Operations to perform: Apply all migrations: admin, articles, auth, boats, captcha, contenttypes, easy_thumbnails, reversion, sessions, social_django, testapp Running migrations: Applying articles.0017_auto_20190517_1713... OK Applying boats.0026_auto_20190522_1053... OK Applying boats.0027_auto_20190530_1536... OK Applying reversion.0001_squashed_0004_auto_20160611_1202... OK Applying social_django.0001_initial... OK Applying social_django.0002_add_related_name... OK Applying social_django.0003_alter_email_max_length... OK Applying social_django.0004_auto_20160423_0400... OK Applying social_django.0005_auto_20160727_2333... OK Applying social_django.0006_partial...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "social_auth_partial" … -
Can django consume rest api to make a beautiful CRUD web app?
My partner control mysql database and supply me a rest web service , I will call this rest api to finish CRUD (create , retrieve , update , delete) operation . I perform to use django framework , after spend some time to study , I find django can easily finish CRUD by using the database it migrated . but in my case , I will call rest api to operate remote mysql database . Is django the suitable framework to finish this work ? or if any other framework can finish it with beautiful UI , please give me some suggest -
I would like to do the same in views that admin.register decorator does in admin
I would like to be able to register different models from a single front view, as I can do from the admin create view. for example in models.py: class Book(models.Model): """Model representing a book (but not a specific copy of a book).""" title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) in admin.py I have: @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): in the admin panel I get I would like to be able to add author by the same way from the create book view in frontend, thank you for your help -
Unable to save objects using nested serializer in django rest framework
I have to save objects of two different models and using nested serializers. I am using following django rest docs:- https://www.django-rest-framework.org/api-guide/relations/#Writable%20nested%20serializers I have followed many solutions on stackoverflow however I am unable to figure the following error:- Bad Request: /api/register "POST /api/register HTTP/1.1" 400 50 I checked my serializers by printing request.data and they are working fine. However, serializer.is_valid(raise_exception=True) raises the above error. serializers.py # Serializer for report class ReportAPISerializer(serializers.ModelSerializer): latitude = serializers.FloatField() longitude = serializers.FloatField() class Meta: model = Property fields = ('longitude', 'latitude', 'consumer_type', 'area', 'avg_monthly_bill',) # Serializer to get user details class UserSerializer(serializers.ModelSerializer): property = ReportAPISerializer() class Meta: model = InterestedUser fields = ('full_name', 'phone_no', 'email', 'property') def create(self, validated_data): property_data = validated_data.pop('property') user = InterestedUser.objects.create(**validated_data) Property.objects.create( owner=user, location=Point(property_data['latitude'], property_data['longitude']), area=property_data['area'], consumer_type=property_data['consumer_type'], avg_monthly_bill=property_data['avg_monthly_bill'] ) return user views.py class RegisterAPIVIew(CreateAPIView): serializer_class = UserSerializer models.py class InterestedUser(AbstractBaseUser, PermissionsMixin): user_id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) date = models.DateTimeField(auto_now_add=True, null=True, blank=True) full_name = models.CharField(max_length=50, default="") email = models.EmailField(blank=False, unique=True) phone_no = models.CharField(max_length=10, default="") active = models.BooleanField(default=False) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) password = models.CharField(default="", max_length=128) is_superuser = None objects = InterestedUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): return "%s -- %s" … -
How can I capture errors and exceptions data from frontend response to django to add more context
I want to receive some parameters with my error capture on django when something wrong on the front-end I have react frontend running on a django backend. Sentry is been used to capture errors and report. In settings.py: SENTRY_DSN = os.environ.get("SENTRY_DSN") if SENTRY_DSN: sentry_sdk.init( dsn=SENTRY_DSN, integrations=[DjangoIntegration()], environment=ENVIRONMENT, release=os.environ.get("HEROKU_RELEASE_VERSION") or "HEROKU_RELEASE_VERSION not set", ) with configure_scope() as scope: scope.user = {"user": "broken lol"} This is reporting the errors from entire app. However, I want to add user ids to error Sentry reports. To do that I need to capture the response from frontend and somehow get that into settings.py and replace the "broken lol" string with UserId -
Serializer for json array
I want to get into my DRF view a json array array_example and then split it. Below is my json: { "key1": "example_key", "array_example": [ "string1", "string2" ] } This is my serializer: class ExampleSerializer(serializers.Serializer): key1 = serializers.CharField(allow_null=True, required=False) array_example = serializers.ListField(child=serializers.CharField()) And this is my view: serializer = sers.ExampleSerializer(data=request.data) serializer.is_valid(raise_exception=True) strings = ','.join(serializer.validated_data['array_example'], []) 1) Is this a correct approach for my case? 2) I get a validation error on array_example. Why ? -
Django fails on "unexpected keyword argument 'allow_blank'", even though I'm following documentation
When I tried adding the possibility for empty fields for one of my models, I get the following error-message: "TypeError: init() got an unexpected keyword argument 'allow_blank'" What I tried doing was adding the keyword "allow_blank=True" to both a TextField and a CharField. Same error in both instances. from django.db import models from django.contrib.auth.models import User class Set(models.Model): pass class Chat(models.Model): setID = models.ForeignKey(Set, on_delete=models.CASCADE) chatID = models.CharField(max_length=100) class Message(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) chatID = models.CharField(max_length=100) messageID = models.CharField(max_length=100) createdDate = models.DateTimeField() createdBy = models.CharField(max_length=1000) author = models.CharField(max_length=1000) messageDate = models.DateTimeField() text = models.TextField() class Category(models.Model): name = models.CharField(max_length=100) class Tag(models.Model): user = models.ForeignKey(User, related_name="tags", on_delete=models.CASCADE, null=True) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) value = models.TextField(max_length=None, allow_blank=True) message = models.ForeignKey(Message, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) flagged = models.BooleanField(default=False) What I want to do is allow an empty field in my Tag-model, so if there is a better way to do this, please do tell. -
REST Framework: Update field in one model and track changes in another model
I have two models: class CustomUser(models.Model): ... act = models.CharField(max_length=10) class ActHistory(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) last_act = models.CharField(max_length=10) act_time = models.DateTimeField(auto_now_add=True) I would like to create a single API endpoint /update/ with DRF that does this: If value vs existing act value in the model is the same, do nothing. If the values are different, update the CustomUser for the authenticated user with the value Then insert a record row in ActHistory with user=authenticated user, last_act = All the docs I managed to find only support doing either the update or create actions with each API point. Thanks in advance! -
How do I permanently publish a project prepared using Django and React?
In my project I used django in the backend and react in the frontend on the linux server. How can I make the development server from django and react running permanent? So that it does't stop when I quit the shell.