Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
E TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use subjects.set() instead
I am writing a test to some api calls, the issue that I am getting is that I can't figure out how to assign a many-to-many variable(subjects) in Django. models.py class Subject(BaseModel): id = models.AutoField(primary_key=True) name = models.TextField(null=False, blank=False) answers = models.ManyToManyField("registration.Answer", through="AnswerSubject") class Answer(BaseModel): id = models.AutoField(primary_key=True) text = models.TextField(null=False, blank=False) subjects = models.ManyToManyField("subjects.Subject", through="subjects.AnswerSubject") test.py def tets_get_answer: Answer.objects.create( text=f'{"test answer"}', subjects = f{"test subject"} # the error is here, how do I assign subjects? ), ........ this is the error that I am getting: E TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use subjects.set() instead. Any help is appreciated -
TypeError: __init__() got an unexpected keyword argument 'export_job'
I am implementing an export function with django-import-export-celery and the instructions are only three steps. I followed all of them, and when I try to do an export, it gives me an error on the celery process: This is what my code looks like: class Issuer(models.Model): name = models.CharField(max_length=200, null=False, blank=False,) @classmethod def export_resource_classes(cls): return { "Issuers": ("Issuers resource", IssuerResource), } class IssuerResource(ModelResource): def ready(self): class Meta: model = apps.get_model('crowdfunding.Issuer') Any help is appreciated. -
How to assign variable to JSON in Django Views.py context
I'm Getting Data from an external API, in which i convert to JSON then i add the data in context to use in my Template. the problem is that the different variables in the API have a specific assigned number. i want to store that number in my database so i can assign them to specific objects on my website. here is the code models.py = api_text = models.CharField(max_length=100, blank=True, null=True,) Views.py def projectdetails(request, pk): url = 'XXX' parameters = { 'slug': 'bitcoin', 'convert': 'USD', } headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': 'XXX' } session = Session() session.headers.update(headers) response = session.get(url, params=parameters) api_price = response.json() coin = Coin.objects.get(id=pk) context = {'coin':coin, 'gimmeprice':api_price['data']['1']['quote']['USD']['price'], } return render(request, 'blog/project_details_coin.html', context) the [1] in the context is where i want to use a variable that i assign to "api_text" im having troubles figuring out with Django Model Query to use and how -
After creating a custom model for custom roles now if create a user and give him 'admin' authentication i cant login to admin page
from django.db import models from django.contrib.auth.models import AbstractUser,User from django.utils.html import escape,mark_safe # Create your models here. class user(AbstractUser): is_admin = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) now if i create a user and give him any of these privilege and then call the user anywhere it shows 'NoneType' object has no attribute 'is_admin' -
How to filter and add multiple datasets using Django and Chart.js
I've been scratching my head for quite a while on this so any help is much appreciated. Let's say I have a model called Transaction. class Transaction(models.Model): time = models.DateTimeField(auto_now_add=True, blank=True) client = models.ForeignKey(User , on_delete=models.Cascade) value = models.IntegerField() I want to generate a chart using chart.js. So far i am able to do this for all the objects using this JS: <script> $(function () { var $xChart = $("#xChart"); $.ajax({ url: $xChart.data("url"), success: function (data) { var ctx = $xChart[0].getContext("2d"); new Chart(ctx, { type: 'line', data: data, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'xChart' } } }); } }); }); </script> And this FBV for the ajax call: def x_chart(request): def random_color(): return "#"+''.join([choice('ABCDEF0123456789') for i in range(6)]) labels=[] data=[] enddate = datetime.now() startdate = datetime.now().date() - relativedelta(days=3) transactions = Transaction.objects.filter(time__range=[startdate,enddate]) grouped_transactions = transactions.values("time__day").annotate(total=Sum('value')) for key in grouped_transactions: labels.append(key['time__day']) data.append(key['total']) return JsonResponse( data={ 'labels': labels, 'datasets': [ { 'label': 'All Transactions, 'backgroundColor': str(random_color()), 'data': data, } ], } ) I want to create a dataset from each Transaction.client field and then pass it as Json to the ajax request. How would i be able to do that since the lables are … -
Does the form to add data have to contain all the fields of models.py to be able to save?
I have a question, what happens is that I have a model called "Clientes" inside an app that has the same name, right there I have a form with all the fields of my model, the form saves quite well. I also have an app called "Presupuestos" that inherits "Clientes", that app serves as a shortcut for "Clientes". That is to say that this shortcut is the reduced version of the "Clientes form", I mean that the "clientes-add.html"(form) has 10 fields and in "presupuestos-add.html" (form) it has 5 fields. The problem is that the "Presupuestos" one does not save anything. Is it because it is not calling all the "Clientes" fields and it only saves 5? And tried also to put the form errors but it doesn't work models.py class Clientes(models.Model): tipo = models.CharField(max_length=200) TITLE = ( ('Mrs.', 'Mrs.'), ('Miss', 'Miss'), ('Mr.', 'Mr.'), ) corporacion=models.CharField(max_length=200) titulo = models.CharField(max_length=200, null=True, choices=TITLE,default='Mr.') nombre = models.CharField(max_length=200) apellido = models.CharField(max_length=200) telefono = models.IntegerField() tel = models.IntegerField() fax = models.IntegerField() correo = models.EmailField(max_length=200) website=models.URLField(max_length=200) pais = models.CharField(max_length=200) direccion=models.CharField(max_length=200) ciudad=models.CharField(max_length=255) estado=models.CharField(max_length=255) zip=models.CharField(max_length=255) fecha_registro = models.DateTimeField(default=datetime.now) def __str__(self): return f'{self.nombre} {self.apellido}' views.py class step1(CreateView): model=Clientes form_class = ClientesForm template_name='Presupuestos/new-estimate-1-customer-details.html' success_url=reverse_lazy('Presupuestos:step2') presupuestos-add.html <form method="post"> {% csrf_token %} <div … -
Save multiple Django formsets into a single database field
Acutal situation I have a db table called "invoice" where all Django formsets are being saved successfully. So, table looks like this: item_id|quantity|description|price|taxes|total|customer_id|invoice_id| 56 1 apple 100 0 100 567 1766 12 1 banana 40 0 40 567 1766 The problem If, for example, invoice has 100 items, I will have 100 rows inside invoice db table. Question I think there's a better and more efficient way to do the same without making the db heavier. So, I would like to save these items coming from the formsets into a single field as a list of tuples of invoice items? For example the new table will look like this: | items |customer_id|invoice_id| ["fruit", [apple,banana], "price", [100,40]] 567 1766 -
ReportLab page break in python
I have a view for creating from a Pandas dataframe and then turns it into a PDF file and returns the file response. Everything works fine except for (see code below for comment:) @login_required() def download_pdf(request, location_name): current = CurrentInfo() pdf_data = current.detail_employees_by_location(location_name) # this gives me the list of people buf = io.BytesIO() canv = canvas.Canvas(buf, pagesize=letter, bottomup=0) textob = canv.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 10) pf = pd.DataFrame.from_dict(pdf_data, orient='index', columns=['EmployeeNumber', 'LastFirst']) data = pf.drop_duplicates() count = data.count() data = data.to_records() line_break = "|"+"-"*150+"|" textob.textLine(f"Employees in: {location_name} total in site: {count['EmployeeNumber']}") textob.textLine(line_break) textob.textLine("{0:^10}{1:^30} {2:^50}".format("#", "Employees Number", "Name")) textob.textLine(line_break) for index, line in enumerate(data, start=1): textob.textLine(f"{index:^10}{line['EmployeeNumber']:^30} {line['LastFirst']:^50}") textob.textLine(line_break) #when i add this space after each line it causes the page #to never break and just stay on the resulting in lines #not showing canv.drawText(textob) canv.showPage() canv.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='employees.pdf') When I add an additional space after each line the for loop for additional spacing it causes the pages not to break and returns a PDF with bad formatting. -
how to pass dropdown field data through excel sheet in django?
this is my model class Items(models.Model): model_no= models.CharField(max_length=30,null= True) description=models.CharField(max_length=50,null= True ) total_qty=models.PositiveIntegerField(default=0,null=True) created = models.DateTimeField(default=datetime.now()) class ItemDetails(models.Model): STATUS = [ ('In-Stock', 'In-Stock'), ('Out-of-Stock', 'Out-of-Stock'), ('issued-to', 'issued-to') ] serial_no = models.CharField(max_length=50,null=True) tag_no = models.CharField(max_length=50, null=True) rem_qty = models.IntegerField(default=0) status = models.CharField(max_length=30, default='In-stock', choices=STATUS) model_no=models.ForeignKey(Items,on_delete= models.CASCADE) issued_to =models.ForeignKey(Prosecutions,on_delete=models.CASCADE) employee_name=models.CharField(max_length=50,null=True) employee_designation = models.CharField(max_length=50, null=True) created = models.DateTimeField(default=datetime.now()) def excel_import_item_details_db(request): try: if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.path(filename) itemdetailsexceldata = pd.read_csv(uploaded_file_url, sep=",", encoding='utf-8') dbframe = itemdetailsexceldata for dbframe in dbframe.itertuples(): if ItemDetails.objects.filter(serial_no = dbframe.serial_no).exists(): messages.warning(request, dbframe.serial_no + "already exists in Database") else: obj = ItemDetails.objects.create(serial_no=dbframe.serial_no,tag_no=dbframe.tag_no,status=dbframe.status, Items_model_no=dbframe.model_no, Prosecutions_issued_to=dbframe.issued_to, employee_name=dbframe.employee_name,employee_designation=dbframe.employee_designation) obj.save() filename = fs.delete(myfile.name) calc_total_qty() messages.success(request, "New Items uploaded to Database") #return render(request, 'excel_import_db.html', {'uploaded_file_url': uploaded_file_url}) return render(request, 'add_items_details.html', {}) except Exception as identifier: print(identifier) return render(request, 'add_items_details.html', {}) -
How to delete objects/posts from database on close window/tab in Django
I want to delete objects from the database on window close. basically, the reason I want to do this is whenever a user adds any city (this is a weather application, where you can submit a city name and can get the weather data ) for searching the weather of the city, it saves the city info to my Sqlite database permanently. and show that city weather to other users as well. Which I don't want. So basically I want to delete the data of other users and don't want to save it to my database permanently and show another user the same data (which is searched by another user). Now, what can I do? Any help would be appreciated. Views.py from django.shortcuts import redirect, render, redirect from .models import City from .forms import CityForm import math def home(request): api_id = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid={appid}' err_msg = '' message = '' message_class = '' if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): new_city = form.cleaned_data['name'] existing_city_count = City.objects.filter(name=new_city).count() if existing_city_count == 0: r = requests.get(api_id.format(new_city)).json() print(r) if r['cod'] == 200: form.save() else: err_msg = 'You City is Belongs to Mars ig. City Does not exist in the world' print(err_msg) else: err_msg = … -
Optional parameters in django urls
I want to achieve this in Django List all items Get only one item def get(self, request, pk, format=None): if pk is not None: product = self.get_object(pk) serializer = ProductSerializer(product) else: products = Product.objects.all() serializer = ProductSerializer(products) return Response(serializer.data) If pk is in URL take only one product if not take all list. How can I achieve that in URL? What I'm doing is this re_path(r"(?P<pk>\d+)", ProductView.as_view(), name="product"), But 'pk' argument is required here. I don't want the pk to be required but optional. Thanks in advance -
Get number of objects into a merged queryset
I've developed a Django's view that merge two queryset usingchain; below the code. def sharedcategories_list(request): """ Con questa funzione definisco la lista dei post della singola categoria """ list = SharedCategories.objects.all() context = {"list": list} return render(request, "shared-categories/shared_categories_list.html", context) def single_sharedcategory(request, slug): object = get_object_or_404(SharedCategories, slug=slug) wms = OGCLayer.objects.filter(categories=object) webgis = WebGISProject.objects.filter(categories=object) context = { "single_object": object, "objects": list(chain(wms, webgis)), } template = "shared-categories/single_shared_categories.html" return render(request, template, context) The views use the models below: class SharedCategories(CategoryBase): icon = models.ImageField(upload_to=settings.UPLOADED_IMAGE_FOLDER, blank=True, null=True) is_active = models.BooleanField(default=True) def get_absolute_url(self): return reverse("single-sharedcategory", kwargs={"slug": self.slug}) class OGCLayer(BaseModelPost, OpenLayersMapParameters): set_zindex = models.IntegerField(default=1) set_opacity = models.DecimalField(max_digits=3, decimal_places=2, default=1.0) ogc_layer_path = models.ForeignKey(GeoServerURL, related_name="related_geoserver_url", on_delete=models.PROTECT, blank=True, null=True) ogc_layer_name = models.CharField(max_length=100) ogc_layer_style = models.CharField(max_length=100, blank=True, null=True) ogc_bbox = models.CharField(max_length=250, blank=True, null=True) ogc_centroid = models.CharField(max_length=250, blank=True, null=True) ogc_legend = models.BooleanField(default=False) is_vector = models.BooleanField() is_raster = models.BooleanField() categories = models.ManyToManyField(SharedCategories, related_name="related_ogc_categories") def get_absolute_url(self): return reverse("ogc-single", kwargs={"slug": self.slug}) class WebGISProject(WebGISProjectBase): categories = models.ManyToManyField(SharedCategories, related_name="related_webgisproject_categories") basemap1 = models.ForeignKey(Basemap, on_delete=models.PROTECT, related_name="related_basemap1", blank=False, null=True) basemap2 = models.ForeignKey(Basemap, on_delete=models.PROTECT, related_name="related_basemap2", blank=True, null=True) basemap3 = models.ForeignKey(Basemap, on_delete=models.PROTECT, related_name="related_basemap3", blank=True, null=True) main_layer = models.ForeignKey(OGCLayer, on_delete=models.PROTECT, related_name="related_main_wmslayer") layers = models.ManyToManyField(OGCLayer, related_name="related_wmslayer", blank=True) def get_absolute_url(self): return reverse("map-single", kwargs={"slug": self.slug}) I need to view in the template how many objects are related … -
default image being reuploaded when new account created
On my profile model I have a default image. However I would expect that all accounts that have the default image would be reading the same image, but when a new account is created the default.jpg is being re uploaded to the s3 bucket. The issue is being caused by a compression function if i remove it and the on save code the issue goes away. how can i not have it re save default.jpg def compress(image): im = Image.open(image) out_put_size = (300,300) im.thumbnail(out_put_size) # create a BytesIO object im_io = BytesIO() # save image to BytesIO object im = im.resize([500,500]) #resize image im = im.convert("RGB") im = im.save(im_io,'JPEG', quality=75) # create a django-friendly Files object new_image = File(im_io, name=image.name) return new_image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, max_length=30) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): initial = self._state.adding #image compression start if self.image and initial: # call the compress function new_image = compress(self.image) # set self.image to new_image self.image = new_image #image compression end super(Profile,self).save(*args, **kwargs) -
django enter password to enter the room
So I wanna ask you guys a feature I want to add to my chatroom project. I created a Room model so you can enter there and send your messages there so everyone can see them. here comes the problem that i wanna create a private room so when you create the room , u enter a password . and whenever a user want to enter the room should enter a password. here's my private room view: class CreatePrivateRoomView(View): form_class = CreatePrivateRoomForm template_name = 'room/create_room.html' def get(self, request): form = self.form_class return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data room = Room.objects.filter(room_name=cd['room_name']) if room: messages.error(request, 'a room with this name is already exists', 'danger') return render(request, self.template_name, {'form': form}) privateroom_slug = slugify(cd['room_name'][:25], allow_unicode=True) privateroom = Room(room_name=cd['room_name'], slug=privateroom_slug) privateroom.set_is_private(True) privateroom.set_password(cd['password']) privateroom.save() messages.success(request, f"Room {cd['room_name']} created", 'success') return redirect('room:room_inside', privateroom.id, privateroom.slug) messages.error(request, 'not valid', 'danger') return render(request, self.template_name, {'form': form}) I'll be happy if anyone gives me the Idea so I can add this feature. -
StreamingHttpResponse works like HTTP response on server
I am using StreamingHttpResponse for SSE but it works like and http response on server class WorkshopNotificationAPIView(View): def get(self, request, *args, **kwargs): res = StreamingHttpResponse(BusinessService.workshop_notification(kwargs.get('workshop'), kwargs.get('type'))) res['Content-Type'] = 'text/event-stream' return res def workshop_notification(self, workshop_id: str, workshop_type: str): initial_data = "" while True: data = list(DB['workshop_gocoin_transactions'].find({'workshop_id': workshop_id, 'type': TransactionType.Credit}, {'_id': 0, 'source': 1, 'remark': 1}).sort('created_at', -1).limit(1)) if data and not initial_data == data[0]: initial_data = data[0] yield "\ndata: {}\n\n".format(data[0]) enter image description here enter image description here -
SQL Django Null Constraint Error - cannot resolve?
What am I doing wrong? Django Models: USER MODEL class User(AbstractUser): # DEFINE MODEL FIELDS related_person = models.OneToOneField(Person, on_delete=models.CASCADE, default='') user_id = models.BigAutoField(verbose_name='User ID', primary_key=True, serialize=False, auto_created=True) email = models.EmailField(verbose_name='Email', max_length=80, blank=False, unique=True, null=False, default='') is_verified = models.BooleanField(verbose_name='Email Verified', blank=False, default=False) date_joined = models.DateField(verbose_name='date joined', auto_now_add=True, null=True) last_login = models.DateField(verbose_name='last login', auto_now=True, null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = None last_name = None username = None # IMPORT MODEL MANAGER CLASS objects = UserManager() # SET LOGIN FIELD USERNAME_FIELD = 'email' # SET REQUIRED FIELDS REQUIRED_FIELDS = ['is_verified'] PERSON MODEL class Person(models.Model): class Titles(models.TextChoices): MR = 'Mr', _('Mr') MRS = 'Mrs', _('Mrs') MISS = 'Miss', _('Miss') MS = 'Ms', _('Ms') DR = 'Dr', _('Dr') related_entity = models.OneToOneField(Entity, on_delete=models.CASCADE) person_id = models.BigAutoField(verbose_name='Person ID', primary_key=True, serialize=False, auto_created=True) first_name = models.CharField(verbose_name='First Name', max_length=50, blank=False, null=False) last_name = models.CharField(verbose_name='Last Name', max_length=50, blank=False, null=False) title = models.CharField(verbose_name='Title', max_length=4, choices=Titles.choices, blank=True, null=False, default='') alias = models.CharField(verbose_name='Alias', max_length=150, blank=True, null=False) I have a Sign Up form that saves a person's email to the User Model, and password to the User Model, after checking the email doesn't already exist, and passwords (when entered twice), match. but then I get this … -
Count objects from a merged queryset
I've developed a Django's view that merge two queryset. def single_sharedcategory(request, slug): object = get_object_or_404(SharedCategories, slug=slug) wms = OGCLayer.objects.filter(categories=object) webgis = WebGISProject.objects.filter(categories=object) context = { "single_object": object, "objects": list(chain(wms, webgis)), } template = "shared-categories/single_shared_categories.html" return render(request, template, context) I need to view in the template how many objects are related to objects. I know that it is possible to get a count of objects for a single model with {{ wms.related_wms.count }}. But how I can do the same thing in my case? -
How can I show an error message If the username already exists for creating an account?
When I go to create a new account by the same user name that already exists in the database, then shows the below error. I just want to show an error message (the user already exists, try again with a unique username) if the users exist. How can I fix these issues? What will be the condition? Problem: IntegrityError at /singup UNIQUE constraint failed: auth_user.username Request Method: POST Request URL: http://127.0.0.1:8000/singup Django Version: 3.2.3 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: auth_user.username Exception Location: C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\Business_Website', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32\\lib', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\Pythonwin', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Mon, 28 Feb 2022 18:15:25 +0000 views.handle_singUp: def handle_singUp(request): if request.method == "POST": userName = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] #pass2 = request.POST['pass2'] myUser = User.objects.create_user(userName,email,pass1) myUser.first_name = fname myUser.last_name = lname myUser.save() messages.success(request,"Your account has been created!") return redirect("/") else: return HttpResponse("404-Not found the page") urls.py: urlpatterns = [ path('', views.index, name="index"), path('singup', views.handle_singUp, name= "handle_singUp"), path('login', views.handle_login, name="handle_login"), path('logout', views.handle_logout, name="handle_logout"), path('contact', views.handle_contact, name="handle_contact"), path('frontend_orders', views.frontend_orders, name="frontend_orders"), path('hire_me', views.hire_me, name="hire_me") ] -
Override a specific argument in all django model queries?
I have a custom django user model that does not contain a username field, it uses email instead. I am attempting to implement a 3rd party package that makes queries to the user model based on username. Is there a way to override all queries (get, filter, etc.) to this model through a custom manager or otherwise so that username is simply converted to email? It would turn this: User.objects.filter(username="grrrrrr@grrrrrr.com") into User.objects.filter(email="grrrrrr@grrrrrr.com") -
How to avoid polling the server for each individual result - htmx
I've got 3 django-celery tasks running independently, they each finish at different times and take anywhere between 20-45 seconds. I could poll the server through 3 different hx-triggers in order to get my 3 different results as they become available, however this seems like unnecessary load on the server, as I'd like to poll every 5 seconds. Ideally I'd just have 1 hx-trigger set up which polls for all 3 results and then places the results in their divs when they become available but I'm not sure how to achieve this - I can alter the front end, if needed, to make it possible. -
How to change add another[object] behavior in TabularInline
I want to make admin InlineTabular add another object button take me to the object add page with prepopulated fields instead of creating an inline model Add Another[Object] button I tried to override the html and add hard coded url in in the tag by sending extra context in my admin model but it didn't work class SupplierAdmin(admin.ModelAdmin): inlines = [ProductViewInline,] def change_view(self, request, object_id, form_url='', extra_context=None): extra = extra_context or {} extra['ProductUrl'] = 'http://localhost:8000/admin/products/product/add/' return super(SupplierAdmin, self).change_view(request, object_id, form_url, extra_context=extra) # Tabular.html <script> ProductUrl = '{{ ProductUrl }}' </script> # Inline.js const addInlineAddButton = function() { ... $parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + `"><a href=ProductUrl>` + options.addText + "</a></tr>"); addButton = $parent.find("tr:last a"); } else { ... -
my getjson is not working can someone help me
I get the data with a fetch url. the whole function works, there are no errors. there is only one error and that is that is can't see the data on tamplate. the data is being fetched, I see that on console. Thanks in advance... views.py def check(request): if request: if request.method == 'POST': data = json.loads(request.body) employeId = data['id_s'] empinfo = Employe.objects.filter(id=employeId) print(empinfo.values) print(data) return JsonResponse({'info': list(empinfo.values())}, safe=False, status=200) return HttpResponse() index.html <script type="text/javascript"> $(document).ready(function() { $(".info-employe").click(function(event){ $.getJSON('/checks/', function(response) { for(var key in response.info) $('#name').append('<p> Name: ' + response.info[key].name + '</p>'); $('#surname').append('<p>Surname : ' + response.info[key].surname + '</p>'); $('#worknumber').append('<p> Work number: ' + response.info[key].work_number + '</p>'); $('#workplace').append('<p> Rank: ' + response.info[key].rank + '</p>'); $('#rank').append('<p> Workplace: ' + response.info[key].workplace + '</p>'); $('#email').append('<p> Email ' + response.info[key].email + '</p>'); $('#phone').append('<p> Phone ' + response.info[key].phone + '</p>'); }); }); }); </script> javascript fetch function function checkEmp(id_s, action){ var url = '/checks/' fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'id_s': id_s, 'action': action}) }) .then((response)=>{ return response.json() console.log(response); }) .then((data)=>{ console.log(data); }) } -
Why is Sweetify not working on my project?
Sweetify does not work in my project. I went ahead according to document but it does not work Does anyone know what the problem is? this is my view enter image description here -
Take CSV file from HTML form and create a table in sqllite in django
Right now I've tried using pandas and converting the file into json and then creating a table with it. This my code HTML File <body> <form action="upload/" method="post" enctype="multipart/formdata"> {% csrf_token %} <div class="block has-text-centered"> <h3 class="is-size-3 has-text-centered is-family-primary has-text-success-dark" > Upload a CSV File </h3> <div class="file is-medium has-name is-info is-centered" id="csv-file"> <label class="file-label"> <input class="file-input" type="file" name="csv" accept=".csv" /> <span class="file-cta"> <span class="file-icon"> <i class="fas fa-upload"></i> </span> <span class="file-label"> Choose a file… </span> </span> <span class="file-name"> No file uploaded </span> </label> </div> <br /> <input class="button is-outlined is-rounded is-info" type="submit" value="Submit" /> <input class="button is-outlined is-rounded is-info" type="reset" value="Reset" id="csv-reset" /> </div> </form> </body> </html> VIEWS File from django.shortcuts import render def home(request): return render(request, 'results/home.html', {}) CSV LOGIC (csvviews.py) from django.shortcuts import render import pandas as pd from django.contrib import messages def form_page(request): if request.method == 'POST': file = request.FILES.get(u'csv') df = pd.read_csv(file) df.to_json(turned_json) my_obj = CsvModel.objects.create(csv_file=turned_json) my_obj.save() messages.success(request, 'CSV Uploaded!') return render(request, 'results/home.html') MODELS File from django.db import models class CsvModel(models.Model): csv_file = models.FileField() But using this code I'm getting the following error Invalid file path or buffer object type: <class 'NoneType'> How do I solve this? Are there any specific packages for csv in django? … -
image being re-uploaded when updating object
On my blog post model I override the save method to call a function to compress the image being uploaded. This works as expected. However when I use an update view and make a change to the post the image is then re uploaded to the s3 bucket and replaces the original image on the model. If i remove all the code from the compress function and just have it return image, when using the update view it does not re upload the image. How can I prevent the image from being re uploaded when on the updateview. model: def compress(image): img = Image.open(image) img = img.convert("RGB") (w, h) = img.size # current size (width, height) if w > 2000: new_size = (w//2, h//2) # new size img = img.resize(new_size, Image.ANTIALIAS) (w, h) = img.size if w > 2000: new_size = (w//2, h//2) # new size img = img.resize(new_size, Image.ANTIALIAS) im_io = BytesIO() img.save(im_io, 'JPEG', quality=70, optimize=True) new_image = File(im_io, name=image.name) return new_image class Post(models.Model): image = models.ImageField(storage=PublicMediaStorage(), upload_to=path_and_rename, validators=[validate_image]) .... def save(self, *args, **kwargs): self.slug = slugify(self.title) if self.image: # call the compress function new_image = compress(self.image) # set self.image to new_image self.image = new_image super(Post,self).save(*args, **kwargs) view: class …