Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to perform update method on writable Nested serializers in django
models.py class Product(models.Model): product_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) product_name = models.CharField(unique=True,max_length=255) class Client(models.Model): client_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name='org',null=True) product = models.ManyToManyField(Product,related_name='product') client_name = models.CharField(unique=True,max_length=100) .... serializers.py class Clientpost_Serializers(serializers.ModelSerializer): billing_method = Billingmethod_Serializers() product = Product_Serializers(many=True) def create(self, validated_data): billing_method_data = validated_data.pop('billing_method') product_data = validated_data.pop('product') billing_method = Billing_Method.objects.create(**billing_method_data) validated_data['billing_method'] = billing_method client = Client.objects.create(**validated_data) product = [Product.objects.create(**product_data) for product_data in product_data] client.product.set(product) return client def update(self, instance, validated_data): billing_method_data = validated_data.pop('billing_method') billing_method = instance.billing_method # product_data = validated_data.pop('product') # product = instance.product instance.currency = validated_data.get('currency', instance.currency) instance.currency_type = validated_data.get('currency_type', instance.currency_type) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.description = validated_data.get('description', instance.description) instance.street_address = validated_data.get('street_address', instance.street_address) instance.city = validated_data.get('city', instance.city) instance.state = validated_data.get('state', instance.state) instance.country = validated_data.get('country', instance.country) instance.pincode = validated_data.get('pincode', instance.pincode) instance.industry = validated_data.get('industry', instance.industry) instance.company_size = validated_data.get('company_size', instance.company_size) instance.client_name = validated_data.get('client_name', instance.client_name) instance.contact_no = validated_data.get('contact_no', instance.contact_no) instance.mobile_no = validated_data.get('mobile_no', instance.mobile_no) instance.email_id = validated_data.get('email_id', instance.email_id) instance.client_logo = validated_data.get('client_logo', instance.client_logo) instance.client_code = validated_data.get('client_code', instance.client_code) instance.save() billing_method.billing_name = billing_method_data.get('billing_name', billing_method.billing_name) billing_method.description = billing_method_data.get('description', billing_method.description) billing_method.save() # product.product_name = product_data.get('product_name', product.product_name) # product.save() product_data = validated_data.pop('product', []) instance = super().update(instance, validated_data) for products_data in product_data: product = Product.objects.get(pk=products_data.get('product_id')) product.product_name = products_data.get('product_name', product.product_name) instance.product_data.add(product) instance.save() return instance When … -
Django makemirgations not updating database
When I make changes to models.py, I am expecting django to update the database structure for me when I run python3 manage.py makemigrations or python3 manage.py makemigrations appname. It doesn't detect any changes. I have had this issue once before and had to delete everything in the database to update it, which seems a bit drastic. What am I doing wrong? This is the new line I have just added: l3_interfaces = JSONField (py38-venv) [xxxxxx@xxxxxxn]$ python3 manage.py makemigrations No changes detected Contents of models.py from django.db import models #Generic for models from django.contrib.auth.models import User #Required for dynamic user information from django.forms import ModelForm #Custom form from jsonfield import JSONField #Unique order. Top of heirachy tree class Order(models.Model): order_name = models.CharField(max_length=100, unique=True)#, null=True, blank=True) #Unique name of order created_by = models.ForeignKey(User, related_name='Project_created_by', on_delete=models.DO_NOTHING) #Person who created the order created_at = models.DateTimeField(auto_now_add=True) #Date/Time order was created def __str__(self): return self.order_name #For CE router definition. Required for all orders. class Ce_Base(models.Model): #Hardware models of router ROUTER_MODELS = ( ('CISCO2901', 'CISCO2901'), ('ISR4331', 'ISR4331'), ('CISCO1921', 'CISCO1921'), ('ISR4351', 'ISR4351'), ('ISR4451', 'ISR4451'), ('ISR4231', 'ISR4231'), ('ISR4431', 'ISR4431'), ('ISR4461', 'ISR4461'), ) #Available regions in which the router can reside. REGION = ( ('1', '1'), ('2', '2'), ('3', '3'), … -
Show different pages based on user - django
I'm building a web app IMDB's like. Each (logged) user views the same exact homepage, but they can flag/unflag every movie they want to save them in a "seen list". I've done that but I've noticed that every user logged can view the other user's flagged movies. Of course this is a problem, so I'd like to build a page relative to each user, so that everyone would have different "seen films" page based on the movies flagged as seen. The main idea behind this, is that whenever a user adds a movie to the database, he can flag it as seen with a simple models.BooleanField in the model of the film. I have then another model "Seen" where there are all the movies flagged. models.py class Films(models.Model): ... seen = models.BooleanField(default=False) class Seen(models.Model): ... views.py films = Films.objects.all() for film in films: flag = 0 seen_films = Seen.objects.all() for _ in seen_films: if film.name == _.name: flag = 1 break if not flag and film.seen: act_seen = Seen(image=film.image, name=film.name, description=film.description) act_seen.save() I need to add that for the user, I use the default class provided by django: from django.contrib.auth.models import User I get that the error is everyone can … -
django/mysql table not found - django.db.utils.ProgrammingError: (1146, "Table 'trustline.authentication_user' doesn't exist")
i was trying to "makemigrations" for my project but whenever i do this, i got this error django.db.utils.ProgrammingError: (1146, "Table 'trustline.authentication_user' doesn't exist" and i have this line in settings.py AUTH_USER_MODEL = "authentication.User" here's the full error 1 2 -
Django admin - default value into a field via the filter selection
I'm trying to make a default value in my table via my selections in django admin. For example, I have 2 tables: model.py class Year (models.Model): year = models.IntegerField(primary_key=True, verbose_name='Year') def __str__(self): return str(self.year) class RFCSTForm (models.Model): id = models.AutoField(primary_key=True) year = models.ForeignKey(Year, verbose_name='Year', null=True, blank=True, on_delete=models.CASCADE) Then when I wanna create a new RFCSTForm and select via year's filters the value "2022", I want the field year will be filled by default with this value. is it possible in django model? -
display:'block' is not working as it supposed to be
I want the table to be visible only after the submit button clicks. But It's not staying on the screen as it is supposed to be. Once I click the submit button, the table comes up for a second and then again becomes invisible. Please let me know what I am doing wrong in my code. Also please let me know if there is any other way to do it. <div style="margin-left: 2rem;"> <input class="btn btn-primary" type="submit" value="Submit" id="btn" onclick="hide()"> </div> <div style="margin-top: 4rem; display: flex; justify-content: center; align-content: center;"> <table style="display: none;" id="table"> <tbody> <tr> <th scope="row">Profile No. : </th> <td>{{ProfileUID}}</td> </tr> <tr> <th scope="row">Name : </th> <td>{{Name}}</td> </tr> </tbody> </table> </div> <script> function hide() { let btn = document.getElementById("btn"); let table = document.getElementById("table"); if (table.style.display === 'none') { table.style.display = 'block'; } </script> -
Selenium authentication without sharing credentials
Isn't it bad to use actual credentials when testing log in pages with selenium webdriver? I am not very sure how security works but if someone is able to access the source code of the program together with its tests, then they would get a dummy test credentials that would still allow them to access the website. How do people go about this? -
Error 500 after 40 sec in Django WEB APP on IIS
I have a web app (DJango/ReactJS) that works perfectly on localhost, but after deploiment on IIS 10 some requests (http post) stops after 30, 40sec with state 500 (u have some inputs then a function gonna treat and calculate then return a resullt). i tried to change the timout in IIS settings but no diffrence ! i checked the logs on IIS, on windows's event viewer but no errors detected ! any sollution ? -
I cannot load the image in my template, I tried changing all upload file location and everything else and its the same with category field
models.py class product(models.Model): categoryChoices=[('food','Food'),('clothing','Clothing'),('books','Books'),('furniture','Furniture'),('others','Others')] product_name=models.CharField(max_length=40) product_decsription=models.CharField(max_length=100) pub_date=models.DateTimeField(auto_now=True) image=models.ImageField(upload_to='CharApp/images/',default='') address=models.CharField(max_length=200, default='') city= models.CharField(max_length=40) station= models.CharField(max_length=40) category= models.CharField(choices=categoryChoices,max_length=30) Views.py def index(request): donations=product.objects.all() return render(request,'CharApp/index.html',{'donations':donations}) Urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.start,name='start'), path('home/',views.index,name='index'), path('upload/',views.productFormView), path('about/',views.about,name='about'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Forms.py class productForm(forms.ModelForm): class Meta: model=product fields='all' widgets= { 'product_name': forms.TextInput(attrs={'class':'form-control'}), 'product_decsription': forms.TextInput(attrs={'class':'form-control'}), 'pub_date': forms.DateInput(attrs={'class':'form-control'}), 'image': forms.FileInput(attrs={'class':'form-control'}), 'address': forms.TextInput(attrs={'class':'form-control'}), 'city': forms.TextInput(attrs={'class':'form-control'}), 'station': forms.TextInput(attrs={'class':'form-control'}), 'category': forms.Select(attrs={'class':'form-control'}), I tried chnaging the img src call to a d.image.url call,and alot of other things it just doesnt load, its the same with category field, the view just doesnt load these two fields even tho they are available in the database -
How long class attributes live in python (Django)
I have this class in my Django app: class MyClass: property_1 = [] def add_elem(self): self.property_1.append(1) print(self.property_1) MyClass().add_elem() MyClass().add_elem() The output will be: [1] [1, 1] That means that when I start Django server, all the scripts(all app) are loaded to memory and as property_1 is a class attribute, every time I call add_elem(), I add a new '1' to the property? And property_1 will be cleaned only after restart server? -
Error H12 Heroku with Django bot scraping app
I have a bot made in Django and I want to run it on Heroku. The project's HTML template opens in Heroku just fine. This template has a form and a submit button. When I press the button, what is written in the form is sent to the main function of the bot and uses it during scraping. The problem is that the bot takes about 4 minutes to perform the functions and the Heroku router only executes requests for 30 seconds. I have searched for a thousand solutions on the internet but no matter how much I apply one after another I can't find it. I have also contacted Heroku support and they told me that I can use New Relic for long-runninf actions and use a background worker as well. I've tried setting both and I can't get around the H12 error either. Could someone tell me how to configure the worker and New Relic correctly? Many answers I find with this are old or I can't optimize it for my project. Thank you. (Sorry for my english btw) worker.py import urllib from redis import Redis from rq import Queue, Connection from rq.worker import HerokuWorker as Worker listen … -
How to loop through all the rows inside the list
I'm trying to iterate through the list of JSON, it just iterate only the first row How could I able to loop through all the rows inside the list This is my payload in browser [{AuditorId: 10, Agents: Joshi", Supervisor: Prabhu", TicketId: "R6726587",…},…] 0: {AuditorId: 10, Agents: Joshi", Supervisor: Prabhu", TicketId: "R6726587",…} 1: {AuditorId: 10, Agents: Joshi", Supervisor: Prabhu", TicketId: "R6726587",…} 2: {AuditorId: 10, Agents: Joshi", Supervisor: Prabhu", TicketId: "R6726587",…} 3: {AuditorId: 10, Agents: Joshi", Supervisor: Prabhu", TicketId: "R6726587",…} 4: {AuditorId: 10, Agents: Joshi", Supervisor: Prabhu", TicketId: "R6726587",…} here, what I tried @api_view(['POST']) def UserResponse(request): if request.method == 'POST': for ran in request.data: auditorid =ran.get('AuditorId') ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = ran.get('SID') TicketType = ran.get('TicketType') TypeSelected = ran.get('TypeSelected') agents = ran.get('Agents') supervisor = ran.get('Supervisor') Comments = ran.get('Comments') action = ran.get('Action') subfunction = ran.get('AuditSubFunction') region = ran.get('AuditRegion') Qstans = str(qid)+'|'+ answer+'&&' cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@agents=%s,@supervisor=%s,@ticketid=%s,@Qstans=%s,@sid=%s,@TicketType=%s,@TypeSelected=%s, @Comments =%s, @action=%s, @subfunction=%s, @region=%s', (auditorid,agents,supervisor,ticketid, Qstans,sid, TicketType, TypeSelected, Comments, action, subfunction,region)) result_st = cursor.fetchall() for row in result_st: return Response({0:row[0]}) -
AttributeError: 'Manager' object has no attribute 'filters'
When running Student.objects.filters(years_in_school=FRESHMANN), I get following Error Message: AttributeError: 'Manager' object has no attribute 'filters' class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' YEAR_IN_SCHOOL_CHOICES = [ (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), (GRADUATE, 'Graduate'), ] year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) # Returns True, if the Objects "year_in_school" equals JUNIOR or SENIOR. def is_upperclass(self): return self.year_in_school in {self.JUNIOR, self.SENIOR} I done makemigrations and migrate already. I have created two objects of Class Student: running Student.objects.all() return me: <QuerySet [<Student: Student object (1)>, <Student: Student object (2)>]>. In Django Admin I created the mentioned objects, one has its property "year_in_school" assigned to "FRESHMAN". Unable to filter the objects by "year_in_school". Why and whats the fix? -
Content-Disposition "inline" --> filename ignored?
I create a HTTPResponse like this (Django): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="foo.pdf"' response.write(response_data) return response Why does the browser ignore the filename "foo.pdf"? -
How to handle multiple lists with get_or_create in python?
At my Django application, I have a celery task that imports objects from an S3 Bucket. To make sure that I don't import objects twice, I use get_or_create, please also see the corosponding code: ... for key in keys: files_obj, created = Files.objects.get_or_create(file_path=key, defaults={'file_name': Path(key).name, 'libera_backend': resource_object}) if created: files_obj_uuids.append(files_obj.pk) resource_objects.append(resource_object.pk) if not files_obj_uuids and not resource_objects: print("No new objects found, everything already imported.") else: print(f'{len(files_obj_uuids)} new objects found. Importing now!') # Building-up task-group try: group([extract_descriptors.s(resource_object, key, files_obj_uuid) for (resource_object, key, files_obj_uuid) in zip(resource_objects, keys, files_obj_uuids)]).delay() return "Import jobs started" As you can see, I first fetch all objects (keys), then I check if the object already exists at the Database using get_or_create. If not I append files_obj and resource_object each to a seperate list. Later on I build a group task where I pass over resource_object, key and files_obj_uuid. At the extract_descriptors tasks I call with these parameters, the actuall error occours: django.db.utils.IntegrityError: (1062, "Duplicate entry 'some_uri/some_file_123' for key 'App_files_descriptor_080cec4f_uniq'") please also see the corosponding code: ... if json_isvalid: try: Files.objects.filter(pk=files_obj).update(descriptor=strip_descriptor_url_scheme(descriptor)) To get a better understanding please dont focus on the "descriptor" here. Its a unique helper field I need for a headless celery tasks that runs in the … -
Save many-to-many relationship after use the add() method on the field to add a record
I have models Book and I want to save new record this book after every update information about this book (duplicate information). It works good, but I don't know how to store many-to-many relationship. Wherein, I want that main book don't save in database, only duplicate information in database models.py class Book(models.Model): slug = models.SlugField(max_length=255) title = models.CharField(max_length=255) author = models.ForeignKey( "Author", on_delete=models.SET_NULL, null=True, blank=True, related_name="author_book", ) abstract = models.TextField() coauthor_book = models.ManyToManyField("Author", blank=True, related_name="coauthor_book") subject = ManyToManyField("Subject") forms.py class BookForm(forms.ModelForm): class Meta: model = Article fields = "__all__" views.py class BookUpdateView(UpdateView): model = Book form_class = BookForm template_name = "book/book_update.html" def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): obj = form.save(commit=False) obj.editor = self.request.user coauthors = obj.coauthor_book subjects = obj.subject draft = Book.objects.create( title=obj.title, author=obj.author, abstract=obj.abstract, slug=obj.slug, ) draft.save() # My triying. But It doesn't work for coauthor in coauthors.all(): draft.coauthor_book.add(coauthor) for subject in subjects.all(): draft.subject.add(subject) return redirect("book", obj.slug) return self.render_to_response({"form": form}) -
Django not saving datetime from input
If I set USE_TZ = True I get an error "DateTimeField received a naive datetime while time zone support is active" . After changing it to False when I try to submit from my pc it works but submitting from other devices(my phone) doesn't work. Can anyone help? Template : <label class="form-label">Submission Ends:</label><input type="datetime-local" id="lastdate" name="lastdate" required> views : lastdate= request.POST['lastdate'] homework= Homework(code=code,title=title,description=description,lastdate=lastdate) homework.save() settings.py : LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = False USE_TZ = False -
im trying to add a response with the full body of the car model but want to only adjust 1 field in the same view which is the car.collection
enter code here basically i want to add 2 functions .. add to collection, remove from collection , while having the full body of the car object in response but only adjust the collection relation field serializers class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ['id', 'model', 'maker', 'release_year', 'vin', 'owner', 'collection'] def update(self, instance, validated_data): instance.collection = validated_data.get('collection', instance.collection) return instance class CarCollectionSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ['id', 'collection'] class CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collection fields = ['id', 'name', 'created_at'] models class Collection(models.Model): name = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}" class Car(models.Model): model = models.CharField(max_length=40) maker = models.CharField(max_length=60) release_year = models.IntegerField() vin = models.CharField(max_length=100) owner = models.ForeignKey(User, on_delete=models.CASCADE, default=None) collection = models.ManyToManyField(Collection) def __str__(self): return f"{self.model}" views class CarViewSet(viewsets.ModelViewSet): """ A simple ViewSet for listing or retrieving cars. """ queryset = Car.objects.all() serializer_class = CarSerializer permission_classes = [IsAuthenticated, IsCarOwner] filter_backends = (filters.DjangoFilterBackend,) filter_class = CarFilter filter_fields = ('maker', 'release_year', 'vin') ordering_fields = 'release_year' @action(detail=True, methods=['GET', 'Put']) def update_car_collection(self, request, pk=None, format=None): car = Car.objects.get(pk=pk) collection = Collection.objects.get(pk=pk) serializer = CarCollectionSerializer(car, request.data) if serializer.is_valid(): serializer.save() car.collection = serializer.data.get(collection, car.collection) return Response(serializer.data) -
How to get the value of a form in html to django
<form action="{% url 'search' %}" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> How can I get the value of q to views.py def search(request): return render(request, "encyclopedia/search.html") Should I make it a post request instead of a get and then take the value. Help me plz -
How can I make my form page resposive design in Django?
I have a form page with Django 1.11.10. I want to desing it responsive for all screen sizes. In phones and tabletes I want to not need to zoom in. Here is my html : {% extends 'base.html' %} {% load bootstrap3 %} {% block content %} <div class="form-body"> <div class="row"> <div class="form-holder"> <div class="form-content"> <div class="form-items"> <div class="row"> <div class="col-xs-11"> <h1>WARRANTY REGISTRATION</h1> <br><br> <form class="requires-validation" method="POST" novalidate> {% csrf_token %} {{form.as_p}} <div class="form-button"> <button id="submit" type="submit" class="btn btn-primary">Register</button> </div> </form> </div> </div> </div> </div> </div> </div> </div> {% endblock %} -
How to validate foreign key with APIView
I'm learning django rest framework at school and now I'm on a internship project, I have some doubts using API base View. I want to do a POST in a endpoint and validate if the foreign key exists or not. My models: # TABELA DOS FORNECEDORES class Fornecedor(models.Model): nome = models.CharField(max_length=100, null=False, blank=False) endereco = models.CharField(max_length=100, null=False, blank=False) codigo_postal = models.CharField(max_length=8, null=False, blank=False) cidade = models.CharField(max_length=50, null=False, blank=False) nif = models.IntegerField( null=False, blank=False, unique=True, validators=[ RegexValidator(r"[1-9]\d*"), MinLengthValidator(9), MaxLengthValidator(9), MaxValueValidator(999999999), MinValueValidator(1), ], ) email = models.EmailField(max_length=50, null=False, blank=False) data_registo = models.DateTimeField(auto_now_add=True) data_ultimo_login = models.DateTimeField(auto_now=True) ativo = models.BooleanField(default=True, null=False, blank=False) def __str__(self): return self.nome # TABELA DAS MARCAS class Marca(models.Model): nome = models.CharField(max_length=55, null=False, blank=False) fornecedor = models.ForeignKey( Fornecedor, on_delete=models.CASCADE, null=False, blank=False ) def __str__(self): return self.nome My serializers class FornecedorSerializer(serializers.ModelSerializer): class Meta: model = Fornecedor fields = "__all__" class MarcaSerializer(serializers.ModelSerializer): class Meta: model = Marca fields = "__all__" My views class FornecedorPOST(APIView): @swagger_auto_schema( operation_summary="Criar um Fornecedor", operation_description="Criar um novo Fornecedor", request_body=FornecedorSerializer, responses={ status.HTTP_201_CREATED: response_201(FornecedorSerializer), status.HTTP_400_BAD_REQUEST: response_400(FornecedorSerializer), }, ) def post(self, request, format=None): fornecedor = FornecedorSerializer(data=request.data) if fornecedor.is_valid(): fornecedor.save() return Response(fornecedor.data, status=status.HTTP_201_CREATED) return Response(fornecedor.errors, status=status.HTTP_400_BAD_REQUEST) class MarcaPOST(APIView): @swagger_auto_schema( operation_summary="Criar uma marca", operation_description="Criar uma nova marca", request_body=MarcaSerializer, responses={ status.HTTP_201_CREATED: response_201(MarcaSerializer), status.HTTP_400_BAD_REQUEST: response_400(MarcaSerializer), }, … -
Got stuck in 'grid-template-columns' in CSS
I am currently learning Django and got stuck. I have created 3 divs inside of an home container and written this CSS code for the home container -> <style type="text/css"> .home-container{ display: grid; grid-template-columns: 1fr 3fr 1fr; } </style> I have created 'grid-template-columns: 1fr 3fr 1fr;' but I am not getting a column for the third div(i.e. 1fr). The third div's content is coming below the second div. Here is the whole source code. -> {% extends 'main.html' %} {% block content %} <style type="text/css"> .home-container{ display: grid; grid-template-columns: 1fr 3fr 1fr; } </style> <div class="home-container"> <div> <h3>Browse Topics</h3> <hr> <a href="{% url 'home' %}">All</a> {% for topic in topics %} <div> <a href="{% url 'home' %}?q={{topic.name}} ">{{topic.name}}</a> </div> {% endfor %} </div> <div> {% if room_count != 0 %} <h5>{{room_count}} rooms available.</h5> {% else %} <h5>No rooms available.</h5> {% endif %} <a href="{% url 'create-room' %}">Create Room</a> <div> {% for room in rooms %} <div> {% if request.user == room.host %} <a href="{% url 'update-room' room.id %}">Edit this room</a> <a href="{% url 'delete-room' room.id %}">Delete this room</a> {% endif %} </div> <div> <span>@{{room.host.username}}</span> <h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5> <small>{{room.topic.name}}</small> <hr> </div> {% endfor %} </div> <div> … -
Django: Update a value in html page without refreshing the page
I have a Rest API which I receive data every 10 seconds. I receive the data with time information that when the data sent. So, user should see the soonest data on the page. That code would work but that also wont update the data without a refresh: def get_datas(request): data = //find the soonest data return render(request, 'page.html', {'data': data}) What is the best solution for this? -
Problem fetching an equation from Excel Django
I have an excel file with a simple math equation In cell C1 it is A1 + B1 and I want to fetch the result of C1 in Django but it returns me nan...... is there a way to solve this problem? I use the pandas library! -
Django RQ ModuleNotFoundError xxx is not a package
I'm using django rq for some long running task, which I would like to provide some feedback about its progress. I hence created a function which is enqueued as a new task and set some model's attribute and save them. Here is a simplified view: class Status(models.Model): progress_a = models.PositiveIntegerField(default=0) class MyObject(models.Model): status = models.OneToOneField(Status) @django_rq.job('low-short') def set_status(self, progress_name, progress): setattr(self.status, progress_name, progress) self.status.save() def set_status_a(self, progress): self.set_status.delay(self=self, progress_name="progress_a", progress=progress) @django_rq.job('default') def long_running_job(): my_instance.set_status_a(100) Now, executing this give me the following output : 2022-05-16 15:50:03 app-85c8459c79-mrkhg rq.worker[1] INFO low-short: api.models.MyObject.set_status(progress=0, progress_name='progress_a', self=<MyObject: MyObject object (129)>) (c13480ca-a25b-4463-af9a-a0a0dd67de61) 2022-05-16 15:50:03 app-85c8459c79-mrkhg root[41] WARNING Import error for 'api.models.MyObject' Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/rq/utils.py", line 141, in import_attribute module = importlib.import_module(module_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 981, in _find_and_load_unlocked ModuleNotFoundError: No module named 'api.models.MyObject'; 'api.models' is not a package api is a package api.models a module models.MyObject a class. I don't get why it doesn't work. What am I doing wrong ? long_running_job starts as a job flawlessly. Note: when removing self=self, it complains about missing self.