Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Migration Errors 1064
Hey guys I am trying to migrate my data in django using python manage.py migrate command but I keep getting this error and I do not know what could be the problem mind you am new in django I have tried to drop the database then made the database again in Mariadb and made the migrations again using python manage.py make migrations and then tried to migrate again using python manage.py migrate and I keep getting the same error shown below django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'b'30') NOT NULL, help_text longtext NULL, data_type varchar(100) NOT NULL, `' at line 1") This is the error I get when I try to migrate it using python manage.py migrate django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'b'30') NOT NULL, help_text longtext NULL, data_type varchar(100) NOT NULL, `' at line 1") -
Conditional files block in ebextensions
I have two environments for the same application I want to run files block command based on some environment variable, that is, I don't want to create files for one environment. files: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash -
Multiprocessing in for loop - django
I have a very large list say of 10000s, And I am trying to check whether a key is present in a json, if not I have to add it. Here is the sample code, with open('filename', 'rt') as f: data_obj = json.loads(f.read()) for item in items: try: key = data[item.lower()] #<my code> except Exception as e: data = item with open('filename', 'w') as outfile: # have to create a data.json file json.dump(data, outfile) I have 2 issues, Iteration itself is taking so long. Write operation is consuming additional time. In short, its taking minutes to get the response for 900 items of the list. I would like to use multiprocessing here. I am using the following the sample code to implement it, def try_multiple_operations(items): for item in items: try: api.my_operation(item) except: print('error with item') executor = concurrent.futures.ProcessPoolExecutor(10) futures = [executor.submit(try_multiple_operations, group) for group in grouper(5, items)] concurrent.futures.wait(futures) but try_multiple_operations is taking only one argument but in my case, I have more than 2 arguments. how should I use multiprocessing for the need? -
Kill a running subprocess with a button click
I'm running strandtest.py to power a neo pixel matrix on a django server. A button click runs the program I'd like a second button click to kill it. I've read a bunch of different solutions but I am having trouble following the instructions. Is there another subprocess command I can execute while the program runs? This is how I start the program import subprocess def test(request): sp = subprocess.Popen('sudo python /home/pi/strandtest.py', shell=True) return HttpResponse() I want to kill the process and clear the matrix -
Loop over two lists and append items in django model
I have two lists A and B: A: [<truck_name: Tempo 407 1500>, <truck_name: Tempo 407 1500>] B: [{<Truckdb: Truckdb object (136)>: [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>]}, {<Truckdb: Truckdb object (254)>: [<ItemBatch: Iphone>, <ItemBat ch: Iphone>, <ItemBatch: Iphone>]}] I looped over both of them and tried to save the list in dictionaries to a model. The list I want to save is this: [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>] Code: for i in range(len(truck_objects)): for j in range(len(master_values)): if i==j: DispatchPlan.objects.create(truck_name=truck_objects[i],items=master_values[something here]) How can I do that? what do i replace "something here" with so that I get the list? -
How to show query result with selectize.js in Django
I want to the taking ajax response.then show select list attribute in Django Template. I take data with ajax request but select list components does not show result of query. How can I fix this problem -
why django-admin.py startproject and django-admin startproject are the same when there is no file named admin.py
django-admin.py startproject projectname django-admin startproject projectname when typing any of these, one folder named the projectname and two files db.sqlite3 and manage.py creates -
How to delete object using function based view?
I am having trouble trying to implement a delete function-based view as I am unsure of what is the correct syntax. So far this is the method that I am using: def delete_lesson(request, post_id): if request.method == 'POST': lesson = Lesson.objects.get(post_id=request.get('post_id')) lesson.delete() return redirect('/') I have implemented the delete function in my model: class Lesson(models.Model): title = models.CharField(max_length=100) file = models.FileField(upload_to="lesson/pdf") date_posted = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('lesson_upload', kwargs={'pk': self.pk}) def delete(self, *args, **kwargs): self.file.delete() self.title.delete() super().delete(*args, **kwargs) class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default = 'default0.jpg', upload_to='course_image/') description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default = 0) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) My urls.py: path('post/<int:post_id>/lesson_delete/', views.delete_lesson, name='delete_lesson'), -
How to call function of model in view file in django
I was created def function in model.py file and now i want to get this function in view.py file. I know how to get this function in template file but i dont know how to get this function in view file for example: In model.py file: class CartItem(models.Model): # cart = models.ForeignKey("Cart") cart = models.ForeignKey( 'Cart', on_delete=models.CASCADE, ) product = models.ForeignKey(product_models.Product,on_delete=models.CASCADE) item = models.ForeignKey(product_models.ProductDetails,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def __unicode__(self): return self.item.title @property def item_week_real_total(self): return self.item.get_week_price() * self.quantity In view.py file cart_item = CartItem.objects.filter(cart_id=request.session['cart_id']) for cart_item_data in cart_item: week_total = cart_item_data.item_week_real_total() But i got error 'decimal.Decimal' object is not callable -
Dont know what data to return for ajax in django?
I want to make my like button asynchronous using JavaScript, in can like a post and once i refresh the page the like count is increased but i want the like count to increase without refreshing. I am trying to do this in pure JavaScript without the use of any framework just so that i know how it truly know how it works. Can someone explain what is should return if request.is_ajax() is True. '''python class PostModel(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) title = models.CharField(max_length=50) message = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') def __str__(self): return self.title objects = PostManager() def get_absolute_url(self): return reverse("birdpost:detail", kwargs={"id": self.id}) def get_like_url(self): return reverse("birdpost:like-toggle", kwargs={"id": self.id}) ''' '''python class PostLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): id_ = self.kwargs.get("id") request = self.request obj = get_object_or_404(PostModel, id=id_) url_ = obj.get_absolute_url() user = self.request.user liked = False updated = False if user.is_authenticated: if user in obj.likes.all(): obj.likes.remove(user) liked = False else: obj.likes.add(user) liked = True updated = True data = { "liked": liked, "updated": updated } if request.is_ajax: print("AJAX Call.") return url_ ''' var likeButton = document.getElementsByClassName("like-btn"); for (var i = 0; i < likeButton.length; i++){ likeButton[i].addEventListener('click', function(event){ event.preventDefault() var likeEndPoint = this.getAttribute("href"); if (window.XMLHttpRequest) … -
Why use custom authentication backend in django?
I've been developing a custom authentication backend for my django app and I'm not entirely sure I understand what advantages and disadvantages a custom authentication backend provides over just implementing the authentication logic in a view. I do understand that this kind of design is modular, and so there's a separation of concerns by breaking up the code in this way, but are there other pros and cons that I'm not seeing? -
Django change values automatically before migrating
I want to migrate my model. It has got a new field wich has null=False active. Normally pre_save sets a value but that's not working on a migration. So I tried to add a pre_migrate receiver but that didn't work either. I read Django's documentation https://docs.djangoproject.com/en/2.2/ref/signals/#pre-migrate but it says nothing about an instance object. So.. is this not possible? @receiver(pre_save) @receiver(pre_migrate) def pre_saver(sender, instance, **kwargs): if issubclass(sender, RandomIDMixin): if instance.id is None or instance.id is "": instance.id = instance.create_id() -
How to create an attendance system with django?
Currently i am working a project for making a student management system for my college. I have a User model and a profile model. I also added an attendance model with User as the foreign key. I was stuck in while i started writing the form for entering the attendance. class Attendance(models.Model): Student = models.ForeignKey(User, on_delete=models.CASCADE) Hour = models.CharField(max_length=1, blank=False) Subject = models.CharField(max_length=8, blank=False) Date = models.DateTimeField(default=timezone.now) Presence = models.BooleanField(default=False, blank=False) def __str__(self): return f'{self.Student}' This is my template where query set is names of Users that should be the default value. The number of Users, the number of forms should come. With this template i can create only one object, with the values of the last form iterated. When the <form> is inside forloop i get multiple objects with the same values of lastly iterated form. <form method="POST" action="{% url 'academics' %}" style=" padding: 5%"> {% csrf_token %} {% for query in queryset %} <input type="text" name="Student" class="form-control" required id="id_Student" value="{{query}}"> <input type="text" name="Hour" class="form-control" required id="id_Hour"> <input type="text" name="Subject" class="form-control" required id="id_Subject"> <input type="checkbox" name="Presence" required id="id_Presence"> {% endfor %} <button type="Submit">Submit</button> </form> I came to know about formsets, but i don't know how to implement for a … -
Updateview create new record on update
I have model with slugfield as primary key. i have updateview when i hit update button it create new object. eg: old record : title = data 1 update entry : title = data 2 output : data 2 data 1 models.py class mymodel(model.Models): slug = models.SlugField(max_length=200, unique=True, primary_key=True, auto_created=False) title = models.CharField(max_length=200) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(mymodel, self).save(*args, **kwargs) forms.py class myupdateform(forms.ModelForm): class Meta: model = mymodel fields = ('__all__') views.py class myupdateview(generic.UpdateView): template_name = 'update.html' model = mymodel context_object_name = 'mymodel_obj' form_class = myupdateform urls.py path('myupdate/<slug:slug>/edit/', myupdateview.as_view(), name='myupdate') -
Empty page when creating data-url to download d3.js graph as svg
I am trying to download a graph that I created with D3.js to a png (any other format would do though), very much unsuccessfully. I am trying to create a data-url and then pass it to a function which should allow me to download it. Like so: First I want to create a function to create data-urls: function svgDataURL(argument) { var svgAsXML = (new XMLSerializer).serializeToString(argument.node()); return "data:image/svg+xml," + encodeURIComponent(svgAsXML); } Next I am saving my url with my svg as argument in a varaiable: var dataURL = svgDataURL(svg) console.log(dataURL) when debugging this outputs the following: data:image/svg+xml,%3Cg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20transform%3D%22translate(100%2C20)%22%3E%3Crect%20class%3D%22bar%22%20width%3D%225.244670050761421%22%20y%3D%22394.44444444444446%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%22526.3857868020305%22%20y%3D%22338.8888888888889%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2257.3502538071066%22%20y%3D%22283.3333333333333%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%22840%22%20y%3D%22227.77777777777777%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%225.116751269035533%22%20y%3D%22172.22222222222223%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2256.96649746192893%22%20y%3D%22116.66666666666666%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2260.079187817258884%22%20y%3D%2261.1111111111111%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2229.932994923857866%22%20y%3D%225.555555555555543%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2257.3502538071066%22%20y%3D%22172.22222222222223%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Cg%20transform%3D%22translate(0%2C450)%22%20fill%3D%22none%22%20font-size%3D%2210%22%20font-family%3D%22sans-serif%22%20text-anchor%3D%22middle%22%3E%3Cpath%20class%3D%22domain%22%20stroke%3D%22currentColor%22%20d%3D%22M0.5%2C6V0.5H840.5V6%22%2F%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0.5%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E0%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(85.77918781725889%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E2%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(171.05837563451777%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E4%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(256.33756345177665%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E6%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(341.61675126903555%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E8%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(426.8959390862944%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E10%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(512.1751269035533%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E12%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(597.4543147208122%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E14%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(682.7335025380711%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E16%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(768.0126903553299%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E18%2C000%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3Cg%20fill%3D%22none%22%20font-size%3D%2210%22%20font-family%3D%22sans-serif%22%20text-anchor%3D%22end%22%3E%3Cpath%20class%3D%22domain%22%20stroke%3D%22currentColor%22%20d%3D%22M-6%2C450.5H0.5V0.5H-6%22%2F%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C419.44444444444446)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding1%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C363.8888888888889)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding2%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C308.3333333333333)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding3%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C252.77777777777777)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3ETradeCenter%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C197.22222222222223)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding13%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C141.66666666666666)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding8%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C86.1111111111111)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding7%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C30.555555555555543)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding6%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fg%3E I am assuming that this is the data link to my svg I want to create. But hey, it looks kinda long and wrong. So maybe I am already going the wrong way here. finally I call my download function and pass my URL function download(){ var dl = document.createElement("a"); document.body.appendChild(dl); dl.setAttribute("href", dataURL); dl.setAttribute("download", "graph.svg"); dl.click(); } Ok fail, it doesn't work. When I open the link or click on my download link I get an empty page. Has anyone an idea where I go wrong? Any help is very much appreciated. Here is my graph btw: var data = build // set the … -
Error on running django server: ModuleNotFoundError: No module named 'django_forms_bootstrap'
On trying to run the server for the following project https://github.com/hschafer2017/django-MultiUsers, I get this error: return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_forms_bootstrap' I have installed requirements.txt and also tried: pip install boostrap3 and pip install django-bootstrap-form but the same error occurs. Does anyone have any suggestions as to how I could resolve this problem and run the server without any errors? -
Problem importing the right package with uwsgi and django
I have an error in my django app in deployment using uwsgi. import error ... profile is not a package I have a profile app listed in settings and sys.path.insert(0, project_base('apps/')) where the profile app is located. the profile app has a file init.py in it. the probleme is that localy I dont have this problem only in deployment. I have tried to install uwsgi with pip3 when I searched in python directory I found a profile module, I have a doubt that django is importing this module instead of my package. uwsgi --http :8000 --enable-threads --single-interpreter --disable-logging --socket /tmp/uwsgi.sock --die-on-term --ignore-sigpipe --master --http-keepalive --processes 4 --chdir /opt/app --wsgi-file project/wsgi.py --check-static /opt/public_assets --static-map /static=/opt/public_assets --static-map /favicon.ico=/opt/public_assets/favicon.png --buffer-size 62768 def project_base(f=''): return os.path.join(BASE_DIR, f) sys.path.insert(1, project_base()) sys.path.insert(0, project_base('apps/')) INSTALLED_APPS = [ 'djangocodemirror', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'school', 'profile', 'graphql_core', ..... ]``` ModuleNotFoundError - degree.models in <module> No module named 'profile.models'; 'profile' is not a package -
Return data via Ajax whenever Firestore real time update is fired in Django
Am trying to listen to real-time updates with firestore in three steps: 1) Invoking the listener via Ajax. 2) Listener invokes and executes. 3) The populated list is returned. The problem is: 1) The data is returned when the page is refreshed twice. 2) The listener 'modified' event is fired but data is not returned via ajax. The question is: 1)Why Ajax does not get the data each time Django returns? 2) How can I successfully get the data in Ajax every time Django returns? Here is my code views.py data_list = [] # on_snapshot listener def on_snapshot(col_snapshot, changes, read_time): request = HttpRequest() data_list.clear() try: for change in changes: if change.type.name == 'ADDED': val_list.append(change.document.id) val_list.append(change.document.to_dict()) data_list.append(val_list) elif change.type.name == 'MODIFIED': val_list.append(change.document.id) val_list.append(change.document.to_dict()) data_list.append(val_list) return get_data(request) except Exception as e: return JsonResponse("failed", safe=False) # returns data def get_data(request): return JsonResponse(data_list, safe=False) # invokes listener def invoke_listener(request): if request.method == 'POST': id_token = request.POST.get('idToken') decoded_token = auth.verify_id_token(id_token) uid = decoded_token['uid'] try: col_query = db.collection(u'cities').where(u'state', u'==', u'CA') query_watch = col_query.on_snapshot(on_snapshot) return JsonResponse('invoked successfully', safe=False) except Exception as e: return JsonResponse("failed", safe=False) else: return JsonResponse("failed", safe=False) Javascript file. Ajax code // listener invoked on page load via ajax document.addEventListener('DOMContentLoaded', function(){ firebase.auth().onAuthStateChanged(function(user) { firebase.auth().currentUser.getIdToken(true).then(function(idToken) { … -
How to apply django transaction to every celery task?
from celery.task import Task from django.db import transaction class MyTask(Task): # ... def run(self, *args, **kwargs): # doesn't work with transaction.atomic(): super().run(*args, **kwargs) celery_task = celery_app.task(ignore_result=True, base=MyTask) @celery_task # @transaction.atomic # this should work, but I want to add transaction through base task class def foo_task(): pass I need to add an atomic transaction to every task with celery_task decorator without using additional decorators. -
How to check if requested data exist
I have a problem with data support. I pass in template different names of variables. When I send one variable i've got error: Exception Type: MultiValueDictKeyError. I send to view variables named btn, delete and undo. I've done it in this way try: task = List.objects.get(id=data['undo']) except: try: task = List.objects.get(id=data['delete']) except..... And that is working properly but i've got a challange to do it in better way. But when i deleted my try-except block and pass to view for example only data['undo'] i've got error Exception Value: 'btn' Is there any way to check which variable exists in view and use it? -
ListView filter according to Model
I have a ListView and it works as follow Logged in user creates an Album (The parent class) Adds pictures (children) to the album Pictures show up when that particular Album is selected The ListView But my query is returning an empty value. Please help I don't know where I am going wrong with the query. My deadline is approaching in 2 days. model.py class AlbumData(models.Model): album_user = models.ForeignKey(User, on_delete=models.CASCADE) album_name = models.CharField(max_length=50) class AlbumPictures(models.Model): album_relation = models.ForeignKey(on_delete=models.CASCADE) pic_title = models.CharField(max_length=50) content_pic = models.ImageField(upload_to='Pictures', blank=False, null=False) View.py class AlbumPicturesList(ListView): model = AlbumPictures template_name='userfiles/AlbumPicsList.html' def get_queryset(self, *args, **kwargs): return AlbumPictures.objects.filter(album_relation_id = self.request.GET.get('AlbumData_id')) -
How can i find total number of login in Django application by user?
In Django User table we can check last_login, But i want to check total number of login in month by user. Is that any function where i can use directly in my system. OR Am i need make change on login view, when every-time user will login then i can create entry in Django Model? I want to data like this: Users JunLogin FebLogin Virat 10 30 Sachin 9 11 Please suggest me the best way. Thanks in Advance -
Trying to Post some info to DRF API but being met with 403 forbidden error using Python Requests
I am trying to GET access to my DRF API and I am trying to authenticate against my API but I cannot post my username/password (Data) as I get a 403 HTTP Error before I was getting a Forbidden (CSRF cookie not set.) error then I changed my view to a DRF Class based view now I am stuck on this error unable to POST anything to my API REQUESTS (Outside the Django Project) payload = {'username': 'user', 'password': '****'} r = requests.get('http://website/api/login/', data=payload) urls app_name = 'api' urlpatterns = [ url(r'^login/$', views.login_to_api.as_view(), name = "login_to_api"), Views class CustomerListAPIView(generics.ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class CustomerRetrieveAPIView(generics.RetrieveAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class login_to_api(APIView): def post(self, request): if request.method == "POST": (logic) HTML <form id="login-form" method="post" action="{% url 'api:login_to_api' %}" > {% csrf_token %} <table class="table"> <tr> <td><label >Username</label></td> <td><input id="username" name="username" type="text" class="form-control"></td> </tr> <tr> <td><label >Password</label></td> <td><input id="password" name="password" type="password" class="form-control"></td> </tr> {%csrf_token%} </table> <input type="submit" value="Login" class="btn btn-primary pull-right" /> settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', #'rest_framework.authentication.SessionAuthentication', )#,'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Any Help would be … -
Save form data into Excell file send as msil
I have formset form with provided input. With click on button, an pop-up opens for user to enter email and after clicking submit, data of formset should mailed to given email Id. Can anyone help me for this. I have read django-import-export. I can send mail using python. I just need way to convert form data into Excell. Thanks in advance. -
ajax url append on current url on document ready and giving 302 error
current href is "http://127.0.0.1:8000/report-page/34" In back it should be /sort-list but it is appending after "/report-page" like "GET /report-page/sort-list HTTP/1.1" 302 0 Actually for some reason on previous request I have send id on url and I need that. $(document).ready(function() { $.ajax({ url: "sort-list", type: "GET", headers: { "X-CSRFToken": $.cookie("csrftoken") }, success: function(response){ } }); });