Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django throws an error: LookupError: No installed app with label 'admin'
Today after installing django-cryptography for encrypting all fields in my models using this website, this error is keep showing on my terminal after running python manage.py runserver: File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\ADAMUDEE\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\ADAMUDEE\Desktop\school\project\school\urls.py", line 23, in <module> path('admin/', admin.site.urls), File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\utils\functional.py", line 266, in inner self._setup() File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\contrib\admin\sites.py", line 595, in _setup AdminSiteClass = import_string(apps.get_app_config("admin").default_site) File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\apps\registry.py", line 165, in get_app_config raise LookupError(message) LookupError: No installed app with label 'admin'. I try to solve it using these answer in this question, but no one works, I also deleted sqlite in my project folder … -
How to get different names in request.post method
I got a problem, I'm making a web for SQLServer Agent Jobs execution, where if my job got parameters it redirects me to another page where I can enter my parameters. My problme is submiting these parameters. I don't know how to send all the parameters from my html to my view.py. All inputs have different names and I really don't know how to make the request accept different input names. I'll add some code below. IM commenting the line where I have the problem parameters.html <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %} Parametros {% endblock %}</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> </head> <div class="container"> <div class="row"> <div class="col-md-4 offset-md-4"> <br><br> <div class="card"> <div class="card-header"> <h3>Parámetros</h3> </div> <div class="card-body"> <form method="post"> {% csrf_token %} {% for i in parameters %} <!-- Parameters input --> <div class="form-outline mb-4"> <label class="form-label" for="form2Example1">{{ i.parameter_name }}</label> {% if i.parameter_type == 'Int' %} <input type="number" id="form2Example1" class="form-control" name="int" /> {% else %} {% if i.parameter_type == 'Decimal' %} <input type="text" id="form2Example1" class="form-control" name="decimal" /> {% else %} {% if i.parameter_type == 'String' %} <input type="text" id="form2Example1" class="form-control" name="string" /> {% else %} {% if i.parameter_type == 'Date' %} <input type="date" id="form2Example1" … -
Django filter with Q objects not working or I am doing it wrong
I have this view to check if two users are friends and in this case they are because the logged in user and the author of the blog are indeed friends BUT the model for friendship only works one way and I need to make provision for that, which is why I wrote this function. After all if user1 is friends with user2 then automatically user2 is friends with user1: The friendship model: class Friendship(models.Model): person = models.ForeignKey( User, on_delete=models.CASCADE, related_name="person" ) friend = models.ForeignKey( User, on_delete=models.CASCADE, related_name="friend" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") The serializer method: def get_friends(self, obj): loggedUser = self.context.get('view').kwargs.get('user') post_author = obj.user_id friends = Friendship.objects.filter(Q(person=loggedUser), Q(friend=post_author) | Q(person=post_author), Q(friend=loggedUser)) if friends: return True else: return False Please tell me what I am doing wrong cause it says they are not friends even though they are? -
Using CSV file in Django choices
I have this function that calls the choices and activates them in each Model, however, I would like to know if there is a way to use this CSV file automatically, without having to call it item by item... def Equipe(): with open("controle_pav/static/texto/equipes.csv", 'r') as arquivo: equipes = arquivo.read() EQUIPE = ( ('equipes', equipes.split()[0]), ('equipes', equipes.split()[1]), ('equipes', equipes.split()[2]), ) return EQUIPE Is there a way to use an iterator or something like that. ? I tried to make a router with the for but I was not successful -
In Django I am getting an Integrity Error while testing to create an object
In my Django REST API project I am getting an Integrity Error when I run my tests. models.py class Tag(models.Model): """Tag for filtering recipes.""" name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.name And here is my test that fails: def test_create_tag(self): user = get_user_model().objects.create_user(email="user@example.com",password="password123") tag = models.Tag.objects.create(user=user, name="Tag1") self.assertEqual(str(tag), tag.name) This is the error that I have been getting: Traceback (most recent call last): File "/app/core/tests/test_models.py", line 80, in test_create_tag tag = models.Tag.objects.create(user=user, name="Tag1") django.db.utils.IntegrityError: null value in column "user_id" of relation "core_tag" violates not-null constraint DETAIL: Failing row contains (1, Tag1, null). Why while this test running creates an error? -
How do I ensure that a Foreignkey field is always referenced in a Django model?
I was thinking of creating an instance of a foreignkey field and referring it every time an instance of a model is created, but I didn't find any solution for this. Usually we need to create a model of foreignkey type and then refer to it from the model, but I want it to automatically create one foreignkey instance from the beginning of and always refer to it. To provide an example let's say we've 2 model fields called User and WeeklySchedule. Everytime an instance of a User is created,another corresponding instance of a WeeklySchedule model is also created that will be referred to by the instance of the User. -
djongo query_set with filter on boolean field
I have a django application with djongo as a database driver. My model is simple: from django.db import models from djongo.models import ObjectIdField class TmpModel(models.Model): _id = ObjectIdField() is_deleted = models.BooleanField(default=False) When I run in shell simple filter command: >>> TmpModel().save() >>> TmpModel(is_deleted=True).save() >>> TmpModel.objects.filter(is_deleted=False).all() I got an error: (0.000) QUERY = 'SELECT "solutions_tmpmodel"."_id", "solutions_tmpmodel"."is_deleted" FROM "solutions_tmpmodel" WHERE NOT "solutions_tmpmodel"."is_deleted" LIMIT 21' - PARAMS = (); args=(); alias=default Traceback (most recent call last): File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 116, in __init__ super().__init__(*args) File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 152, in parse self.where = WhereConverter(self, statement) File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\converters.py", line 27, in __init__ self.parse() File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\converters.py", line 119, in parse self.op = WhereOp( File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\operators.py", line 476, in __init__ self.evaluate() File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\operators.py", line 465, in evaluate op.evaluate() File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\operators.py", line 258, in evaluate self.rhs.negate() AttributeError: 'NoneType' object has no attribute 'negate' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 885, in … -
Filtering in DJANGO with OR condition
I have a restfull API created with Django and DRF. When I try to filter with OR condition (), it doesn't detect the condition and return all the objects. I want to make it work by a diferent way other than modifying the "get_queryset" method. I want to find the way to implement some module or backend filter package to implement that filters -
Python Django functions
I tried everything, why my 'POST request' from 'send' function isn't considered in the 'checkview' function ? def send(request): room = request.POST['room_name'] #YAHOO API import yfinance as yf aapl = yf.Ticker(room) ainfo = aapl.history(period='1y') #Plot the Chart import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=ainfo.index,y=ainfo.Close, mode='lines')) #x = fig.show() #DB inject plot rx = str(randint(9999,99999)) fig.write_image("/Users/Xlibidish/Desktop/Django/static/"+room+rx+".png") #DB Inject from send plot_id = str(room+rx) new_message = Message.objects.create(room=plot_id) new_message.save() return HttpResponse('All Good in send') def checkview(self): send(self) chart_id = Message.objects.get(room=plot_id) return JsonResponse(chart_id.room, safe=False) Here is the error: django.utils.datastructures.MultiValueDictKeyError: 'room_name' I ultimately need to transfer through AJAX the plot_id variable. -
How to make each product have functioning plus minus button on my product page and add its price to the total amount?
I'm working on Ecommerce Website that sells Coffee and my problem is that the only working plus and minus button is the first coffee. The plus and minus buttons on the others are not functioning. Is it about the for statement where I'm wrong? or the structure of the html isn't right. I've copied some of the code on cart.html file to make the product page had the option of adding products to the cart and also has a proceed button to the checkout page. The before structure of the site was you click on the image of a product and directed to the addtocart page then to the checkout page. -
Django test factory post with foreign key
I'm trying to test a view-function with django's RequestFactory's post-method. The view-function should create a new ObjA-instance. ObjA has a foreign key field to an ObjB. My test currently looks like this (names changed for better reading): request = self.factory.post('/create-objA/', data={'objB': objB.id, 'field1': 'dummy'}) request.user = self.user request.POST.is_bound = True create_objA(request) self.assertTrue(ObjA.objects.filter(field1='dummy').exists()) objB does exist, this is tested few lines before in the same test function. However the test in the snippet fails. The reason is that in the following create function form.is_valid() is never true: def create_objA(request): if request.method == 'POST': form = ObjAFormCreate(request.POST) if form.is_valid(): .... So the ObjA is not created. Form is not valid because it has an error in the ObjB reference field: Select a valid choice. That choice is not one of the available choices. though objB.id is inside form.data. Question: How should I write the test, so that the form would not have the error? Model: class ObjA(models.Model): id = models.BigAutoField(primary_key=True) obj_b_id = models.ForeignKey(ObjB, on_delete=models.CASCADE) field1 = models.CharField(max_length=10) Form: class ObjAFormCreate(ModelForm): objB = forms.ModelChoiceField(queryset=ObjB.objects.all()) field1 = forms.CharField(max_length=10) -
How can I redirect the user to the form page while keeping some data from the previous page
I am trying to allow customers to place an order for a specific product on my website, and I want to create a button for each product that contain the product's unique id so that I can associate the order with the correct product in admin dashboard. how can I do this? i have displayed the products and i did the order form this is the code I have : models.py: from email.policy import default from unicodedata import name from django.db import models class Product(models.Model): name = models.CharField(max_length=10, null=True) price = models.DecimalField(max_digits=6, decimal_places=0,null=True) description = models.TextField(null=True) image = models.ImageField(upload_to='photos',null=True) productid = models.CharField(max_length=10, null=True) def __str__(self): return self.name class Order(models.Model): product = models.OneToOneField(Product , on_delete=models.PROTECT , null=True) fullname = models.CharField(max_length=10, null=True) phone= models.CharField(max_length=10, null=True) address = models.CharField(max_length=10, null=True) date = models.DateField(blank=True , null=True) views.py: def order(request): name = request.POST.get('name') phone = request.POST.get('phone') address = request.POST.get('address') date = request.POST.get('date') orderdata = Order(fullname = name , phone = phone , address = address , date = date) orderdata.save() return render(request,'order.html') def products(request): products = Product.objects.all() return render(request, 'products.html', {'products':products}) order.html: <section class="content" id="content" name="content"> <div class="row"> <div class="col-75"> <div class="container"> <form method="post"> {% csrf_token %} <div class="row"> <div class="col-50"> <h3>Enter your details</h3> <label … -
redirect to another page for script execution in django
I got a problem, I'm making a web for SqlServer Agent Jobs execution, and I got to type of Jobs, with parameters or without parameters (I added this attribute in my table with a boolean), so if my job got no paremeters executes normally, but if my job got parameters it redirects to another page where I can type the value of the parameters and then execute the job. I got my code byt it returns error "didn't return an Http.Response", can someone please tell me what I'm doing wrong? I'll leave some code below views.py #Job execution def ejecutar(request, job_name): print("Ejecutando el job") cursor = connection.cursor() job = Jobs.objects.get(job_name=job_name) if job.flag_params == 0: cursor.execute("EXEC msdb.dbo.sp_start_job '" + job.job_name + "'") return HttpResponse("""<html><script>alert("Job ejecutado");window.location.replace('/home');</script></html>""") else: #redirects to parameters.html redirect('parameters.html', job_name=job.job_name) if request.method == 'POST': #get job parameters parametros = Parametros.objects.filter(job_id=job.id) for parametro in parametros: #Update parameters in my table cursor.execute("UPDATE Jobs_parametros SET parameter_value='" + request.POST['parameter'] + "' WHERE parameter_name='" + parametro.parameter_name + "' AND job_id='" + str(job.id) + "'") cursor.execute("EXEC msdb.dbo.sp_start_job '" + job.job_name + "'") return HttpResponse("""<html><script>alert("Job ejecutado");window.location.replace('/home');</script></html>""") #Get Job List per User def insertar(request): #get user id who logged in user = Usuarios.objects.get(username=request.session['username']) #get jobs asigned to the … -
Django Api-Key with unit test
I am trying to implement unit tests to an existing project, the existing project uses Api-Key's to access and authenticate against the Api endpoints. if I do the following via postman or command line: curl --location --request GET 'http://127.0.0.1:8000/api/user_db' \ --header 'Authorization: Api-Key REDACTED' \ --header 'Content-Type: application/json' \ --data-raw '{ "username" : "testuser@localhost" }' Everything works great, however when trying to add the Api-Key to the header in Unit tests I receive the following : 'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')} AssertionError: 403 != 200 from rest_framework.test import APITestCase from rest_framework import status from django.urls import reverse import environ env = environ.Env() class GetUserTestCase(APITestCase): def test_get_user_account(self): getdata = { "username" : "testuser@localhost" } response = self.client.get(reverse('users_db'), data=getdata, **{ "HTTP_AUTHORIZATION": f"Api-Key {env('API_KEY')}" }) print(response.data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data["username"],response.data["enc_password"],response.data["oid"]) Also tried with the following items: headers = { 'Authorization': f'Api-Key {env("API_KEY")}', 'Content-Type': 'application/json' } response = self.client.get(reverse('users_db'), data=getdata, headers=headers) AND self.client.credentials(HTTP_AUTHORIZATION=f"Api-Key {env('API_KEY')}") No joy so far, anyone else had this problem and find a way forward? -
How do I link different users to view the page differently?
hi if anyone is familiar with django, i'm working on how different group of users will be able to view different buttons, but i cant seem to make that work; my elif doesn't work, when i'm logged in to employee i'm able to view the buttons but when im logged in the inventory manager i can only view undefined user employee view inventory manager view below are my codes views.py def menu(request): user = request.user is_employee = request.user.groups.filter(name='employee').exists() is_inventorymanager = user.groups.filter(name='inventorymanager').exists() is_financialdirector = user.groups.filter(name='financialdirector').exists() is_vendor = user.groups.filter(name='vendor').exists() return render(request, 'app/menu.html', { 'is_employee': is_employee, 'is_inventorymanager': is_inventorymanager, 'is_financialdirector': is_financialdirector, 'is_vendor': is_vendor }) menu.html (interface) {% extends "app/layout.html" %} {% block content %} <div> <br /> {% if is_employee %} <h2>Employee Menu</h2> {% elif is_inventorymanager %} <h2>Inventory Manager Menu</h2> {% elif is_financialdirector %} <h2>Financial Director Menu</h2> {% elif is_vendor %} <h2>Vendor Menu</h2> {% else %} <h2>Undefined</h2> {% endif %} <br /> <table> {% if is_employee %} <tr><td> <form class="margintop" action='createpurchaseorder' method='GET'> <button type="submit" class="btn btn-info"> EMP | Create Purchase Order</button><br /> </form> </td></tr> <tr><td> <form class="margintop" action='createdeliveryorder' method='GET'> <button type="submit" class="btn btn-info"> VEN | Create Delivery Order</button><br /> </form> </td></tr> <tr><td> <form class="margintop" action='listview_po' method='GET'> <button type="submit" class="btn btn-info">EMP FM VEND | View … -
Django email backend and smtp configuration
I'm trying to use my Zoho account within my django project, in order to receive emails via contact forms. I also followed this guide: https://www.zoho.com/mail/help/zoho-smtp.html In the 'settings.py' file I wrote: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtppro.zoho.eu' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '<domain name email>' EMAIL_HOST_PASSWORD = '<password>' and in views.py: def home(request): allTemplates = AllTemplates.objects.all() if request.method == 'POST': form = forms.ContactForm(request.POST) if form.is_valid(): body = { 'name': form.cleaned_data['name'], 'surname': form.cleaned_data['surname'], 'from_email': form.cleaned_data['from_email'], 'message': form.cleaned_data['message'], } mail_body = "\n".join(body.values()) try: send_mail("Generic contact", mail_body, '<domain name email>', ['<domain name email>'], fail_silently=False) except BadHeaderError: return HttpResponse('Ops, qualcosa è andato storto') form = forms.ContactForm context = {'form': form, 'allTemplates': allTemplates, 'allTemplates_length': len(allTemplates)} return render(request, 'home.html', context) N.B. in 'send_email' I entered my email address twice to test I also tried to use ssl EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtppro.zoho.eu' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = '<domain name email>' EMAIL_HOST_PASSWORD = '<password>' but nothing, I don't receive any email. Is there anyone who has already gone through it or who can direct me towards some document or guide to study? Thank you very much in advance. -
Got AttributeError when attempting to get a value for field `name` on serializer `BusinessSerializer`
I am getting this error. when trying to save a record using rest AttributeError at /business/ Got AttributeError when attempting to get a value for field name on serializer BusinessSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'name'. why is trying to find name field on user object when business object already has that field views.py class BusinessViewSet(viewsets.ModelViewSet): serializer_class = BusinessSerializer queryset = Business.objects.all() def create(self,request): serializer = BusinessSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) businessRecord = serializer.save() return Response({ "business": BusinessSerializer(businessRecord, context=self.get_serializer_context()).data, }) models.py class Business(models.Model): businessOwner = models.OneToOneField(User,blank=True,null=True,on_delete=models.CASCADE) # first name, last name, username, email, password etc. present in this model name = models.TextField() mobileNumber = PhoneField(help_text='Mobile Number') businessLocation = models.PointField() created = models.DateTimeField(auto_now_add=True) businessType = models.CharField(max_length = 30,choices = BUSINESS_TYPE_CHOICES,default = 'Business') address = models.TextField() businessCategory = models.ManyToManyField(Category, related_name='Bcategory', blank=True) hashTags = models.ManyToManyField(HashTag, related_name='Bhashtag', blank=True) socialMediaAccountLink = models.URLField(max_length=400, blank=True,null=True) socialMediaType = models.CharField(max_length=30, choices=SOCIAL_MEDIA_TYPE_CHOICES, default='Instagram') class Meta: indexes = [ models.Index(fields=['businessLocation', 'businessType','name','businessOwner']), ] serializers.py class BusinessOwnerSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password','first_name','last_name') extra_kwargs = … -
Django model not saving POST ajax request
My Django model isn't saving response even after getting a POST request. I'm trying to create a basic like , dislike counter and I'm having trouble updating my like value in database. Although I'm sending POST response to to function likePost in view.py I can't seem to update like_votes field in my Post model. My model class Post(models.Model): post_text = models.CharField(max_length=1000) pub_date = models.DateTimeField('date published') like_votes = models.IntegerField(default=0) dislike_votes = models.IntegerField(default=0) def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def __str__(self): return self.post_text My ajax function <script type="text/javascript"> var likebtn = document.getElementById("likebtn"); likebtn.addEventListener('click', buttonClikckHandler); var num1 = 1; var like = parseInt("{{post.like_votes}}"); var new_l = like; function buttonClikckHandler() { console.log("clicked like"); const xhr = new XMLHttpRequest(); var new_l = like + num1 % 2; num1 = num1 + 1; document.getElementById("like").innerHTML = new_l; var catid; catid = $(this).attr("data-catid"); $.ajax( { type: "GET", url: "/likepost", data: { post_id: catid , votes : new_l }, success: function (data) { $('#like' + catid).remove(); $('#message').text(data); } }) console.log(new_l, num1); } </script> Views.py def likePost(request ): if request.method == 'POST': post_id = request.POST['post_id'] print( post_id) likedpost = Post.objects.get(pk=post_id) #m = Like(post=likedpost) likedpost.like_votes = int(request.POST['votes']) likedpost.save() #m.save() return HttpResponse("Success!") else: return HttpResponse("Request method is not a POST") -
Django ORM expression for recursive sum type?
I am making a simple PLM software and the recursive component system is necessary for it. Specifically, I would like to know if there is any way one can express the data type below with Django ORM; if not what would be the best workaround? Component ::= Part | [Component] (or Set of Components) I think the problem breaks down into two issues. How to express sum type with Django ORM How to express a List of a type with ORM For the second issue alone, I am using the two Models (or Table); One for the list instance and another for the rows of the lists which have foreign key filed of list instance to indicate which model it belongs to. However, It seems not that useful for this case; Especially considering querying and forms. What would be the closest expression of the data type above in Django ORM? -
How to design Django models?
This is my Django Models class Course(models.Model): course_name = models.CharField(max_length=100, blank=True) def __str__(self): return self.course_name class Video(models.Model): video_name = models.CharField(max_length=100, blank=True) video_link = models.CharField(max_length=500, blank=True) def __str__(self): return self.video_name class Unit(models.Model): unit_name = models.CharField(max_length=100, blank=True) videos = models.ManyToManyField(Video) course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return self.unit_name class Blog(models.Model): blog_name = models.CharField(max_length= 100) def __str__(self): return self.blog_name Course : Python Tutorial 1 Course : Python Tutorial 2 I want my Python Tutorial 2 doesn't have a video list that Python Tutorial 1 has, but every unit in Python Tutorial 1 has the same video list, How I could modify my code to have that system? -
Django create common "createObject" view logic
I've got a django app with multiple models, and mostly crud functionalities. Most of my views are very similar, ie. for example, all ModelnameCreate functions have very similar structure. So I decided to make helper function: (here is an example of helper for creating new objects) def createFuncHelper(request, title_label , formClass , form_render , success_render , renderToViewWithId , success_message): form = formClass() if request.method=='POST': form = formClass(request.POST, request.FILES) if form.is_valid(): form.instance.updatedBy = request.user newObject = form.save() messages.success(request, success_message) if(renderToViewWithId): return redirect(success_render, id=newObject.pk) else: return redirect(success_render) return render(request, form_render, {'form':form, 'title_label':title_label}) Which is called from my each view (for each model) eg.: def BookingCreate(request): return createFuncHelper(request, etc... It works, but the question for my more experience collegues is - if it is the right approach, or are there any serious risks I'm not aware? -
Html file did not work for live streaming in django
In camera.py file class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) # Define the codec and create VideoWriter object def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() ret, jpeg = cv2.imencode('.jpg',image) return jpeg.tobytes() **In view.py file ** def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type='multipart/x-mixed-replace; boundary=frame') ** My url.py file** tyurlpatterns = [ path('live/',stream_views.video_feed,name='video_feed'), And HTML file {% extends 'blog/base.html' %} {% block content %} <img src="{{ url 'video_feed' }}" alt="video_feed"> {%endblock content%} here my html file is not work.It just run other file.Html file can't access this url . what i can do for solving this problem? I expect my every frame continuously pass into my html page. -
How to access data from previous form in django-formtools wizard?
I'm trying to use information selected in a previous step of a wizard in a subsequent step. I assume this is a pretty common use case but my googling has ben of limited help, so I think I'm not approaching it in the django way. I only find a few questions from 10 years ago. I have distinct templates defined for each step It seems like there must be a very basic way to access the previous steps data but I'm struggling (new to Django in general) This is the only documentation I can find but it seems to be just be describing how to use the context dictionary to determine to skip a step or not. There must be some 1 IQ simple way to get a value input in step 1 and display it in step 2.. Please help me! -
Plotly write_image() - Django framework Python
My python code generates perfectly the chart, however, i struggle to save it in my repo. My Django framework is structured as such. I want the script located in playground/views.py to generate in /static/ import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=ainfo.index,y=ainfo.Close, mode='lines')) x = fig.show() fig.write_image("../static/fig1.png") And got this error message: FileNotFoundError: [Errno 2] No such file or directory: '../static/fig1.png' In addition, How can I name the file with a variable ? let MyVariable = 1 fig.write_image("../static/"+ MyVariable +".png") -
Can we add a HTML attr with value from our DB in Django?
I have a form, I take the info to this form from my DB. My form.py class TrafficSourcesForm(ModelForm): class Meta: model = TrafficSources fields = ['name', 'token'] widgets = { 'name': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Traffic source name' }), 'token': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'API-token' }) } My views.py def settings(request): error = '' if request.method == 'POST': new_form = TrafficSourcesForm(request.POST, instance=request.POST.get('id')) if new_form.is_valid(): # new_form.save() error = request.POST.text else: error = 'Something went wrong!' new_form = TrafficSourcesForm() forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()] return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error}) MY HTML <table class="table table-striped table-hover"> <tr> <th style="width: 42%">Name</th> <th style="width: 43%">Token</th> <th style="width: 15%">Action</th> </tr> {% for form in forms %} <tr> <td>{{ form.name }}</td> <td>{{ form.token }}</td> <td><button class="btn btn-lg btn-success w-100" form="{{form.instance.id}}">Save</button></td> </tr> {% endfor %} <tr> <td colspan="3">Add new traffic source:</td> </tr> <tr> <td><input class="form-control" placeholder="Name"></td> <td><input class="form-control" placeholder="API-token"></td> <td><button class="btn btn-lg btn-success w-100">Add</button></td> </tr> </table> As I am using a table grid, my forms for the inputs and submit button are outside the table. In that way I need to put a tag form="{a variable from DB to match the form}" on my inputs. Something like instance number or name …