Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Azure and Django error: "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable"
I believe the error I am getting is due to how Django is trying to serve the static files. The default azure landing page works but as soon as I go to /admin/ I get the error message: "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable" This here is the static files infomation from the Settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), #'/var/www/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn') //used in development MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media_cdn')//used in development and in D:\home\site\wwwroot\static I have got the following web.config from this answer here: IIS7, web.config to allow only static file handler in directory /uploads of website -
Debug Django unit tests with multiple databases and apps - Circular d
I've integrated a small app to a multi-application project. Every application has its own database. Tests were running fine when the app was isolated but now they almost all fail, for different reasons. I'd like to debug these tests using Pycharm debugger (like I used to with the isolated app). However when I run the test I get this exception. django.core.exceptions.ImproperlyConfigured: Circular dependency in TEST[DEPENDENCIES] The problem is that if I don't use the databases settings (Django 2.2), I get this error (as expected) : {AssertionError}Database queries to 'app_db' are not allowed in this test. Add 'app_db' to app.tests.test_models.ModelTestCase.databases... Below is a sample of my unit tests. class ModelTestCase(TransactionTestCase): databases = {'sycoma2_db'} def setUp(self): pass def test_app_ready(self): """ comment :return: """ from django.apps import apps app = apps.get_app_config("app") app.ready() self.failUnlessEqual(Group.objects.using("app_db").all().count(), 14) -
Nested loop to access dictionary Django HTML
I have list of Column title like this ColumnName = ['Latitude', 'Longitude', 'Depth'] and a dictionary with format like this MyDict = [{'Latitude': '75', 'Longitude': '37', 'Depth': 6.0}, {'Latitude': '23', 'Longitude': '97', 'Depth': 2.3}, {'Latitude': '55', 'Longitude': '14', 'Depth': 1.9}] i want to make table with that data and access a dictionary value by its key from a list. And i have tried with this code in my django HTML but it doesnt work <table> <thead> <tr> {% for ColName in ColumnName %} <th> ColName <th> {% endfor %} <tr> </thead> <tbody> {% for i in MyDict %} <tr> {% for x in ColumnName %} <td> {{i.x}} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> i want to access that data with {{i.x}} but it doesnt work -
Django Forms with Custom Location Widget
I am working on creating a form that allows the user to create a Scavenger Hunt. One of the fields I need is the city, state, and country that the hunt is occurring in. I have a form in Django right now, but it just generates a text field for the user to type in this information. However, I'd like to use the Teleport Location Autocomplete widget (https://developers.teleport.org/api/getting_started/#search_name), but I'm not sure how I could implement this within Django. Is there a way to do so? -
Button for update a blog post
I've a trouble to create correctly a button based on Bootstrap 4.3 with wich activate the update of a post. I've created this view: def updatePost(request, slug_post=None): update_post = get_object_or_404(BlogPost, slug_post=slug_post) form = BlogPostForm(request.POST or None, request.FILES or None, instance=update_post) if form.is_valid(): update_post = form.save(commit=False) update_post.slug_post = slugify(update_post.title) update_post.save() return redirect('post_list') context = { 'form': form, } template = 'blog/editing/create_post.html' return render(request, template, context) and this path: path("blog/<str:slug_post>/update/", views.updatePost, name='update_post'), But when I use this button: <button class="btn btn-primary btn-lg mt-2" href="{% url 'update_post' %}">Update</button> I see this error message: Reverse for 'update_post' with no arguments not found. 1 pattern(s) tried: ['blog/(?P[^/]+)/update/$'] The strange thing is that if I write the link to the update into the addres bar I can update my post. For exampe: I've this link to a post: /blog/title-slug-post/. If I digit /blog/title-slug-post/update/ it is possible for me to update the post. What I've wrong? -
Format django-admin CMS content in ReactJS front-end from REST api
I recently decided to dive into JavaScript and ReactJS to start making a single page application. I have created the back-end for my project with django rest framework, and plan on using the django-admin gui as my CMS for now. Here is my django model for one of the api: class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField() image = models.ImageField(upload_to = 'images/') body = models.TextField() time = models.DateTimeField() author = models.ForeignKey( 'auth.user', on_delete=models.CASCADE, ) def __str__(self): return self.title I can consume this content just fine with react using axios, and it allows me to format the structure in a minimal way. For example: class Projects extends React.Component { state = { home: [] }; componentDidMount() { this.getHome(); } getHome() { axios .get('http://192.168.1.19:8000/api/projects/') .then(res => { this.setState({home: res.data}); }) .catch(err => { console.log(err); }); } render() { return( <div class="posts"> {this.state.home.map(item => ( <div key={item.id}> <img src={} alt="placeholder" /> <h1>{item.title}</h1> <h5>{item.description}</h5> <br /> <p>{item.body}</p> <br /> <p>Posted at: {item.time}</p> <br /> </div> ))} </div> ); } } This is a very basic mock-up for now just to represent the data is able to read from the api. I need to be able to format the content within {item.body}. I'm currently … -
Apache mod_wsgi memory cache with multiple daemon processes
I have a fairly large Django REST Framework API WSGI website, with 60,000 endpoints. This is deployed to servers running Apache 2.4.6 with Python 3.6.8 and mod_wsgi 4.6.2. I've implemented several tricks (such as lazily loading models) which have made it very fast. The only exception to this is when it is first published: it takes about two minutes to spin up whenever we publish a new version to our integration or production environments. That's fine for us, as subsequent page loads are nearly instant. I am assuming this is because elements of the Django project, such as the URL dispatcher for the 60,000 endpoints, get cached in memory. However, if I change the the processes value to anything other than the default of 1, every page takes the ~2 minutes to load. Here's the relevant part of my current VirtualHost configuration: <VirtualHost *:443> TimeOut 600 ServerName mysite-develop.wharton.upenn.edu # Set to the GLOBAL Application Group WSGIApplicationGroup %{GLOBAL} # Pass Authorizations through to the WSGI app for Django REST Framework Token Auth WSGIPassAuthorization On WSGIDaemonProcess mysite-develop-https processes=1 python-home=/var/django/mysite/sites/mysite-develop/venv request-timeout=600 user=mysite group=mygroup WSGIProcessGroup mysite-develop-https WSGIScriptAlias / /var/django/mysite/sites/mysite-develop/config/wsgi.py process-group=mysite-develop-https <Directory /var/django/mysite/sites/mysite-develop/config> Require all granted </Directory> </VirtualHost> Is there any way to get the … -
Why won't Django template won't recognize list from object field?
I have an object field that stores a list. The Django template is treating the list like a string, it iterates over each character, not each list value. Tried saving the object field in various ways, "['1','2']" and "1,2". Tried the "|make_list" filter. {% for list_value in object_field.value_options %} <option>{{ list_value }}</option> {% endfor %} I was hoping for: <option>1</option> <option>2</option> But I am getting: <option>[</option> <option>'</option> <option>1</option> <option>'</option> <option>,</option> <option>'</option> <option>2</option> <option>'</option> <option>]</option> -
How to get an object with a form and then send it to the next view using urls?
I'm trying to send an object obtained with a ModelChoiceField into a view via urls and views parameters by I don't think that's the right method. I don't know if I have to use POST or GET method. When I use the GET method, the object is displayed in the url but the view stay the same. With the POST method, django send errors messages about parameters. My form class IndividuForm(forms.Form): individu = forms.ModelChoiceField(queryset=Individu.objects.all() Here's the view with the form def index(request): individu_form = IndividuForm(request.GET or None) if individu_form.is_valid(): individu_id = individu_form.cleaned_data['individu'].id HttpResponseRedirect('%i/raison/' % individu_id) return render(request, 'derog_bv/index.html', {'individu_form':individu_form}) The template where the form is displayed <form action="{% url 'index' <!-- Errors when I put parameters here --> %} method="<!-- GET or POST -->"> {% csrf_token %} {{ form }} <input type="submit">Suivant</input> </form> The view where I want to get my object def raison(request, """ error with this parameter : individu_id"""): individu = get_object_or_404(Individu, pk=individu_id) -
How to track API usage with DjangoRestFramework Tracking
Trying to use DRF-Tracking and I seem to be doing everything correctly, but it's simply not logging in the info So far what I have in in my polls\views.py app which has two models Questions and Choices from rest_framework_tracking.mixins import LoggingMixin Then in my api/views.py I have from rest_framework import generics from rest_framework.response import Response from rest_framework_tracking.mixins import LoggingMixin class LoggingView(LoggingMixin, generics.GenericAPIView): def get(self, request): return Response('with logging') -
Can't send array data to REST endpoint
I am using Django REST framework. I have a model that looks like this: class Post(models.Model): title = models.CharField(max_length=100, null=False) content = HTMLField() created_at = models.DateField(auto_now_add=True) authors = models.ManyToManyField(User) With an api view and serializer that looks like this: class CreateStoryApiView(CreateAPIView): serializer_class = PostSerializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('title', 'content', 'authors') Going to the actual endpoint, I can actually submit successfully. I am trying to use Ajax to take the details and submit the data to the endpoint, but for some reason I am always getting a 400 bad request error. If I remove the authors field, I don't have that error. Here's how the Ajax request looks like: $.ajax({ type: 'POST', url: '/api/save-post/', data: { "csrfmiddlewaretoken": getCookie('csrftoken'), "title": "dasf", "desct": "dasf", "content": "fdasf", "authors": [1,2] }, success: function (msg) { console.log(msg); } }); I get a 400 bad request when I try this Ajax request. Why can't I submit my array successfully? I've tried "authors[]": [1,2] and "authors": "[1,2]" and a lot of other combinations, but it seems like nothing is working for some reason. What am I doing wrong? -
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')