Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is a better way to start django project?
I am using Django framework. I have tried the following four methods to start my project python manage.py. Disadvantage: If the first request get stuck, all the other requests will get stuck. gunicorn. Disadvantage: it has conflicts with asynchronous servers. (websockets) uvicorn. Disadvantage: it doesn't process some requests randomly. gunicorn+uvicorn(gunicorn myproject.asgi:application -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000). Disadvantage: the same with python manage.py -
How to display database data to your website?
This is a very simple question that got me stuck. I have 2 tables that are connected: Dealershiplistings, Dealerships. On my website I need to display the Model, Make and year of the car (Which are all stored in the DealershipListing, so i have no problem wiht this part) but I also need to print the address that is stored in the Dealerships table. Can anyone help me with this? this is what i have for my views.py def store(request): dealer_list = Dealer.objects.all() car_list = DealershipListing.objects.all() context = {'dealer_list': dealer_list, 'car_list': car_list} return render(request, 'store/store.html', context) i tried doing {{%for car in car_list%}} <h6>{{car.year}} {{car.make}} {{car.model}}</h6> {% endfor %} which works perfectly displaying those. But now how do i display the address of the dealership that is selling the car? models.py class Dealer(models.Model): dealersName = models.TextField(('DealersName')) zipcode = models.CharField(("zipcodex"), max_length = 15) zipcode_2 = models.CharField(("zipCode"), max_length = 15) state = models.CharField(("state"), max_length=5) address = models.TextField(("Address")) dealerId = models.IntegerField(("ids"), primary_key=True) def __str__(self): return self.dealersName class DealershipListing(models.Model): carID = models.IntegerField(("CarID"), primary_key=True) price = models.IntegerField(('price')) msrp = models.IntegerField(('msrp')) mileage = models.IntegerField(('mileage')) is_new = models.BooleanField(('isNew')) model = models.CharField(("Models"), max_length= 255) make = models.CharField(("Make"), max_length=255) year = models.CharField(("Year"),max_length=4) dealerID = models.ForeignKey(Dealer, models.CASCADE) def __str__(self): return … -
Dhnago Server Side Data table with DataTable.net
I am trying to implement serverside data table with Django.My Datas are going to the Clients side from server(as i have checked console.log(data)) but they are not displaying into table. If any of you guys could help me with this then i will be so much greateful. Thanks in advance ! Template: <div class="container"> <div class="row"> <div class="col-md-12"> <table id="example" class="display" style="width:100%"> <thead> <tr> <th>Uploader</th> <th>Main Category</th> <th>Sub Category</th> <th>Product Name</th> <th>Product Price</th> <th>Brand Name</th> <th>In Stock</th> <th>Product Number</th> <th>Warranty</th> <th>Uploaded</th> <th>Image</th> <!-- <th>Action</th> --> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> </div> </div> Script: $(document).ready(function () { $('#example').DataTable({ responsive: true, "serverSide": true, "processing": true, "ajax": { url: '{% url "mainTableData" %}', success: function(data){ console.log(data) }, error: function (error){ console.error(error) } }, }); }); Views.py: def mainTableData(request): ajax_response = {} search_values = [] fields = ['v_user__username', 'v_main_category__cat_name', 'v_sub_category__sub_cat', 'v_product_name', 'v_product_price', 'v_brand_name', 'v_in_stock', 'v_product_number', 'v_product_warranty', 'v_created' ] for i in range(1, 10): value = request.GET.get('columns['+str(i)+'][search][value]') search_values.append(value) products = VendorProduct.objects.filter(reduce(AND, (Q(**{fields[i]+'__icontains': value} ) for i, value in enumerate(search_values)))).values_list('v_user__username', 'v_main_category__cat_name', 'v_sub_category__sub_cat', 'v_product_name', 'v_product_price', 'v_brand_name', 'v_in_stock', 'v_product_number', 'v_product_warranty', 'v_created').order_by('-id') # Add paginator paginator = Paginator(products, request.GET.get('page_length', 3)) showing_rows_in_current_draw = request.GET.get('length') products_list = … -
django: related_name of self related ForeignKey field not working | get opposite direction of self reference in template
Hej! :) I have a model to create single institutions (Institution) and can connect it to a parent institution, via parent_institution (self). So I have the institution A, which is parent to b, c, d (All themselves single institutions with an own detail view.) In the detail view of b I have the section 'parent institution' where I get A as a result, including a link to the detail view of A. <p><b>Parent institution: </b> {% if institution.parent_institution %} <a href="{% url 'stakeholders:institution_detail' institution.parent_institution.id %}"> {{institution.parent_institution}} </a> {% endif %} </p> Following this link I get to the detail view of A where I want a section with the child institutions. There should b, c, d be listed. I added a related name to the parent_institution class Institution(models.Model): name = models.CharField( verbose_name=_("Name of the institution"), max_length=200, ) parent_institution = models.ForeignKey( "self", verbose_name=_("Parent institution"), on_delete=models.SET_NULL, blank=True, null=True, help_text=_("if applicable"), related_name="child", ) normally I can follow the ForeignKey in the opposite direction via this related_name. <p><b>Child institution: </b> {{institution.child.name}} </p> but in this case this is not working and gives me 'None'. Therefor did I try: {% if institution.id == institution.all.parent_institution.id %} {{institution.name}} {% endif %} {% if institution.all.id == institution.parent_institution.id %} … -
Why doesn't this django form accept my input if it also generates the options itself?
It is a competition manager that matches the participants of a competition randomly, I call these pairs games. The game is a django model with an attribute called "ganador" to store the winner of the game. To choose the winner I use a modelform_factory called formaGanador and exclude all the attributes of the model except the "ganador" attribute. The attribute "ganador" has an option of "choices" so that the form only allows to choose one of the participants of that game and not participants of other games. Finally, when I select a participant from the list and press the submit button on the form, I receive the following response: Select a valid choice. Player A is not one of the available choices. model for games in model.py: class Juego(models.Model): torneo = models.ForeignKey(Torneo, on_delete=models.CASCADE, null=False) ronda = models.ForeignKey(Ronda, on_delete=models.CASCADE, null=False) jugadorA = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorA') jugadorB = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorB') puntuacionA = models.IntegerField(default=0) puntuacionB = models.IntegerField(default=0) ganador = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, default=None, choices=[('Jugador A', 'Jugador A'), ('Jugador B', 'Jugador B')]) creating the form in the views: GanadorForm = modelform_factory(Juego, exclude=['torneo', 'ronda', 'jugadorA', 'jugadorB', 'puntuacionA', 'puntuacionB']) passing and receiving the form "formaganador" from the template : def detalleTorneo(request, id): torneo … -
AWS lightsail django static files not loading using apache
I created a django project in AWS lightsail which makes use of bitnami. I have been able upload my project but when I tried accessing the from the public ip address I was given, it produced some error in my browser and the error log were Exception ignored in: <function Local.__del__ at 0x7f923d359550> Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7f923d359550> Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined [Thu Dec 02 08:25:01.082092 2021] [mpm_event:notice] [pid 18334:tid 140267253222272] AH00491: caught SIGTERM, shutting down [Thu Dec 02 08:25:01.259848 2021] [ssl:warn] [pid 18855:tid 140702045899648] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name [Thu Dec 02 08:25:01.269998 2021] [ssl:warn] [pid 18856:tid 140702045899648] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name [Thu Dec 02 08:25:01.270771 2021] [mpm_event:notice] [pid 18856:tid 140702045899648] AH00489: Apache/2.4.51 (Unix) OpenSSL/1.1.1d mod_wsgi/4.7.1 Python/3.8 configured -- resuming normal operations [Thu Dec 02 08:25:01.270797 2021] [core:notice] [pid 18856:tid 140702045899648] AH00094: Command line: '/opt/bitnami/apache/bin/httpd -f /opt/bitnami/apache/conf/httpd.conf' [Thu Dec 02 08:25:16.600738 2021] [authz_core:error] [pid 18858:tid 140701463279360] [client 185.220.101.170:29682] … -
TypeError at / Field 'id' expected a number but got <username>
returns username instead of user.id,i'm try to getting user.id in user_id field but getting username, the user-id field registerd as forignkey fiels of user,so it returns number only views.py def index(request): if request.user.is_authenticated: cus = User.objects.get(pk=request.user.id) print(cus) if request.method == 'POST': task = request.POST['task'] priority = request.POST['priority'] date = request.POST['date'] time = request.POST['time'] add_task = AddTodo(task=task, priority=priority, date=date, time=time, user_id=cus) add_task.save() if add_task is not None: print("task added suuccesfuly", task) else: print("task not added", task) return render(request, 'index.html') models.py class AddTodo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=100, blank=True) priority = models.IntegerField() date = models.DateField() time = models.TimeField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) exception: TypeError: Field 'id' expected a number but got <User: captainamerica123>. -
How to create dynamic queries with Django Q objects from parenthesis inside a string
I don't know if the title of the question is formed well enough. But essentially I would like to be able to do something like this from front end : (name="abc" OR name="xyz") AND (status="active" OR (status="available" AND age=30)) I want to the user to send this string. I will parse it in backend and form a query. I have looked at this answer and this but couldn't figure out how to solve the parenthesis here. I am thinking about using a stack (the way we solve infix expressions) to do this, but don't want to go that long route unless I am sure there isn't another/ready solution available. If someone can do this with that method, would be great too. -
how to create model object of a selected type of user in the registration form
how to create model object of a selected type of user in the registration form? what I want is if the selected type of user is a student then I want to automatically create it in the student model after being registered not just in the User model. how to achieve that? models.py class User(AbstractUser): is_admin = models.BooleanField('Is admin', default=False) is_teacher = models.BooleanField('Is teacher', default=False) is_student = models.BooleanField('Is student', default=False) class Student(models.Model): GENDER = ( ('1', 'Male'), ('2', 'Female') ) STATUS = ( ('1', 'Ongoing'), ('2', 'On Probition'), ('3', 'NA') ) name = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) id_number = models.IntegerField() gender = models.CharField( max_length=10, choices=GENDER, blank=True, null=True) date_of_birth = models.CharField(max_length=20, blank=True, null=True) course = models.ForeignKey( Course, on_delete=models.CASCADE, blank=True, null=True) year_level = models.IntegerField() status = models.CharField(max_length=10, choices=STATUS, default='3') def __str__(self): return str(self.name) class Teacher(models.Model): name = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return str(self.name) forms.py class SignUpForm(UserCreationForm): username = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control" } ) ) password1 = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control" } ) ) password2 = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control" } ) ) email = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control" } ) ) class Meta: model = User # model = Profile fields = ('username', 'email', 'password1', … -
Convert HTML to PDF with full CSS support
I want to convert a HTML file to PDF. Is there any package that supports CSS3? -
How to merge (audio-video) moviepy object download at client side using Django?
Is that possible to moviepy object download at the client-side without saving it in the local system? from moviepy.editor import * new_filename = "file.mp4" videoclip = VideoFileClip('https://r1---sn-bu2a-nu8l.googlevideo.com/videoplayback?expire=1638440709&ei=pUqoYZ2cI7rrjuMPkcmekAg&ip=103.250.149.188&id=o-ANFawiDzzYp-FoY6AqX0SXbijhKJ35opECWXtCnACjMA&itag=247&aitags=133%2C134%2C135%2C136%2C137%2C160%2C242%2C243%2C244%2C247%2C248%2C278&source=youtube&requiressl=yes&mh=Ex&mm=31%2C29&mn=sn-bu2a-nu8l%2Csn-cvh7knzy&ms=au%2Crdu&mv=m&mvi=1&pl=24&initcwndbps=1033750&vprv=1&mime=video%2Fwebm&ns=dlzD-Hg9SRxU5fPWrHNCpxoG&gir=yes&clen=4785704&dur=98.800&lmt=1629780934695756&mt=1638418840&fvip=4&keepalive=yes&fexp=24001373%2C24007246&c=WEB&txp=5316224&n=iQjeGVjS9lxbMWOMcaQ&sparams=expire%2Cei%2Cip%2Cid%2Caitags%2Csource%2Crequiressl%2Cvprv%2Cmime%2Cns%2Cgir%2Cclen%2Cdur%2Clmt&sig=AOq0QJ8wRAIgcB3Y4lQ_gHYarp6no018274Exolw0TWq2CLRs8yrSw8CIDOiiKaOcY5ErMyFoldCS7KHTzlQPPW0yEPYuVsCnCun&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AG3C_xAwRgIhAJjwzsCqE5dF_IvaUo5JjQ8FsC1Wz9S84XGs_krXvSo5AiEA4va5rbULblSOajaV9-aJqP7vOsg5ZByr1QYJTQXegu0%3D') audioclip = AudioFileClip('https://r1---sn-bu2a-nu8l.googlevideo.com/videoplayback?expire=1638440709&ei=pUqoYZ2cI7rrjuMPkcmekAg&ip=103.250.149.188&id=o-ANFawiDzzYp-FoY6AqX0SXbijhKJ35opECWXtCnACjMA&itag=249&source=youtube&requiressl=yes&mh=Ex&mm=31%2C29&mn=sn-bu2a-nu8l%2Csn-cvh7knzy&ms=au%2Crdu&mv=m&mvi=1&pl=24&initcwndbps=1033750&vprv=1&mime=audio%2Fwebm&ns=dlzD-Hg9SRxU5fPWrHNCpxoG&gir=yes&clen=549813&dur=98.861&lmt=1629780936256332&mt=1638418840&fvip=4&keepalive=yes&fexp=24001373%2C24007246&c=WEB&txp=5311224&n=iQjeGVjS9lxbMWOMcaQ&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cvprv%2Cmime%2Cns%2Cgir%2Cclen%2Cdur%2Clmt&sig=AOq0QJ8wRQIhAPVt1A7C5tmoTqAtAIgx0vFlM7LHSiyD2QGmJBL0hdGBAiBfjiw5qrUrbw9KkTk_3z9gzDHHMsFUCOL9lhOMZbAbkg%3D%3D&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AG3C_xAwRgIhAJjwzsCqE5dF_IvaUo5JjQ8FsC1Wz9S84XGs_krXvSo5AiEA4va5rbULblSOajaV9-aJqP7vOsg5ZByr1QYJTQXegu0%3D') new_audioclip = CompositeAudioClip([audioclip]) videoclip.audio = new_audioclip response = StreamingHttpResponse(streaming_content=videoclip) response['Content-Disposition'] = f'attachement; filename="{new_filename}"' return response It returns the error TypeError: 'VideoFileClip' object is not iterable Please help me. -
Does Django RestFramework supports async views and class?
It will be helpful if someone helps me with a clear cut answer. If Yes any suggestion how to approach... coz, I try to use async with DRF but I am always ending with "AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'coroutine'>" this error -
How to add buttons instead of select element as action in django admin
hope everyone is doing well. I want to integrate ample admin template to django, so what I want is just customize the look and feel of django admin but not the behaviour. I want to show buttons like delete and other actions instead of select element that django admin comes with by default. Following is what django do to render the select element, I overriden admin templates but dont know what I do to get buttons instead of select items, I would love to mention that these actions are dynamic you know by customization of admin class, we can add different actions and so thats why we have this for loop. What output I am getting is as follow: This is what django generates: What I want is just render buttons instead of html select element, plz help -
Django - check_password() always returning False
I have written a test for creating user. This statement self.assertTrue(user.check_password(payload["password"])) is failing with this error, AssertionError: False is not true. user.check_password() is returning False even though both passwords are equal. class UsersAPITests(TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.client = APIClient() self.faker = Faker() def test_create_user(self): payload = { "email" : self.faker.email(), "password": self.faker.password(), "username": self.faker.user_name() } response = self.client.post(CREATE_USER_URL, payload) self.assertEqual(response.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**response.data) self.assertTrue(user.check_password(payload["password"])) self.assertNotIn('password',response.data) -
Trying to post blob data from js to django server
I have some (recorded as .webm)audio as blobs, and I want to transfer it to my django server, but for some reason the file is being saved with content being the string null client.js var file = new File([recorder.blob], "rec.webm") var fdata = new FormData() fdata.append('rec.webm',file,'rec.webm') let response = fetch("/recording/", { method: "post", body: fdata, headers: { "X-CSRFToken": csrftoken }, }) server_endpoint if request.method == 'POST': recording = request.FILES.get('rec.webm') print(request.FILES) with open('./rec.webm', 'wb+') as destination: for chunk in recording.chunks(): destination.write(chunk) return HttpResponse("202") return HttpResponseBadRequest rec.webm null -
How to change the datatype of Django model field
I have a set of django models as follows class FirstCategory(models.Model): first_category = models.CharField(max_length=200) def __str__(self): return self.first_category class SecondCategory(models.Model): first_category = models.ForeignKey(FirstCategory, on_delete=models.CASCADE) second_category = models.CharField(max_length=200) def __str__(self): return self.second_category class ThirdCategory(models.Model): first_category = models.ForeignKey(FirstCategory, on_delete=models.CASCADE) second_category = models.ForeignKey(SecondCategory, on_delete=models.CASCADE) third_category = models.CharField(max_length=200) def __str__(self): return self.third_category class FinalList(models.Model): unique_number = models.BigIntegerField() name = models.CharField(max_length=200) first_category = models.ForeignKey(FirstCategory, on_delete=models.SET_NULL, null=True, db_column="first_category") second_category = models.ForeignKey(SecondCategory, on_delete=models.SET_NULL, null=True, db_column="second_category") third_category = models.ForeignKey(ThirdCategory, on_delete=models.SET_NULL, null=True, db_column="third_category") def __str__(self): return self.name When I migrate the models and check the datatypes of the fields in the FinalList table I get the following column_name | data_type ---------------------------+------------------- third_category | bigint first_category | bigint second_category | bigint unique_number | bigint name | character varying I had specified the first, second, and third categories as Character fields. Why is it being migrated as BigInt? I am trying to implement a chained dropdown in my form. I am following SimpleBetterThanComplex tutorial for this -
Django hosted sites response nothing
My django rest framewrok backend site is hosted in cpanel.Somestimes it responses with data and sometimes it responds nothing like in image.Server log doesn't shows any problem.This problems occurs in some interval.It automatically works after some times like 10-15 minutes.What might be the problem? -
Django models: Query to Get the data from the table an hourly basis
enter image description here I am working in Django and python. I have the data for minutes basis in my database please have a look at the image, But when am querying it I want to have a query which fetches the data on an hourly basis Table Name: TrafficTrend_SDP_BHCA This image has the table name and the columns it has. I have the full length of data fromdate 202109270835 to todate 202109290956 202109270835 is the date hour format. "20210927" is the date, "08" is an hour and "35" is minutes. From this table I want to fetch data on an hourly basis. Example: data started with 202109270835 , so i want to get the data something like for 08 hours and 09 hours (an hourly basis). and for each hour the respective columns(VCS1FI) and (VCS1FI_Fail) values should be summed up individually Output could be for 2021092708 hours VCS1FI= "", VCS1FI_Fail="" and for 2021092709 hours VCS1FI= "", VCS1FI_Fail="". -
media image is not able to display on webpage
when click on "yo" I am able to see media file but when tried to display image through the image tag it is not seen on webpage <a href="{{status.adv.url }}">yo</a> <img src="{{status.adv.url}}" width="250" height="250" alt="advertise"/> -
Django sql server migration not working Error: NotImplementedError: the backend doesn't support altering from/to AutoField
NotImplementedError: the backend doesn't support altering from/to AutoField. -
I am getting "not NULL Constraint error" in my unit test only
I need help. My registration system is working perfectly fine when I run on a local server, but when I run my test. It fails. I don't understand why? I am unable to figure out what is wrong, I have deleted the entire database and migrations. even I created the new app and did everything there. But still, I am getting this error. My test_setup.py from rest_framework.test import APITestCase from django.urls import reverse class TestSetup(APITestCase): def setUp(self): self.register_url = '/register/' self.user_data = {"Username":"frontend123", "First name":"Frontend", "Last name":"Developer", "Password":"bitspro##1", "Confirm password":"bitspro##1","Email":"rida@bitspro.com","Date of birth":"1997-12-27"} return super().setUp() def tearDown(self): return super().tearDown() My testViews.py from authentication.models import User from authentication.tests.test_setup import TestSetup class TestViews(TestSetup): def test_user_cannot_register_without_any_data(self): res = self.client.post(self.register_url) self.assertEqual(res.status_code, 400) def test_user_can_register_correctly(self): res = self.client.post(self.register_url, self.user_data, format="json") self.assertEqual(res.status_code, 201) My view.py (I am testing registration system only from rest_framework.response import Response from rest_framework.views import APIView from authentication.models import User as Client class Register(APIView): def post(self, request): username = request.data.get('Username') first_name = request.data.get('First name') last_name = request.data.get('Last name') password = request.data.get('Password') confirm_password = request.data.get('Confirm password') date_of_birth = request.data.get('Date of birth') email = request.data.get('Email') if password == confirm_password: if Client.objects.filter(username = username).exists(): return Response({"message": "this username already exist"}, 400) elif Client.objects.filter(email = email).exists(): return Response({"message": … -
How to represent all ManyToMany fields in djangorestgramework serializer class?
I want to render ManyToMany fields with there values using django. Base model class SalesAction(models.Model): sales_representative = models.ForeignKey( SalesRepresentative, on_delete=models.CASCADE) doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) remark = models.CharField(max_length=500) date = models.DateField() medicines = models.ManyToManyField(Medicine, through='SalesActionMedicine') def __str__(self): return f'{self.sales_representative} - {self.doctor}' Details model class SalesActionMedicine(models.Model): sales_action = models.ForeignKey(SalesAction, on_delete=models.CASCADE) medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE) quantity_type = models.CharField(max_length=50) quantity = models.PositiveIntegerField() What I want is to represent all medicines related to each object in the SalesAction model class. This is the serializer I built. class SalesActionMedicineSerializer(serializers.ModelSerializer): class Meta: model = SalesActionMedicine fields = ('sales_action', 'medicine', 'quantity_type', 'quantity') class SalesActionSerializer(serializers.ModelSerializer): medicines = SalesActionMedicineSerializer(many=True) class Meta: model = SalesAction fields = ('sales_representative', 'doctor', 'remark', 'date', 'medicines') This code gives my this error: Got AttributeError when attempting to get a value for fieldsales_actionon serializerSalesActionMedicineSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Medicineinstance. Original exception text was: 'Medicine' object has no attribute 'sales_action'. -
Django Reportlab getKeepWithNext
I am trying to add an image to a PDF generated in Reportlab. I am trying to access the image from a Django field, specifying the full path of the file. When I run the below code I get: "Exception Value: getKeepWithNext". Any help as to what I am doing wrong would be greatly appreciated. def holding_pdf(self, course_slug, holding_slug): buffer = io.BytesIO() holding = HoldingDetail.objects.get(identifier=holding_slug) doc = SimpleDocTemplate(buffer, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=72, pagesize=A4, title=f"Why the {holding.name} is in the portfolio.pdf") elements = [] styles = getSampleStyleSheet() elements.append(Paragraph(str(holding.logo.path), styles['Normal'])) elements.append(Image(holding.logo.path)) print(holding.logo.path) doc.build(elements) buffer.seek(0) return FileResponse(buffer, as_attachment=False, filename=f"Why the {holding.name} is in the portfolio.pdf") -
How to change the executer of python in vscode?
I was trying to change the executer of python in vscode. I have installed python3 in my system.However default executer of python in vscode is python.So i am getting error as 'python not found' whenever i try to run code. So how could i change the executer to python3 in line no 4066? -
OperationalError at /users/friend-request/accept/6/ no such table: main.users_profile__old
I'm unable to accept the friend request, delete request and send request is working fine users/views.py @login_required def send_friend_request(request, id): user = get_object_or_404(User, id=id) frequest, created = FriendRequest.objects.get_or_create( from_user=request.user, to_user=user) return HttpResponseRedirect('/users/{}'.format(user.profile.slug)) @login_required def accept_friend_request(request, id): from_user = get_object_or_404(User, id=id) frequest = FriendRequest.objects.filter(from_user=from_user, to_user=request.user).first() user1 = frequest.to_user user2 = from_user user1.profile.friends.add(user2.profile) user2.profile.friends.add(user1.profile) if FriendRequest.objects.filter(from_user=request.user, to_user=from_user).first(): request_rev = FriendRequest.objects.filter(from_user=request.user, to_user=from_user).first() request_rev.delete() frequest.delete() return HttpResponseRedirect('/users/{}'.format(request.user.profile.slug)) if any more code is required, please comment below