Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can you send a subExpand in django?
As you can see, I am making a request to get to viewset ServicioRealizadosOrdenTrabajoTipoViewSet. if you look at the serializer "Servicioserializer", There are 3 expandable_fields that I am using in the frontend endpint sefl._list.... ".....&expand=tecnico&expand=orden_trabajo". lor what I want is to be able to pass a subExpand to "&expand=Orden_trabajo(expand=vehiculo)" something like that. Resume: expand "vehicle" from "Serializer order" from the end point. through the viewSet ServicioPalizadasOrdenTrabajoTipoViewSet class OrdenSerializer(BaseSerializer): foto_derecha = Base64ImageField(required=False, use_url=False) foto_izquierda = Base64ImageField(required=False, use_url=False) foto_frente = Base64ImageField(required=False, use_url=False) foto_atras = Base64ImageField(required=False, use_url=False) foto_panel = Base64ImageField(required=False, use_url=False) class Meta: model = Orden fields = '__all__' expandable_fields = { 'vehiculo': (Vehiculoserializer, { 'many': False }), 'asesor': (Tecnicoserializer, { 'many': False }), 'servicio_orden_registro': (Orden_registroserializer2, { 'many': True }) } class Orden_trabajo(BaseModel): ORDENTIPO = ( (1, 'estandar'), (2, 'garantia'), (3, 'cortesia') ) STATETIPO = ( (1, 'abierta'), (2, 'bodega'), (3, 'revisada'), (4, 'correo'), (5, 'aceptada'), (6, 'parcial'), (7, 'rechazada'), (8, 'orden'), (9, 'incompleto'), (10, 'completo') ) NIVELCOMBUSTIBLE = ( (1, 'Vacio'), (2, 'Primer cuarto'), (3, 'Segundo cuarto'), (4, 'Tercer cuarto'), (5, 'Lleno') ) def number(): no = Orden_trabajo.objects.count() if no == None: return 1 else: return no + 1 vehiculo = models.ForeignKey(Vehiculo, on_delete=models.CASCADE, related_name="vehiculo", null=True) tercero = models.IntegerField(blank=True, null=True) tercero_nombre = models.CharField(max_length=150,default='') … -
Django Rest Framework can't identify serializer field name
This is the problem: I have a serializer field pointing to another serializer. I sending an allright request to server and I get this response: { "purchase_header": [ "This field is required." ] } But the field was sended by POST request (in debugger I can see it). I finded this code in html.py (from DRF): def parse_html_dict(dictionary, prefix=''): """ Used to support dictionary values in HTML forms. { 'profile.username': 'example', 'profile.email': 'example@example.com', } --> { 'profile': { 'username': 'example', 'email': 'example@example.com' } } """ ret = MultiValueDict() regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix)) for field in dictionary: match = regex.match(field) if not match: continue key = match.groups()[0] value = dictionary.getlist(field) ret.setlist(key, value) return ret Well, when debuging I can see that prefix variable contain "purchase_header" and field variable contain the same "purchase_header" string but de match fail returning None. Very rare... dictionary parameter contain all keys and values. But If you can helpme I appreciate much. This is the rest of significant code: urls.py router = DefaultRouter() router.register(r'cancel-requests', PurchaseCancellationsRequestViewSet, basename='purchase-cancel-requests') router.register(r'invoices', PurchaseViewSet, basename='purchase') urlpatterns = router.urls urlpatterns += [path('payment-headers/', PaymentHeadersListAPIView.as_view( ), name='PaymentHeadersListAPIView')] api.py class PurchaseViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing purchases instances. """ serializer_class = PurchaseSerializer queryset = … -
Django Lambda with Microservices, Breaking Django Project in Lambda functions
I've just started to implement serverless architecture using Django and AWS lambda and It's working perfectly fine now. My project consist of two apps user_onboarding and user_training and structure is as follows : MainApp - user_onboarding - models.py - urls.py - views.py - user_training - models.py - urls.py - views.py - MainApp - urls.py - settings.py - wsgi.py - manage.py - lambda_handler.py - serverless.yml model/s are shared between both the apps, contains one to many, Foreign Key relations and working perfectly fine on Lambda. now, I want to split the apps into two different lambda functions. i.e. user_onboarding in seperate lambda function and user_training in seperate lambda function. what will be the best approach to achieve this? My Questions while I was thinking of it: how my models are going to be shared with lambda functions? does lambda layers is the best option? i) I've tried making layers of both the apps's models like this structure: ``` > python/user_onboarding_models/models.py > python/user_training_models/models.py ``` and when I tried to import models so that I can use to query in ORM like this : from user_onboarding_models.models import *. It gives me error - RuntimeError: Model class user_onboarding_models.models.xxx doesn't declare an explicit app_label and … -
Return a string representation of a model in another model DJango
So I have two models, and if I try the get method on postman for the products, I can only see the product category by ID and I want to see it as text. Any ideas on how to do that? I tried using the def save and then setting the self.name to Product_category.name and then saving it but still getting the same thing.Thanks in advance. class Product_category(models.Model): name = models.CharField(max_length=50, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50) default_price = models.FloatField(max_length=10) product_category = models.ManyToManyField(Product_category, related_name="products") -
How I limit cart creation to (specific url) "/api/cart/" URL only?
The following class was designed for creating cart and add items to it class CartAPIView(TokenMixin, CartUpdateAPIMixin, APIView): cart = None # get the cart from token otherwise create new cart def get_cart(self): # if the token exist get it from the request token_data = self.request.GET.get('token') # create dummy cart object cart_obj = None # if the get request has token, decode it, get cart_id, return cart object if token_data: # token_dict = ast.literal_eval(base64.standard_b64decode(token_data.encode("utf-8")).decode("utf-8")) token_dict = self.parse_token(token=token_data) cart_id = token_dict.get("cart_id") print(cart_id) try: cart_obj = Cart.objects.get(id=cart_id) except: pass self.token = token_data # If no cart passed in the request it will create new cart object if cart_obj == None: cart = Cart() cart.tax_percentage = 0.075 if self.request.user.is_authenticated: cart.user = self.request.user cart.save() data = { "cart_id": cart.id, } # use the create_token from the mixins to create the token for the new cart self.create_token(data) cart_obj = cart return cart_obj # The entry point for /cart/ API to create & update cart def get(self, request, format=None): # First either i will get the cart data or i wil create new one cart = self.get_cart() self.cart = cart # if the get call has cart and has item it will update the cart self.update_cart() # … -
How to edit the value of a field for a given object? Django
I have a number of votes, and i wont that every time somone clicks on a button that number goes up by one. How to do that? -
generate html page in document pdf multipage django
Good evening everyone if there your help needs I have an html page that I want to convert to PDF in several copies but in the same document. But when I do this it’s the last line of my file that generate then I wanted to have a PDF document so the number of pages is the size of my database -
Serialize Django User in template: Object of type Group is not JSON serializable
I've a Django CBV DetailView that has an embedded Vue app. In the view, I get some of the data and pass it to the template so Vue can access it appropriately. The view data looks like this: def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context["summative"] = get_object_or_404( Summative, id=self.kwargs["summative_id"] ) context["json_requestor"] = model_to_dict(self.request.user) context["json_evaluation"] = model_to_dict(self.object) return context In the template I add it like this: {{ json_requestor|json_script:"requestor-data" }} {{ json_evaluation|json_script:"evaluation-data" }} json_evaluation comes across fine. However the json_requestor is where the error pops up. It gives this error: Object of type Group is not JSON serializable Any thoughts on how to best fix this issue? -
Create a method to update value of fields in django model based on another model
Code I want to update value of Betslip.settled_status to 'Lost', if bet.settlement_status is 'lost' -
ValidationError getting thrown when cascading the deletion of an object
A user always has one default dashboard for each company they are associated with. We prevent the deletion of the last dashboard/ default dashboard by using the below. @receiver(pre_delete, sender=Dashboard) def check_if_default(sender, instance, **kwargs): if instance.is_default: raise ValidationError( 'Default dashboard for a company can not be deleted.') However with this code in place the users can't be deleted as Django tries to cascade this to the model and it raises this ValidationError. Is there some way to prevent this check or to check in the check_if_default if the user is beeing deleted? -
When i put new image to an empty image source it gives me error "ValueError: The 'image' attribute has no file associated with it"
I am using django rest framework, Everything is fine in my code. I can update my file. My main problem is that when i put new image on empty image source it gives me an error like ValueError: The 'image' attribute has no file associated with it. But when i update image with image source it works fine.I want to update my image on empty image source but gives me error like ValueError: The 'image' attribute has no file associated with it Please help me how i solve that error Here is my code: My models.py file: It includes my models fields from django.db import models from django.utils import timezone from .validators import validate_allfile_extension from sessionauthapp.models import User from django.dispatch import receiver import os # from datetime import datetime class Blog(models.Model): id = models.AutoField(primary_key=True) title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.TimeField(default=timezone.now) image = models.FileField(null=True, verbose_name="") user = models.ForeignKey(User, on_delete=models.CASCADE) # time = models.DateTimeField(default=datetime.now) # image = models.ImageField(null=True, verbose_name="", validators=[validate_allfile_extension]) def __str__(self): return self.title @receiver(models.signals.pre_save, sender=Blog) def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding `MediaFile` object is updated with new file. """ # if not … -
Using a Django generated slug URL to link to specific pages
Hi generous and kind people of Stack Overflow. I'm fairly new to Python and Django, and have undertaken the project of building a portfolio for my copywriting. I have a main landing page that's going to have a grid of 9 different writing projects. Someone will click on one of the images for a project and then be brought over to a new page that has a more detailed description of the project. Each individual project page has a URL, whose path contains a slug. The code I have works in generating this path. Each writing project will have a URL path that contains projects/(slug) My problem is that I can't get this slug based link that will point to each individual page to work in my code. I'm getting this error: NoReverseMatch at / Reverse for 'individual_project' not found. 'individual_project' is not a valid view function or pattern name. Please forgive any wonkiness with this code, as I am struggling a bit in understanding it all. Here is my views.py: from django.shortcuts import render, get_object_or_404, get_list_or_404 from .models import Project def individual_project_view(request, project_id): projectpage = get_list_or_404(Project, slug=project_id) return render(request, 'projects/project_detail.html', {'projectpage':projectpage}) def project_home(request): portfolioprojects = get_list_or_404(Project) return render(request, 'projects/project_detail.html', … -
Django REST API on Azure Web App - Static Files
I have a basic django app with django rest framework. I have deployed it to Azure Web App and it working fine except the I am not able to serve the static files. I have the following in setting.py BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_ROOT = "/home/site/wwwroot/static/" # Azure path STATIC_URL = '/static/' The application is looking for www.domain.com/static/". I did ran python manage.py collectstatic file on azure and it does create a directory will all the file at the above location. Not sure what's wrong, may be something to do with how azure containiser the application. Any help would be much appreciated -
Python Django view function for virtual assistant app
I have finished the code for a virtual assistant using neuralintents, speech_recognition, PyAudio, pyttsx3 and a json file for training the model. Now I'm trying to add it to a website I already have. Does anyone have an example of how the view function should look like ? Thanks -
Querying a model to filter where a ManyToManyField matches a specific set
I have two models: class Item(models.Model): name = models.CharField() # etc class MergedItems(models.Model): items = models.ManytoManyField(Item) # etc I want each MergedItem to require a unique set of Items. When a user tries to create a new MergedItem, they pass an array of Item ids. I'm trying to validate that input and error if a MergedItem with that specific set of Items already exists, but I'm struggling with the logic to query for/determine that. For example: User creates MergedItem with Item [1, 2] - OK User creates MergedItem with Item [3, 4] - OK User creates MergedItem with Item [1, 2, 3] - OK, [1, 2] already exists but the addition of 3 makes it a unique set User creates MergedItem with Item [1, 2] - ERROR, [1, 2] already exists All the resources I've found have been focused on using something like filter(items__id_in=[1, 2]) but that does an OR query for the item ids. I want an AND query for them, and haven't been able to find anything like that. I'm sure there are some brute force solutions, but this will be running on a public endpoint to a large database, so query efficiency is also key. Thanks in … -
Django ModuleNotFoundError for urlpattern in Heroku deployment
I have a problem with my Django project after deploying it to Heroku. When I go to the project url on Heroku, I am hit with a "ModuleNotFoundError at / No module named 'spotify.urls' ". spotify is an app name in my project called bio_project. This error message leads me to believe that there is something wrong with my urls somehow or perhaps even settings.py bio_project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("", include("spotify.urls")) ] spotify urls.py from django.urls import path, include from . import views app_name = "spotify" urlpatterns = [ path("", views.index, name="index"), path("authorize", views.authorize, name="authorize"), path("callback", views.callback, name="callback"), path("short_term", views.short_term, name="short_term"), path("medium_term", views.medium_term, name="medium_term"), path("long_term", views.long_term, name="long_term"), ] Here is the error: ModuleNotFoundError at / No module named 'spotify.urls' Request Method: GET Request URL: Django Version: 3.2.6 Exception Type: ModuleNotFoundError Exception Value: No module named 'spotify.urls' Exception Location: , line 984, in _find_and_load_unlocked Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Screenshot of error I cannot seem to make any sense of the error since the app is still working perfectly on localhost. Any thoughts? -
How to hide a user's access token that is sent from Django web application?
I am a beginner. I have been working on a Django web application that is integrated with the Webex API. After the OAuth grant flow, an access token is generated (expires after 14 days, so I stored it in a database) and the access token is used in the Webex space widget code to enable the video calling feature on the website. This webpage template along with the Webex space widget code is rendered with Django. But I'm worried about exposing the access token as anyone can see it with developer tools in the browser. Is there any way to hide this access token visible in the browser? This is the webpage code generated by Django <body> <div id="my-recents-widget" /> <script> var widgetEl = document.getElementById('my-recents-widget'); // Init a new widget webex.widget(widgetEl).recentsWidget({ accessToken: '3f9a677931960cf65b6f13d20d1f1cfbcb2b502321891038' }); </script> </body> When this webpage is rendered in the browser, the access token is visible to anyone using the browser's developer tools. I want to hide this token at the same time making the widget working. Is there any way I can achieve this? As I'm a beginner, a detailed explanation will be helpful. The widget code is available here -
What email API should i use to power an app where users can sign-up and then send emails?
I made a django app where users can sign-up, create an account (not email address) and then ideally send out emails through some specific flows I designed in the app. My question is "how should I power the email sending system?". I initially thought about using gmail api but i don't want users to download/upload their credentials et cetera et cetera so now I am looking at services like SendGrid for example. My ideal scenario is that I have a scalable way to onboard users and send emails. Potentially from different email addresses (one per user) but it's ok also from one same email address (and I can differentiate in the text/subject) Suggestions? -
Django post-form cannot validate when using Form with additional inputs
I have a form containing af MultipleChoiceField where the choices are created dynamic based on the given user class UpdateForm(forms.Form): def __init__(self,names,*args,**kwargs): super(UpdateForm,self).__init__(*args,**kwargs) self.fields["list_names"] = forms.MultipleChoiceField(choices = zip(names,names),widget=forms.CheckboxSelectMultiple,label="Pick some names") add_new = forms.BooleanField(initial=True, label="Add new names?",required=False) delete_missing = forms.BooleanField(label = "Delete names?",required=False) and it works fine as GET-request, the issues arrives with the post-request: My view is the following: def update(request): user = request.user list_names = MyModel.objects.filter(user=user).all().values_list("nick_name",flat=True).distinct() form = UpdateWishlistForm(names =list_names) if request.method == "POST": post_form = UpdateForm(request.POST) if post_form.is_valid(): list_names = post_form.cleaned_data["list_names"] add_new = post_form.cleaned_data["add_new"] delete_missing = post_form.cleaned_data["delete_missing"] messages.success(request, "Success") context = { "form":form, } redirect("home") else: #invalid post_form messages.error(request, "Error") context = { "form":form, } return render(request, "discounttracker/update.html") else: #Get request context = { "form":form, } return render(request, "myapp/update.html",context=context) The post_form = UpdateForm(request.POST) does not validate and the post_form.errors is empty. It does contain data though (before calling post_form.is_valid()) print(post_form) # UpdateForm: <UpdateForm bound=False, valid=Unknown, fields=(add_new;delete_missing;list_names)> print(request.POST.dict()) #<QueryDict: {'csrfmiddlewaretoken': ['...'], 'add_new': ['on'], 'list_names': ['test_name_1']}> -
Django Auto Count Field and User - Django
I am using Django to build a website and now need custom counting for each user. I need a separate count for data submitted by a user for each user separately. I have code that works but I have been trying for a long time to integrate user separation into it but I can't. I'm using a foreign key to separate user's data and I need a separate count for each user so all user's first data submitted starts with 1 and counts up from there. I also think it is easiest to keep it all in my models because that is where I have had the best luck but I could be wrong. Thanks in Advance! models: class Sheet_Building(models.Model): user = models.ForeignKey(User, default=True, related_name="Building", on_delete=models.PROTECT) user_count = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True, verbose_name='Inspection Date') time = models.TimeField(blank=True, null=True, verbose_name='Inspection Time') class Meta: ordering = ['-pk'] def __str__(self): return self.timeor 'None' def get_absolute_url(self): return reverse('list_building') def save(self, *args, **kwargs): self.user_count = Sheet_Building.objects.count() + 1 super(Sheet_Building, self).save() -
Django CookieCutter: django.db.utils.OperationalError: fe_sendauth: no password supplied
How to fix the fe_sendauth: no password supplied erorr? There's this open-source framework for Django that is production-ready (https://github.com/pydanny/cookiecutter-django) I don't exactly know the cause of the error, but I do have some ideas, and I'm going to list out all the possible things that could have led to that error. I've followed all steps from this doc (https://cookiecutter-django.readthedocs.io/en/latest/developing-locally.html) Here are some of my answers to when I initialised the cookiecutter: version [0.1.0]: 0.1.0 timezone [UTC]: GMT use_whitenoise [n]: n use_celery [n]: n use_mailhog [n]: y use_sentry [n]: y use_pycharm [n]: n windows [n]: y use_docker [n]: n use_heroku [n]: n use_compressor [n]: y Select postgresql_version: 1 - 13.2 2 - 12.6 3 - 11.11 4 - 10.16 Choose from 1, 2, 3, 4, 5 [1]: 1 Select js_task_runner: 1 - None 2 - Gulp Choose from 1, 2 [1]: 1 Select cloud_provider: 1 - AWS 2 - GCP 3 - None Choose from 1, 2, 3 [1]: 1 custom_bootstrap_compilation [n]: n Select open_source_license: 1 - MIT 2 - BSD 3 - GPLv3 4 - Apache Software License 2.0 5 - Not open source Choose from 1, 2, 3, 4, 5 [1]: 5 keep_local_envs_in_vcs [y]: y debug[n]: n And then … -
Django forms don't are saving any information
So I have been trying do build a manager of activities with django and I'm still on the scratch. I was trying to test if the code can simply show if a acitivity is done or not, but it don't change anything. Everything looks good to me and I don't know if the error is in the form, in the view that saves the form or in everything else. I already tried to change the widget and fields of form and haven't been succeed in it. models.py: from django.db import models from django.contrib.auth.models import User class Activity(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) is_complete = models.BooleanField() def __str__(self): return self.title forms.py: from .models import Activity class ActivityUpdateForm(ModelForm): class Meta: model = Activity fields = ['is_complete'] views.py: from .models import Activity from .forms import ActivityUpdateForm def home(request): acts = Activity.objects.all() if request.method == 'POST': form = ActivityUpdateForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('home') else: form = ActivityUpdateForm() context = { 'acts': acts, 'form': form, } return render(request, 'diary/home.html', context) template: {% for act in acts %} <form method="POST"> {% csrf_token %} <p>{{ act.title }}</p> <p>Is complete: {{ act.is_complete }}</p> {{ form }} <p>{{ act.author }}</p> <button type="submit">Submit</button> </form> {% endfor … -
Picking up broker_api from Django settings
I have a Django / Celery / Flower setup routing messages to RabbitMQ on windows. All works well except that I can't find a way to pick up the flower broker_api from the Django settings file. CELERY_BROKER_URL is picked up and the tasks can be viewed by Flower, but the Broker tab is blank. If I pass broker_api on the celery -A myapp flower commandline then I can view the Broker tab. e.g. The following works and the broker tab is populated celery -A myapp flower --broker_api=http://myuser:mypwd@localhost:15672/api/ However if I add the broker api into settings.py along with the CELERY_BROKER_URL, instead of passing on the command line, then this no longer works. e.g. CELERY_BROKER_API_URL = 'http://myuser:mypwd@localhost:15672/api/' I have tried different setting names including BROKER_API, BROKER_API_URL, CELERY_BROKER_API, CELERY_BROKER_API_URL and even FLOWER_BROKER_API and FLOWER_BROKER_API_URL. I have also tried adding a flowerconfig.py file with broker_api configured as per the Flower manual, but this doesn't seem to be picked up. Any ideas? -
travis selenium does't work - django - stripe - javascript redirection
I have a selenium test that work on my local machine. Creating test database for alias 'default'... System check identified no issues (0 silenced). ............. ---------------------------------------------------------------------- Ran 13 tests in 32.510s OK Destroying test database for alias 'default'... I use selenium to test stripe checkout. When I click() on button I get redirection to stripe checkout. It work with the javascript from stripe documentation: <script type="text/javascript"> // Create an instance of the Stripe object with your publishable API key var stripe = Stripe("{{ public_api_key }}"); var checkoutButton = document.getElementById("checkout-button"); const headers = new Headers({ 'X-CSRFToken': "{{ csrf_token }}" }) checkoutButton.addEventListener("click", function () { fetch("{% url "sale:detail" ordered.pk %}", { method: "POST", headers, }) .then(function (response) { response_json = response.json(); return response_json; }) .then(function (session) { return stripe.redirectToCheckout({sessionId: session.id}); }) .then(function (result) { // If redirectToCheckout fails due to a browser or network // error, you should display the localized error message to your // customer using error.message. if (result.error) { alert(result.error.message); } }) .catch(function (error) { console.error("Error:", error); }); }); </script> however when i do the same test on travis-ci I get this error: selenium.common.exceptions.TimeoutException due to the: WebDriverWait( selenium, timeout ).until( EC.url_changes(current_url) ) so, the url never change when … -
Ability to have users add/edit/remove form fields dynamically?
I am working on a project that requires a base form + template for ever user, based off of a simple model as such... class FloorPlan(models.Model): user = models.ForeignKey(account) stories = models.IntegerField() bathrooms = models.IntegerField() sqft = models.IntegerField() I know that JS will be needed to make this dynamic. So every user will have a base form and view, which displays just those 3 fields. Now I also want this form to be customizable in a sense to let the user add any extra fields, or also remove fields that are not used. Maybe they add backyard info, pool info, etc. I came across this app, https://github.com/askvortsov1/dynamic-django-forms but doesn't seem to fit what I need. I was thinking of adding an extra field called extra_field=models.ForeignKey(ExtraField) in the FloorPlan model, and make it a m2m, and in the ExtraField model just store the new fields the user wants to create. But design wise, dont think this would be best to let every user flood the DB? I've been looking around to find maybe a JS library too. Really just looking for some advice if anyone has created something similar, just looking for some pointers in the right direction. TY in advance!