Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get Django Form ModelChoiceField values from Class View back to the template from which they came
I am trying to display a list of tests, select one with ModelChoiceField Form and then display the selected test information on the same template the ModelChoiceField is on. (2 fields - the ID number and the name) as a link. So basically you select the test, it appears under the ModelChoiceField as a link and then you click it go to a detail screen. I can capture the selected choice information in the class view in form_valid but I don't know how to return to the template with this new information. Tried various approaches with context etc. but nothing is working. The screen will look something like this: When you press the select button the test selected will appear on the same screen. I need access to both the name and id number, which I get in form_valid # forms.py class TestBrowseForm(forms.Form): choice = forms.ModelChoiceField( Universal_Test_File.objects.all().order_by('test_name'), to_field_name="service_id") # views.py class ListTests(FormView): model = Universal_Test_File context_object_name = "testlist" form_class = TestBrowseForm template_name = "lab/list_tests.html" success_url = '/list_tests/' def form_valid(self, form): # choice is a queryset with both service_id and testname so we need to specify service_id choice = form.cleaned_data.get("choice") ## I want to display the test_name and link to service_id … -
Restrict user registration with registration key
I want to restrict who can register on my site. I want to achieve this by asking for a registration key in the registration form. The key should be valid X amount of times, so not it can not be used by everyone forever. I have created two separate models, one user model and one registration key model. In the User model, have I created a key field, which is a foreign key related to the registration key model. These are my two models class RegistrationKey(models.Model): key = models.CharField(max_length=30) max_amount = models.IntegerField(null=True) class User(AbstractUser): ... key = models.ForeignKey(RegistrationKey, on_delete=models.CASCADE) The problem however is that I don't know how to validate that the key the user enters in the registration form is registered in the model and that the key is still valid, in other words still not being used more than X times. I would appreciate all sorts of help, even sources that describes similar problems because I have not been able to find any. -
sever error ,contact the administrator in django4.0
When i tried to access the admin in django 4.0.3, ** A server error occurs, contact the administrator ** in the terminal it returns the timezone error,while the timezone has not yet be modified how do i resolve this working on termux -
How to get data from django many to many fields?
Model: class Message_Manu(models.Model): Message = models.CharField(max_length=50) def str(self): return str(self.pk) +"."+" "+ self.Message class Frontend_Order(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE,related_name='user_frontend_order') Service_Type = models.CharField(max_length=250, null=True) Price = models.CharField(max_length=250, null=True) Number_of_Section = models.CharField(max_length=250, null=True) Website_Functionality = models.CharField(max_length=50, null=True) Email = models.EmailField(max_length=50, null=True) files = models.FileField(upload_to="0_frontend_files/", null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True, null=True) order_message = models.ManyToManyField(Message_Manu) Views: def index(request): total_user = User.objects.count()-1 frontend_order_list = Frontend_Order.objects.order_by("pk") backend_order_list = Backend_Order.objects.order_by("pk") Complete_Website_Order_list = Complete_Website_Orders.objects.order_by("pk") context = { "total_user":total_user, "frontend_order_list":frontend_order_list, "backend_order_list":backend_order_list, "Complete_Website_Order_list":Complete_Website_Order_list } return render(request,'0_index.html',context) -
How to Deploying Django project on ionos
I have a Django project that I want to deploy on ionos but I don't know how to do this. Please who knows how to do this? -
Django saving forms to sqlite database
I am completely new to django and I am currently working on this program which is already in production. Now I need to save certain forms to a sqlite database and I've watched some tutorials however I cannot understand how to do this. Here is a portion of the code: {% block content %} <!-- Modal --> <div class="card shadow-sm"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> Receptas</h5> <span class="d-flex flex-row-reverse"><button class="btn btn-secondary" id="save_recipe_btn" type="button"><i class="bi bi-save"></i></br> Saugoti</button></span> </div> <div id="card-base" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <div class="row"> <div class="col"> {% csrf_token %} {{recipe_form.ibu}} {{recipe_form.abv}} <div class="row"> <div class="col">{{recipe_form.name|as_crispy_field}}</div> <div class="col">{{recipe_form.style|as_crispy_field}}</div> </div> <div class="row"> <div class="col">{{recipe_form.batch_size|as_crispy_field}}</div> <div class="col">{{recipe_form.boile_time|as_crispy_field}}</div> <div class="col">{{recipe_form.efficiency|as_crispy_field}}</div> </div> <div class="row"> <div class="col">{{recipe_form.primary_age|as_crispy_field}}</div> <div class="col">{{recipe_form.secondary_age|as_crispy_field}}</div> <div class="col">{{recipe_form.age|as_crispy_field}}</div> </div> <div class="row"> <div class="col">{{recipe_form.pub_date|as_crispy_field}}</div> </div> <div class="row"> <div class="col">{{recipe_form.notes|as_crispy_field}}</div> </div> </div> Now I need to save forms like name, style, batch size and so on. In all the tutorials I watch they do something like doing method = post and making the button type = submit However, this whole code looks quite a bit different than what they do in the tutorials and I am unsure whether I still should be saving in the same way or should I do something … -
How to Implement SSO using Django and React
I wanted to achieve Single Sign-On similar to Google, Youtube, Gmail, Drive where only you have to sign in only one time for all the apps. My application backend is on Django Rest Framework - Using JWT Token Front-end: I have two different React apps hosted on two different domains. I read that, google used cookies for the SSO but I haven't found any practical example on how to achieve it. -
Integrating a payment application (API) in a django application
I have a Django web application in which I would like to integrate a local payment API in order to enable customers who want to use their money from this payment application to pay their car insurance but honestly, I don't have any idea of how to do it. Below are the related models (Contrat and Reglement): class Contrat(models.Model): Statut_contrat = ( ('Encours', 'Encours'), ('Suspendu', 'Suspendu'), ('Expiré', 'Expiré'), ) categorie_choices =( ('Tourisme', 'Tourisme'), ('Transport', 'Transport') ) # numero_de_contrat = shortuuid.uuid() type_contrat = models.ForeignKey(TypeContrat, on_delete=models.CASCADE, null=True, blank=False) tca = models.DecimalField(_('TCA 4%'),max_digits=10, decimal_places=2, default=0.00) numero_de_contrat = models.CharField(max_length=50, blank=True, null=True,db_index=True, unique=True) statut_assurance =models.CharField(max_length=15, choices=Statut_contrat, default='Non') vehicule = models.ForeignKey(Vehicule, on_delete=models.CASCADE) utilisateur = models.ForeignKey(User, on_delete=models.CASCADE) nombre_de_mois = models.IntegerField(null=True, blank=True) sous_couvert = models.CharField(_('S/C'),max_length=200, null=True, blank=True) categorie = models.CharField(max_length=50, choices=categorie_choices, null=False, blank=False, default='Tourisme') created = models.DateField(auto_now_add=True) modified = models.DateField(auto_now=True) active = models.BooleanField(default=True) remainingdays=models.IntegerField(default=0) blocked_date=models.DateField() unblocked_date = models.DateField(null=True, blank=True) history = HistoricalRecords() class Meta: ordering=('-created',) @property def static_id(self): 'C{0:07d}'.format(self.pk) def __str__(self): return str(self.numero_de_contrat) def save(self, *args, **kwargs): self.tca=self.type_contrat.montant_du_contrat*Decimal(0.04) if self.statut_assurance=="Suspendu": dt=abs(self.blocked_date-self.modified) print('Difference est:',dt) numberOfDaysLeft= self.remainingdays-dt.days print('Big diff',numberOfDaysLeft) self.remainingdays=numberOfDaysLeft self.blocked_date=date.today() super(Contrat, self).save(*args, **kwargs) def activeStatus(self): if self.nombre_de_mois==0: return self.active==False else: return self.active==True def get_NbDays(self): if self.statut_assurance=='Encours': # nb_Days = timedelta(days=self.remainingdays)+date.today() nb_Days = timedelta(days=self.remainingdays)+self.blocked_date print('Date de fin', nb_Days) return nb_Days … -
How to change information inside hidden tags in .as_table form
I have used .as_table in my website design to format my form, but now I am experiencing problems where random text is displaying within the form that I cant change inside my html document but when I run the website and inspect it I can see the tags and elements inside it and I was wondering how I would remove or change the 'Currenlty' and 'Change' Element being displayed. Html within Visual Studio {% block content_block %} <link rel="stylesheet" type="text/css" href="{% static 'css/editprofile.css' %}" xmlns="http://www.w3.org/1999/html"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <form id="EditProfile" method="POST" action='/edit_profile/' enctype="multipart/form-data"> <h2>Edit Profile</h2> {% csrf_token %} <table> {{ form.as_table }} <br> {{ profile_form.as_table }} </table> <!-- Make changes button--> <div> <button type="submit" class="button">Make Changes</button> </div> </form> <script>$( ".helptext" ).remove();</script> {% endblock %} Html inside web browser <table> <tbody><tr><th><label for="id_email">Email:</label></th><td><input type="email" name="email" value="c.@gmail.com" required="" id="id_email"></td></tr> <tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" value="ctuck" maxlength="150" required="" id="id_username"><br></td></tr> <tr><th><label for="id_picture">Picture:</label></th><td>Currently: <a href="/media/profile_images/parapic_Kuw8fB7.png">profile_images/parapic_Kuw8fB7.png</a> <input type="checkbox" name="picture-clear" id="picture-clear_id"> <label for="picture-clear_id">Clear</label><br> Change: <input type="file" name="picture" accept="image/*" id="id_picture"></td></tr> </tbody></table> -
How could I solve using Deleteview to cancel an order .... error NoReverseMatch at / orderbook /Error
I would like to cancel an order made by the user but it reports an error; Reverse for 'delete_order' with no arguments not found. 1 pattern(s) tried: ['orderbook/(?P[0-9]+)/delete/\Z']and and not what the problem is. class Order(models.Model): CHOICES = (("BUY", "BUY"), ("SELL", "SELL")) _id = ObjectIdField() profile = models.ForeignKey(Profile, on_delete=models.CASCADE) position = models.CharField(max_length=8, choices=CHOICES, default="BUY") status = models.Field(default="open") price = models.FloatField() quantity_max_insert = models.FloatField() datetime = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse("exchange:orderbook", kwargs={"_id": self._id}) view class DeleteOrder(DeleteView): model = Order success_url = "/" def get_queryset(self): queryset = super().get_queryset() return queryset.filter(profile_id=self.request.user) <div class="container"> <div class="row row-cols-2"> {% for orders in page.object_list %} <div class=" col"> <div class ="card my-1 border border-info mb-3 "> <div class="card-header bg-info"> <h5>{{ orders.profile.user.email }}</h5><p class="text-dark mb-0">{{ orders.datetime|date:"M d Y H:m:s" }}</p> {% if orders.status == 'open' and request.user == orders.profile.user %} <p>{{ orders.id }} <a href="{% url 'delete_order' %}">Delete</a> {% endif %} </div> -
Microsoft Azure - how to locate ML models
I have been writing Python for a number of years and I'm at a fairly decent level. I have never formally studied Computer Science. I have been reading about and using Azure Cognitive Services for one of my applications which uses the Microsoft Azure Cognitive Service' textanalytics service for Language Detection based on text input. As per my understanding Microsoft (MS) has trained some powerful ML models that are used for their cognitive services package. I understand that all the code is open source: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics And I am able to do some basic navigation through the SDK documentation and repo to solve my purpose. However, I want to understand that if Microsoft does use a ML model for the text analytics service or any other cognitive service where is the actual model saved in the repository. While navigating the repository I was expecting to find a call to some sort of serialized file (eg .pkl, .yaml) which loads the model and makes a prediction / returns an output. However, for the life of me, after spending a couple of hours I am lost in this massive repo with no results. To make it easier, I'd be interested to know where … -
What is the difference between default LoginView and creating my own form with authentication in Django? One works, the other doesn't with LDAP
I ask this because I use ldap to authenticate users. A user logs in with the default Django LoginView and in the back ldap does all the checks and it works. However, if instead I customize my own login method with authentication, it no longer works. I know my login method is correct because it works in applications without ldap. So I wonder what are these differences... To be more precise... here are the two examples: 1)This is my customized method: def login_page(request): login_data = LoginForm() return render(request, 'login.html', {'login_data':login_data}) def login_validate(request): login_data = LoginForm(request.POST) if login_data.is_valid(): user = auth.authenticate(username=request.POST['username'], password=request.POST['password']) if user is not None: if user.is_active: auth.login(request, user) return redirect('/') error_message= 'Incorrect password / username. Try again.' return render(request, 'login.html', {'login_data':login_data,'login_errors':error_message}) error_message= 'Internal error. Please contact the administrator.' return render(request, 'login.html', {'login_data':login_data,'login_errors':error_message}) It doesn't work with ldap... however if instead I choose 2)Default login: def login(request): return LoginView.as_view(template_name='login.html')(request) it works with ldap ...both work in applications without ldap.. so what is the difference between both. I don't show the ldap set up but is the default installation of django-ldap. What makes LoginView special in this case? If there are differences, then how do I customize my own login … -
running background task in django
I am working on a pyaudio app in django. I want to run the stream as a background function until I end the stream intentionally from the frontend. below is my views.py. from django.shortcuts import render from .models import Account import pyaudio import socket import select def start_stream(request): var = request.POST['id'] streaming = False if var == "start": streaming = True FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 CHUNK = 4096 audio = pyaudio.PyAudio() serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) if streaming: serversocket.bind(('', 4443)) serversocket.listen(5) def callback(in_data, frame_count, time_info, status): for s in read_list[1:]: s.send(in_data) return (None, pyaudio.paContinue) # start Recording stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK, stream_callback=callback) read_list = [serversocket] print("streaming...") while streaming: readable, writable, errored = select.select(read_list, [], []) for s in readable: if s is serversocket: (clientsocket, address) = serversocket.accept() read_list.append(clientsocket) print("Connection from", address) else: data = s.recv(1024) if not data: read_list.remove(s) serversocket.close() # stop Recording stream.stop_stream() stream.close() audio.terminate() print("finished streaming") return None def server(request): return render(request, 'server.html') I rendered template with the server function in my views.py and used htmx from the frontend to call the start_stream endpoint which then calls the start_stream fucntion in my views.py. This … -
How to find out the client browser type in Django?
I am trying to display a message telling the user to use Google Chrome or Firefox, but I want this message to appear only if they are using Internet Explorer. How can I find out what kind of browser a user has? I know the http request contains such information (the request header). But how do I get this information in Django? -
How do i access cookie in the django model?
After Login in Django Admin popup appeared in which we have to select a database and it will store in the cookie . Here problem Come How do I get database from the cookie and set on the django model? -
Django app w/Python and JS: Alert modal is not produced when user does not apply search filters to jqGrid
Below I have some python logic for a Django view that takes the search_query and checks if the data the user wants to download has had filters applied, to prevent them from downloading all database records for every page of the grid. The code does reach return JsonResponse; I have checked that. However, the corresponding JS function does not produce the alert modal. There is another piece of js code adjacent to my if(gridData["export_Error"] does produce a modal for a separate gridData value, but why would mine not be working? It seems to attempt to produce the exported CSV instead of stopping to show a modal filters = search_query['filters'][0] filter_list = filters.split('[')[1] list_fields = re.findall("\{(.*?)\}", filter_list) no_search = False for search_filter in list_fields: filter_data = search_filter.split(':')[-1] if filter_data not in ['"2"', '""', '"any"']: break no_search = True if no_search: data = { "export_error": "Results must be filtered before exporting. If you need large exports, " "please contact Production Bioinformatics team." } return JsonResponse(data, safe=False) JS script for producing modal loadComplete: function(gridData){ $('#jqGrid').jqGrid('setGridParam', {postData:{download:false}}); $(function(){ $(".toggle_search").attr("disabled", false); }); $(".overlay").hide(); if(gridData["export_error"]){ showAlertModal("Error", griData["export_error"]); } -
It work for me, yout need change the LANGUAJE CODE IN the settings.py
In django, you need change the language in you setting.py like that: LANGUAGE_CODE = 'es-PE' i'm from Perú. -
Partial update on boolean fields in Django not updating the field in Database
I'm trying to update boolean fields using PATCH request and partial-update in DRF. However, only the name field gets updated and not the others Model: class UserModel(): name = models.CharField(max_length=64) enabled = models.BooleanField(default=False) admin = models.BooleanField(default=False) Serializer class UserSerializer(): class Meta: model = UserModel fields = ( 'id', 'name', 'enabled', 'admin' ) read_only_fields = ('id',) View and function class UserView(): def get_queryset(self): return User.users.for_company(company=self.request.company.pk) def get_serializer_class(self): return UserSerializer def update(self, request, id): try: instance = self.get_queryset().get(id=id) except User.DoesNotExist: return Response('User not in DB', status=status.HTTP_404_NOT_FOUND) if 'name' in request.data and self.get_queryset().filter(name=request.data['name']).exists(): return Response('Duplicated user name', status=status.HTTP_400_BAD_REQUEST) serializer = self.get_serializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) Url urlpatterns = [ url(r'^(?P<id>${uuid})/$', UserView.as_view( {'patch': 'update'}), name='user-update') ] Currently if I send a PATCH request with a user_id and the following data in the body, ONLY the name field gets updated in the DB. name = user2 enabled = True admin = True However if I change the update method as follows, the DB gets updated correctly def update(self, request, id): try: instance = self.get_queryset().get(id=id) except User.DoesNotExist: return Response('User not in DB', status=status.HTTP_404_NOT_FOUND) if 'name' in request.data and self.get_queryset().filter(name=request.data['name']).exists(): return Response('Duplicated user name', status=status.HTTP_400_BAD_REQUEST) serializer = self.get_serializer(instance, data=request.data, partial=True) if 'enabled' or 'admin' … -
setup crontab with docker in django
I'm want to run a cron job and I have a docker envrioment but unfortunately the corn is not working. Dockerfile FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # COPY ./core /app WORKDIR /app EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts RUN pip install --upgrade pip COPY requirements.txt /app/ RUN apt-get update && apt-get install -y cron && service cron start && \ pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts USER app CMD ["/scripts/run.sh"] settings.py INSTALLED_APPS = ( 'django_crontab', ... ) # Cron Jobs CRONJOBS = [ ('* * * * *', 'projects.cron.notifications_cron', '>> /var/log/cron.log') ] cron.py: def notifications_cron(): print("hello from cron") when I check cron status in my docker container so it throws me following error: app@40e4b7a671cd:/app$ service cron status cron is not running ... failed! python manage.py crontab show app@40e4b7a671cd:/app$ python manage.py crontab show Currently active jobs in crontab: 822cc1d53a9bdce5e2b3a94a98bdb284 -> ('* * * * *', 'projects.cron.notifications_cron', '>> /var/log/cron.log') I'm unable to figure out what's the issue -
Django mptt filters children
I'm building an eCommerce website that has categories and sub-categories. I'm using the Django MPTT model for the categories. I want to add the children of the category while filtering the category and when filtering the children only the children to get filtered. Here's the filtering process I tried: views.py def categoryview(request): category = Category.objects.all() return render(request, 'products/category.html', {'category':category}) def filteredproducts(request, slug): category = Category.objects.get(slug = cat_slug, is_active =True) products = Products.objects.filter(category = category, is_active = True).order_by('-created_on') return render(request, 'products/filteredproducts.html', {'products': products}) models.py class Category(MPTTModel): category = models.CharField(max_length = 255) cat_slug = models.SlugField(max_length = 255, unique = True, default = 'random') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class Meta: unique_together = ('cat_slug', 'parent') verbose_name_plural = "categories" def __str__(self): return self.category -
using Django views Queries in graphene resolvers
how can i use my django view qureies in graphene resolvers as queries def get_queryset(self): return CustomerModel.objects.for_entity( entity_slug=self.kwargs['entity_slug'], user_model=self.request.user ).order_by('-updated') i trie this it did not work class CustomerList(DjangoObjectType): """testing API """ class Meta: model = CustomerModel fields = ("email",) class CustomerQuery(graphene.ObjectType): all_customers = graphene.List(CustomerList) def resolve_all_customers(self, root, **kwargs): return CustomerModel.objects.for_entity.filter( entity_slug=self.kwargs['entity_slug'], user_model=self.request.user ).order_by('-updated') i get this graphql error { "errors": [ { "message": "'NoneType' object has no attribute 'kwargs'", "locations": [ { "line": 2, "column": 3 } ], "path": [ "allCustomers" ] } ], "data": { "allCustomers": null } } -
Heroku - Django - the application loading process fails
I've been browsing all the options and advice on the internet for 14 days and I can't help it, please help me how to run a properly installed application on Heroku? I'm creating an application on Windows10 and I can't run "gunicorn" there locally, unfortunately, how do I debug or where am I making a mistake...? 2022-03-08T17:05:18.069332+00:00 heroku[web.1]: State changed from up to crashed 2022-03-08T17:05:18.091002+00:00 heroku[web.1]: State changed from crashed to starting 2022-03-08T17:05:17.994885+00:00 heroku[web.1]: Process exited with status 1 2022-03-08T17:05:24.550895+00:00 heroku[web.1]: Starting process with command gunicorn final_sda_project.wsgi --log-file - 2022-03-08T17:05:26.835207+00:00 heroku[web.1]: State changed from starting to up 2022-03-08T17:05:26.291724+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [4] [INFO] Starting gunicorn 20.1.0 2022-03-08T17:05:26.292294+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [4] [INFO] Listening at: http://0.0.0.0:12794 (4) 2022-03-08T17:05:26.292350+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [4] [INFO] Using worker: sync 2022-03-08T17:05:26.296152+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [9] [INFO] Booting worker with pid: 9 2022-03-08T17:05:26.399828+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [10] [INFO] Booting worker with pid: 10 2022-03-08T17:05:26.442367+00:00 app[web.1]: [2022-03-08 17:05:26 +0000] [11] [INFO] Booting worker with pid: 11 2022-03-08T17:05:27.924052+00:00 app[web.1]: [2022-03-08 17:05:27 +0000] [11] [ERROR] Exception in worker process 2022-03-08T17:05:27.924073+00:00 app[web.1]: Traceback (most recent call last): 2022-03-08T17:05:27.924074+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-03-08T17:05:27.924074+00:00 app[web.1]: worker.init_process() 2022-03-08T17:05:27.924075+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in … -
django "StringRelatedField.to_internal_value() must be implemented for field " error
I have a model for a "gym", and a model for a "workout": class Gym(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) def __str__(self): return self.name class Workout(models.Model): gym = models.ForeignKey(Gym, on_delete=models.CASCADE) time = models.DateTimeField() I will also show the 'WorkoutSerializer': class WorkoutSerializer(serializers.ModelSerializer): gym = serializers.StringRelatedField() class Meta: model = Workout fields = ['gym','time'] as you can see, gym is represented in the workout json as a string of the field 'name'. here is the view for workout: @api_view(['GET','POST']) def workout_list(request): if request.method == 'GET': queryset = Workout.objects.select_related('gym').all() serializer = WorkoutSerializer(queryset, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = WorkoutSerializer(data=request.data) serializer.is_valid(raise_exception=True) # rasis 400 bad request if needed serializer.save() return Response('ok') when I try to test a POST request with (I want to use the gym's str representation in POST as well): { "gym": "gym 2", "activity": "Yuga", "time": "2022-03-07T06:00:00Z", "participants": [ "Anna Boing" ] } I get the error: StringRelatedField.to_internal_value() must be implemented for field any idea why, and what can I do to fix this? -
how to create a hyperlink in matched results in Django search autocomplete trevoreyre
I am using autocomplete trevoreyre to handle autocomplete function in my search bar. For now, the user is redirected to the search_result page when clicking enter or search icon. The problem is that even if a suggestion appears user must click on title then click enter or search icon, then the function will redirect him to the search_results page, and then user can click on a card that is interested in. I'd like to extend this feature and create a hyperlink in title suggestions so if the user clicks on the title suggestion then the function should redirect the user directly to DetailedView page. I know that I should follow this logic: onSubmit: result => { window.open(`${wikiUrl}/wiki/${ encodeURI(result.title) }`) } but I am not sure how to create a link to DetailView pages if there are 3 models in my Django app and these models have different URLs. I want to add something like onclick event so when the user clicks on suggestion then it will redirect him to the DetailView page but if clicks enter or search icon it will redirect him to the search_result page. base.html <button onclick="openSearch()"><i class="fas fa-search fa-sm"></i></button> <form action="{% url 'search_result' %}" method="get" id="search"> … -
How to auto save data every month?
CentreInvoice model: class CentreInvoice(core_models.TimestampedModel): centre = models.ForeignKey(Centre, null=False, on_delete=models.CASCADE, related_name="c_centre_invoice") rcl_share_amount = models.FloatField(null=True) total_billed_amount = models.FloatField(null=True) start_date = models.DateField() end_date = models.DateField() paneluser = models.ForeignKey("panel.PanelUser", related_name="c_invoice_creator", on_delete=models.DO_NOTHING) invoice_no = models.CharField(max_length=255) total_advance_payment = models.FloatField(default=0) I am using this model to generate invoices in my project. I need to save this manually everytime, but I want it to happen automatically every month. Is there a way to do this? Any advice would be appreciated.