Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uncaught (in promise) Error: Network Error - Django and React
I am trying to make a axios get request to the backend built using DRF. I am getting the following error and the data does not load. import React, { useState, useEffect } from 'react' import Service from '../components/Service' import axios from 'axios' const ServicesScreen = () => { const [services, setServices] = useState([]) const [loading, setLoading] = useState(true) useEffect(() => { const getData = async () => { const { data } = await axios.get(`http://127.0.0.1:8000/api/services/`) setServices(data) setLoading(false) } getData() }, []) console.log(services) return ( <div> <Service header='Header' title='Carpenter' text='Text' /> </div> ) } export default ServicesScreen I have set the permissions at the backend in django settings. -
Is @transaction.atomic cheap?
This is mostly curiosity, but is the DB penalty for wrapping an entire view with @transaction.atomic a negligible one? I'm thinking of views where the GET of a form or its re-display after a validation fail involves processing querysets. (ModelChoiceFields, for example, or fetching an object that the template displays.) It seems to me to be far more natural to use with transaction.atomic() around the block of code which actually alters a bunch of related DB objects only after the user's inputs have validated. Am I missing something? -
Is Django blocking requests.post data in production platform?
From my Django webserver in production I have the below code snippet, where I am putting some data from an object into a postBody and posting the data to another server for it to be processed def sendOrderToRestaurant(session_id): order = Order.objects.filter(session_id = session_id).values() #Create a postBody and load the payload postBody = dict() postBody['order'] = order[0] postBody['order']['orderCreationDateTime'] = order[0]['orderCreationDateTime'].isoformat() postBody['order']['webhookDateTimePaymentReceived'] = order[0]['webhookDateTimePaymentReceived'].isoformat() #Extract the cartItems corresponding to the order session_id postBody['cartItems'] = list() cartItems = CartItem.objects.filter(cart_id = session_id) for item in cartItems: tmp = dict() tmp['quantity'] = int(item.quantity) tmp['productName'] = item.product.name tmp['productUnitPrice'] = float(item.product.price) tmp['DeliveryFee'] = float(item.restaurant.delivery_fee) tmp['bagFee'] = float(item.restaurant.bagFee) postBody['cartItems'].append(tmp) #Request post url = 'http://someservername.dk/submitOrder' response = requests.post(url, json = postBody, headers={"Content-Type":"application/json"}) return response.status_code, postBody I have verified in the log that postBody exists and have the right content that I expect. However when it was being posted to another server running on flask, nothing is received. @app.route('/submitOrder', methods = ['GET','POST']) def receiveOrder(): content = request.json logging.info('The received content') logging.debug(type(content)) logging.debug(content) #Print the content printKitchenThread = threading.Thread(target = printKitchen, args = (printer_ip, content,)) printKitchenThread.start() printHostThread = threading.Thread(target = printHost, args = (printer_ip, content,)) printHostThread.start() #Only print driver if it is a delivery if content['order']['delivery']: printDriverThread = threading.Thread(target = printDriver, … -
Name returning a number after serializing data
I have a table service : from django.db import models from users.models import CustomUser SERVICE_CHOICES = ( ('Carpenter', 'Carpenter'), ('Driver', 'Driver'), ('Ambulanve', 'Ambulanve'), ('Spa', 'Spa'), ('Barber', 'Barber'), ('Cleaning', 'Cleaning'), ('Cook', 'Cook'), ) class Service(models.Model): name = models.ForeignKey(CustomUser, on_delete=models.CASCADE, limit_choices_to={'is_worker': True},) service = models.CharField(choices=SERVICE_CHOICES,max_length=100) def __str__(self): return f'{self.service} - {self.name}' and a table CustomUser : from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_worker = models.BooleanField(default=False) is_customer = models.BooleanField(default=True) I am serializing the Service table below : from rest_framework import serializers from django.contrib.auth.models import User from .models import * class ServiceSerializer(serializers.ModelSerializer): class Meta: model = Service fields = '__all__' But when I add a service from the admin panel, the name shows a number in the browser and not the string. How do I change it to show a the name and not a number? -
Docker-compose (and django): Can't get environment variables onto the services
I'm trying to write a small docker(-compose) deployment solution for a small Django application. Currently, the django-compose file, named docker-compose.dev.yaml looks something like this: version: "3" services: backend: build: context: ./backend dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 env_file: - dev.env The file dev.env looks like this: DEBUG=1 SECRET_KEY=We9ZyuSKsP9Mgvsrt74gExF8baWbGL # not important that this leaks DJANGO_ALLOWED_HOSTS=localhost However, when django tries to start, I get the following: #11 0.634 ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") #11 0.634 AttributeError: 'NoneType' object has no attribute 'split' Basically, the environment variable is returning None, meaning the variables aren't getting onto the container. I tried, according to the docs, to do this: # ... environment: - DEBUG - SECRET_KEY - DJANGO_ALLOWED_HOSTS Without any luck. Any ideas? The repository behind the code is public, I invite you to try. My current test environment is Docker desktop on Windows 10. -
Apache server with django is saying: Access denied for user 'root'@'localhost'
I am trying to run a working Django server on Apache2. I've install and configured an Apache2 server with the following 000-default.conf: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin oreo@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog /home/chunao/WhiteBoard/error.log CustomLog /home/chunao/WhiteBoard/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # … -
How to render choices in a Django field based on a condition
I have a custom user model: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_worker = models.BooleanField(default=False) is_customer = models.BooleanField(default=True) def __str__(self): return f'{self.username} - {self.is_worker}' And I have this model services : from django.db import models from users.models import CustomUser SERVICE_CHOICES = ( ('Carpenter', 'Carpenter'), ('Driver', 'Driver'), ('Ambulanve', 'Ambulanve'), ('Spa', 'Spa'), ('Barber', 'Barber'), ('Cleaning', 'Cleaning'), ('Cook', 'Cook'), ) class Service(models.Model): name = models.ForeignKey(CustomUser, on_delete=models.CASCADE) service = models.CharField(choices=SERVICE_CHOICES,max_length=100) def __str__(self): return f'{self.service} - {self.name}' In services model, I am using CustomUser model for the name. Whereas, I need only those names where is_worker = True. In my code, I am getting all the users irrespective of the status. How can I change it? -
How can I get date like(07.11.2021 ) from date name like (Monday,Tuesday...)
I' developing a django project and in my template user can select a day.As shown as bottom picture. And after day select post request is working.And in my views.py I can get the day name.Like(Monday,Tuesday,...).Using this knowledge, I want to get date of this week.For example coming value of request is Wednesday and I want to get what date is Wednesday in this week like (03.11.2021) -
Django choice field as model ForeignKey in FormSet
I have models which is Player and Position. Player is associated with position player is currently at. You can assign a player new position, which is why I need it to use it in some form. But in that form I see that Position is position Object (see image bellow), but I would like to put "Position.name" in there to see the name of choices instead that object, but I have no Idea how to do it. Thank you for your help. models.py class Position(models.Model): name = models.CharField(max_length=20) short = models.CharField(max_length=2) class Players(models.Model): name = models.CharField(max_length=200) positionId = models.ForeignKey(Position, on_delete=models.CASCADE, null=True, blank=True) forms.py class CompositionForm(ModelForm): class Meta: model = Players fields = ("positionId", ... many more ... ) table.html <table id="nominated-player-table" class="table table-bordered" style=""> {% for form in formset.forms %} {% if forloop.first %} <thead> <td colspan="15" style="background-color: dimgray; color: white; border-top-right-radius: 15px; border-top-left-radius: 15px; border: none"> Nominovaní hráči </td> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr> {% for field in form.visible_fields %} <td> {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field }} </td> {% … -
CSS acting differently in localhost
I'm working on a project. So first, i started with front-end. And then after finishing that, i loaded all the files in django app and started the localhost. But suddenly everything seems to be bigger. Most of the padding, margin, font-size, changes from small to big 1.front end designed locally is the first image. 2.frond end after loading into localhost is the second image Why is this happening, is there any solution for this. Do I have to redesign all on the perspective of localhost AGAIN? -
Update profile picture through clicking on picture itself Django
I'm trying to find some info online on how to update my user's profile picture on the profile page in the same way that social media applications do it, i.e. by clicking on the profile picture itself and getting asked for the file upload straight away. However, all I'm finding online is options to create a form to do that job, but then it's going to be an upload button that does the job, which is not the same. How do I get the image to be clickable, opening a file upload after I click it that would then update my model ImageField? -
Understanding flaky Django tests: Creation order affecting array order
I have a test in Django that looks something like this: class WebhookClientSerializerTestCase(TestCase): def test_serializes_agent_from_client(self): agent1 = factories.AgentUserFactory(email='dave@agently.com') agent2 = factories.AgentUserFactory(email='jim@agently.com') client = factories.ClientFactory(agents=[agent1, agent2]) schema = serializers.WebhookClientSerializer() # do some stuff data = schema.dump(client).data self.assertEqual(data['agents'][0]['email'], 'dave@agently.com') self.assertEqual(data['agents'][1]['email'], 'jim@agently.com') We create a entity called an Agent, then another, and run through some custom serializer logic. The serializer returns an array of serialized agent data. There are other tests defined within the same class. However, sometimes the agents come out in the wrong order. It fails with AssertionError: u'jim@agently.com' != 'dave@agently.com' I had assumed that when the entities were created, that it would be done sequentially. This test runs fine locally, but it fails in CI/CD sometimes, not always. We use the --parallel flag when running tests, but I don't see where or how the asynchronicity is messing with the order of the output array. Why does the order change, and how could I write this test more robustly? -
save() method for django_comments_xtd model
I am using Wagtail + Django_comments_xtd + Django. My_Django_App/models.py from wagtail.core.models import Page class PostPage(Page): ... from django_comments_xtd.models import XtdComment class PostComment(XtdComment): page = ParentalKey('PostPage', on_delete=models.CASCADE, related_name='rn_comments') def save(self, *args, **kwargs): if self.user: self.user_name = self.user.username self.page = PostDetail.objects.get(pk=self.object_pk) super(PostComment, self).save(*args, **kwargs) On Wagtail CMS, if I revise an existing post which has some comments already and publish the revised post again, I thought PostComment.save() should not be triggered any more. However, during my debug, I found it was triggered unexpectedly. I guess that I need to fine-tune PostComment.save() to achieve above intention. After some researches on StackOverflow, Identifying new Model Instance in Django Save with UUID pk In a django model custom save() method, how should you identify a new object? I realize that I might need to use PostComment._state.adding and force_insert within the save() to achieve my intention. Can anyone show me how should I fine-tune PostComment.save() ? -
django-filter: How to get the choices from related model?
Im trying to create a filter, and get the choices from the related model. Is it possible? My models: class Container(models.Model): description = models.CharField(max_length=255) class Period(models.Model): class PeriodType(models.TextChoices): LONG = 'long', 'Long period' SHORT = 'short', 'Short period' container = models.ForeignKey(to=Container, null=True, blank=True, on_delete=models.SET_NULL) type = models.CharField(max_length=15, choices=PeriodType.choices, null=True, blank=True) My viewset: class ContainerFilter(django_filters.FilterSet): type_of_period = django_filters.ModelChoiceFilter(Period.objects.all(), field_name='period__type', label='Type') class Meta: model = models.Container fields = ['type_of_period',] class ContainerModelViewSet(viewsets.ModelViewSet): queryset = models.Container.objects.all() lookup_field = 'id' filter_backends = [filters.SearchFilter, django_filters.rest_framework.DjangoFilterBackend] search_fields = ['description',] filter_class = ContainerFilter -
Django caches user object
Our websites sometimes has around 600 authenticated users trying to register for an event in a timeframe of 5 min. We have a VPS with 1 CPU and 1GB ram. On these moments the site slows down and gives a 502 error. For that reason I'm using per-site cache with FileBasedCache. This works excellent and stress tests work fine. But, when people login, they're redirect to their profile. This is the code: class UserRedirectView(LoginRequiredMixin, RedirectView): permanent = False def get_redirect_url(self): return reverse("users:detail", kwargs={"membership_number": self.request.user.membership_number}) the user is redirect to an url with their membership_number class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = "membership_number" slug_url_kwarg = "membership_number" Some users are reporting that they are redirected to someone else his/her profile after logging in. How does this work? How to prevent user specific parts of the website to be cached? e.g. users also see a list of events that are specific to the groups they are in. In other words, every user should see a different list. Any ideas? Best practices? -
Django Change 3rd Party Model Name
I know that I can change the name of model created by myself using verbose_name="Updated Model name". Is there any way of changing name of 3rd party model in Django? I also tried changing the attribute of parent class using child class but that didn't work for me. -
Overrided Multi Select BooleanField request response django
The information are here: This is print(request.POST) in views.py <QueryDict: {'csrfmiddlewaretoken': ['token'], 'agree_2': ['19', '22'], 'submit_multiple': ['']}> My views.py return JsonResponse(request.POST) {"csrfmiddlewaretoken": "token", "agree_2": "22", "submit_multiple": ""} enter image description here enter image description here What i want to do is take post id to be value in boolean field and I want to take all "agree_2":["19","22"] This is my views.py files def index(request): AVM_Form = AVMForm() post = PostAVM.objects.all() context = { 'form':AVM_Form, 'post':post, } if request.method=='POST': if 'submit_single' in request.POST: submitPost(request) return HttpResponseRedirect('result/') elif 'submit_multiple' in request.POST: dump = request.POST print(dump) return JsonResponse(dump) return render(request, 'index.html', context) Could anyone help me? Thanks for help! -
Make REST Framework require authentication for GET method
I'm working on an Django app that uses REST Framework together with Swagger. Also added some models, and one of them is called Example. Added some views based on mixins in views.py for the model previously mentioned. In views.py, I've created two classes: ExampleList (that uses GET to get all the objects made out from that model and POST to add a new model) and ExampleIndividual, that uses methods such as individual GET, PUT and DELETE. Anyways, this is how my ExampleList class looks like: class ExampleList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): permission_classes = [IsAuthenticated] queryset = ExampleModel.objects.all() serializer_class = ExampleSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) In the settings.py file, in the REST_FRAMEWORK configuration, I've set: 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] Everything works fine at this moment. What I want to do, is, whenever I want to get the list of all objects from the Example model (access the get() method from the ExampleList() class, I want it to work only if I am authenticated (using the Authorize option from Swagger). If not, a status code like "FORBIDDEN" should be returned. I tried using permission_classes = [IsAuthenticated] at the beginning … -
Field 'id' expected a number but got 'product_id' django
In my ecommerce app when I click on add to cart the product goes to the cart but when I click on the cart it gives me the error that 'Field 'id' expected a number but got 'product_id''. Basically I use context_processor to pass the cart.py information to the template. Link to the cart from base.html is: <div class="navbar-item"> <a href="{% url 'cart' %}" class="button is-dark">Cart {% if cart %}({{cart|length}}){% endif %}</a> </div> When I click on cart this error is generated: Field 'id' expected a number but got 'product_id' my project/urls.py is path('cart/',include("cart.urls")), my cart/urls.py is urlpatterns = [ path('',views.cart_detail, name='cart') ] my cart/cart.py is from django.conf import settings from product.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __iter__(self): for p in self.cart.keys(): self.cart[(p)]['product'] = Product.objects.get(pk=p) for item in self.cart.values(): item['total_price'] = item['product'].price * item['quantity'] yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def add(self, product_id, quantity=1, update_quantity=False): product_id = str(product_id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 1, 'id': product_id} if update_quantity: self.cart[product_id]['quantity'] += int(quantity) if self.cart[product_id]['quantity'] == 0: self.remove(product_id) self.save() print(self.cart) def remove(self, product_id): if product_id … -
CSRF token error for django app when deploying to AWS server
I have a django site that runs fine locally but when trying to deploy with AWS elastic beanstalk I get the following error when I try to login (using django allauth) Forbidden (403) CSRF verification failed. Request aborted. The logs state: Forbidden (CSRF cookie not set.): /accounts/login/ My settings.py middleware has: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.common.BrokenLinkEmailsMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] The form has a csrf_token: <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> <button class="primaryAction btn btn-primary" type="submit">{% trans "Sign In" %}</button> </form> Any advice as to how to fix and why it runs ok locally but not when deployed appreciated -
How to set charset header in Django 1.11
we are using Django1.11 and we are having some problems because our header Content-Type does not contain the charset part set to UTF-8. Something like this: Content-Type: application/json; charset=UTF-8 I want to fix that for all endpoints, so I have thought to include a middleware to run after all midlewares have been run. The problem is that I do not know if that's possible. Any ideas? Or alternative solutions? -
Difference between creating a field vs model Django model
I have a small uml association diagram. It goes as follows... PetOwner first_name:CharField last_name:CharField email:EmailField address:CharField phone_number:CharField pet:Pet[0..*] and Pet first_name:CharField last_name:CharField breed:CharField weight:FloatField date_of_birth:DateField date_of_death:DateField owner:PetOwner[1..*] The idea is a PetOwner may own 0 - many pets and a Pet can have 1 - many owners. You can see that the Pet has a field breed. However, I have an understanding that you want to use models to represent selection-list options. This is recommended when all the options aren't known up front or may change. The breed of my pet won't change but I might not know the breed at first? I was thinking about creating a table for Breed and so in my Pet the breed field would be of type Breed, where a Pet can be only of one breed and there could be 0 or many pets of a certain breed. If I did this what exactly is the advantage of this over just having it as a String field in my database without creating a new table for Breed. -
decoding b64 data uri django
The user fills out a form and provides a signature. The signature becomes an encoded data image URI and sent via AJAX to the view, it is then decoded and saved as a png in the database. When the string is passed to the server it is different to what I console.log() on the client side. Usually it converts '+' to whitespace - which I thought I corrected, but it sometimes still throws the error incorrect padding. This is my first time working with base64 and file uploads in Django. Could somebody please tell me if there is an error in the code I'm using or if there is a better way to send data URI to django views? Views.py def certify_logbook_ajax(request): if request.method == 'POST': if request.is_ajax: encoded_sig = request.POST.get('signature').split(',') encoded_sig[1] = re.sub(r"\s+", '+', encoded_sig[1]) decoded_sig = base64.b64decode(encoded_sig[1]) file = {'signature': SimpleUploadedFile('signature.png', decoded_sig)} form = CertifyLogbookForm(request.POST, file) form.instance.user = request.user if form.is_valid(): form.save() return JsonResponse(....) else: return JsonResponse(form.errors.as_json(escape_html=False), safe=False) return Http404() Javascript Sent via XMLHttpRequest for (let i = 0; i < formFields.length; i++) { ajaxStr += formFields[i].getAttribute('name') + '=' + formFields[i].value + '&'; } ajaxStr += 'signature=' + signaturePad.toDataURL("image/png") + '&csrfmiddlewaretoken={{ csrf_token }}'; Error log Traceback (most recent … -
Geodjango saving shapefile to postgis (Geopandas, geoalchemy2)
hi I'm trying to store a shp in postgis, creating an additional column where I insert the geometry, but trying to convert gdf ['geom'] = gdf ['geometry']. apply (lambda x: WKTElement (x. wkt, srid = epsg)), The server overflows, I have no errors but I imagine it is because we have empty data, I work in a mac environment my model.py # extract zipfile with zipfile.ZipFile(file, 'r') as zip_ref: zip_ref.extractall(file_path) os.remove(file) # remove zip file shp = glob.glob(r'{}/**/*.shp'.format(file_path), recursive=True) # to get shp try: req_shp = shp[0] gdf = gpd.read_file(req_shp) # make geodataframe crs_name = gdf.crs epsg = crs_name.to_epsg() if epsg is None: epsg = 4326 # wgs 84 coordinate system #geom_type = gdf.geom_type[1] engine = create_engine(conn_str) # create the SQLAlchemy's engine to use print('-----', name, '-----') gdf['geom'] = gdf['geometry'].apply( lambda x:WKTElement(x.wkt, srid=epsg)) print('-----', name, '-----') # Drop the geometry column (since we already backup this column with geom) gdf.drop('geometry', 1, inplace=True) gdf.to_sql(name, engine, 'data', if_exists='replace', index=False, dtype={'geom': Geometry('Geometry', srid=epsg)}) # post gdf to the postgresql gdf.to_postgis( con=engine, name=name, if_exist="replace") for s in shp: os.remove(s) except Exception as e: for s in shp: os.remove(s) instance.delete() print("There is problem during shp upload: ", e) geo.create_featurestore(store_name='xxxxxxxx', workspace='xxxxxxxxx', db='xxxxxxxx', host='localhost', pg_user='postgres', pg_password='xxxxxxxx', schema='xxxx') … -
How do I use `@transaction` to rollback the registered user in case Email fails to generate?
I am building a simple django-rest-framework backend that uses dj-rest-auth authentication system with the following settings ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' I want to ensure that in case of failure in email-generation the registered user is rolled back. This is my serializer.py class CustomRegisterSerializer(RegisterSerializer): first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=30) @transaction.atomic def save(self, request): try: user = super().save(request) user.first_name = self.data.get('first_name') user.last_name = self.data.get('last_name') user.save() return user except <...What exception has to be caught?...>: transaction.set_rollback(True) return What exception do i have to catch and am I doing this right? How do I achieve this? For reference, this is the error generated in case of wrong values in settings.py file Exception Type: ConnectionRefusedError at /api/auth/register/ Exception Value: [WinError 10061] No connection could be made because the target machine actively refused it Also is it possible to rollback in case of user submitting a wrong email and email fails to deliver?