Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
List not showing in html
Im trying to create a table in html but the list is not even working This is my site.html {% extends "blog/base.html" %} {% block content %} <h1>tab in my website</h1> <p>site info</p> {% if result_dict %} <ul> {% for i in result_dict %} <li> {{ forloop.counter }} - {{ i }}</li> {% endfor %} </ul> {% else %} <p>This is not working</p> {% endif %} {% endblock content %} This what what i have in my views.py def prtg(request, *args, **kwargs): response = requests.get("https://prtg.c3ntro.com/api/table.json?content=status=down&username=someuser&passhash=somehash&count=200000000") data = response.json() d = data result_list = [d for d in data['status%3Ddown'] if d['status'] == 'Down'] return render(request, 'blog/prtg.html', {'title':'PRTG'}, {'result_list': result_list}) When I open the page is not loading any information and well it's supposed to show at least the sensors that I'm filtering but nothing shows us, instead I get the message of the else statement "This is not working" What am I doing wrong? -
Django - Register custom values for sharing url
I want to add a share function. I want to register in a model what suffix it should have and later the builder should build a url from this (and of course redirect the user). Example: example.com/article/the-best-article should be converted into this: example.com/sU74?a (That's just an random id) Another example: example.com/poll/what-is-your-thought should be converted into this: example.com/sU74?p (The ids are the same but they are different models!) I want to register the suffix this way: class Poll(Model): # some fields @share.register def suffix(self): return "p" def share_builder(self): # return shared builder # this should return the short url I don't know if this is possible or not. Thanks for your help -
django-hijack fails with UserPassesTestMixin starting in Django 2.1.0
Apparently, starting with Django 2.1.0, django-hijack (version 2.1.10) seems to bug out when used with UserPassesTestMixin. It works fine when the test passes; when the test fails, I get a 403 Forbidden error rather than a redirect to login_url. Is this a bug? If so, how can I monkey patch the package to work with Django 2.1.0+? class MyView(UserPassesTestMixin, View): test_func = lambda self: False login_url = '/myurl/' def get(self, request): return HttpResponse('Hello world') [25/Jun/2019 13:03:29] "GET /hijack/username/someuser/ HTTP/1.1" 302 0 Forbidden (Permission denied): /myview/ Traceback (most recent call last): File "C:\Envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Envs\myenv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Envs\myenv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\program files\python36\Lib\contextlib.py", line 52, in inner return func(*args, **kwds) File "C:\Envs\myenv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Envs\myenv\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Envs\myenv\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Envs\myenv\lib\site-packages\django\contrib\auth\mixins.py", line 108, in dispatch return self.handle_no_permission() File "C:\Envs\myenv\lib\site-packages\django\contrib\auth\mixins.py", line 43, in handle_no_permission raise PermissionDenied(self.get_permission_denied_message()) django.core.exceptions.PermissionDenied [25/Jun/2019 13:03:29] "GET /buy/ HTTP/1.1" 403 22 -
multiple objects to templates with render doesn't work
I have a problem I want to send more than one object to the same page on tamplate but happens with me Problem NoReverseMatch at / and Try reversing the order of the last 2 urls and stay problem path('', views.index, name='home'), path('', views.category_view, name='home'), boards=Board.objects.all() categorys=Category.objects.all() context = { 'boards':boards , 'categorys':categorys, } return render(request,'home.html',context=context) urlpatterns = [ path('', views.index, name='home'), path('track/<int:track_id>', views.record_view, name='track1'), path('boards/<int:id>', views.boards_topic, name='boards_topic'), ] -
How to add a serializer field in DRF for GET only not POST?
I am working on an existing DRF codebase and want to add a last_build field to return on a GET request only. I do NOT want this to affect anything to do with POST requests. I have created a method that returns the field I am looking for and have successfully tested that it returns the data I want, however I have not yet tested if this will affect existing POST requests. class JobSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True, max_length=150) product = ProductSerializer(many=False, required=True) platform = PlatformSerializer(many=False, required=True) stages = StageSerializer(many=True, required=False) last_build = serializers.SerializerMethodField() def get_last_build(self, name): latest_build = JobExecution.manager.filter(job__name=name.name) return latest_build.last().build_id class Meta: model = Job fields = ("name", "product", "platform", "stages", "last_build") validators = [ UniqueTogetherValidator( queryset=Job.manager.all(), fields=("name", "platform", "product") ) ] def create(self, validated_data): # Create objects from data try: product_data = validated_data.pop("product", None) if product_data: ps = ProductSerializer() validated_data["product"] = ps.create(product_data) else: logger.exception("product is not valid") platform_data = validated_data.pop("platform", None) if platform_data: ps = PlatformSerializer() validated_data["platform"] = ps.create(platform_data) else: logger.exception("platform is not valid") stage_data = validated_data.pop("stages", []) stages = [] the_job = Job.manager.get_or_create(**validated_data)[0] if stage_data: for stage_data in stage_data: ss = StageSerializer() stage_data["job"] = the_job the_stage = ss.create(stage_data) return the_job except Exception as e: logger.exception(e) raise e … -
How to update the page in Django by pressing a pushbutton
I made an application using django and raspberry, and I wanted it when I push the pushbutton, django requests the page through the url. Can someone help me ? -
Using a dropdown box to display a picture in Django
I am building a Django website and I want to have a page where there is a dropdown box (which is made from a variable in one of my models) and the selection from that dropdown box alters the display down below. For example: I have a model that contains the variables Name & Value I want to have in a dropdown box all the values for Name, and for the corresponding Value to be displayed when a Name is selected. Using views.py I can send the values of Name to create the dropdown box. But I don't know how to display the corresponding value when the user selects a Name. This seems like it probably has a very simple answer, but I am struggling to find an example for this on SO or Django tutorials. (Likely because I don't know the correct terminology to use). Could someone offer some direction please? -
my main.css is not rendering,I am using multiple entry points webpack.config
my main.css is not rendering,I am using multiple entry point webpack.config.js file % load render_bundle from webpack_loader %} <!DOCTYPE html> <html> <head> <meta name='apple-mobile-web-app-capable' content='yes' /> <meta itemprop='name' content='TableGrabber Dashboard'> {% render_bundle "main" "css" %} {% render_bundle "vendors~main" "css" %} <title> {{ title }} </title> I expect my both app.js file will render and the routes written in them can be run by putting the URL in the browser -
Pviz Html file shows correct graphic when locally opened but on server no graphic appears
I am creating a website and want to show a image based on the protein sequence that a user inputs. I am using the genentech Pviz GitHub to help me create the graphic and have copied an example from their website. It work completely fine and shows the correct image and graphic when I open it within PyCharm but when I open it as a template in views.py it does not. <html> <head> <title>pViz.js different track heights</title> <link rel="stylesheet" type="text/css" href="deps/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="deps/pviz-core.css"> <script src="deps/pviz-bundle.min.js"></script> <!-- just a few lines of javscript to decorate the page --> <script src="examples-utils.js"></script> <style type="text/css" media="screen" class='example'> g.feature rect.coverage_bar.psm_coverage { fill: blue; fill-opacity: 0.4; } g.feature rect.coverage_bar.psm_no_coverage { fill: red; fill-opacity: 0.4; } </style> </head> <body class="container"> <div class="row"> <h2>pViz with different track heights example</h2> </div> <div id="main" class="row"></div> <div class="row"> <h3>Comments</h3> </div> <script class="example"> var pviz = this.pviz; var seq = 'MELAALCRWGLLLALLPPGAASTQVCTGTDMKLRLPASPETHLDMLRHLYQGCQVVQGNLELTYLPTNAS'; var seqEntry = new pviz.SeqEntry({ sequence : seq }); /** * attach a track height ratio to the category (1 is the default) */ pviz.FeatureDisplayer.trackHeightPerCategoryType.psms = 0.2; pviz.FeatureDisplayer.trackHeightPerCategoryType.psms_coverage = 3; pviz.FeatureDisplayer.setStrikeoutCategory('oups'); new pviz.SeqEntryAnnotInteractiveView({ model : seqEntry, el : '#main' }).render(); pviz.FeatureDisplayer.setCustomHandler(['psm_coverage', 'psm_no_coverage'], { appender : function(viewport, svgGroup, features, type) … -
Create multiple shipments and packages in FedEx using a single API call
I have a requirement to create multiple shipments in FedEx with multiple packages. Here is my scenario In a single button click, I want create 10 shipments and each shipment have 5 packages each. As per the example I found, I have to call a FedEx API each time for each shipment and package. That means, In my case, I have to make 50(5 * 10) API calls one by one and this makes the system really slow. Do we have any alternate method to make a single API call to create multiple shipments and create shipments with multiple packages? Thanks in advance -
Select link menu with go button
This is a dropdown selection box where user can choose page and then click the submit button to go to that page Im using Django 2.2, don't know how to make the button go to the selected link gradovi.html {% block content %} <div class="row"> <form> <div class="input-field"> <select> <option value="" disabled selected>Izaberite grad</option> {% for grad in gradovi %} <option value="{{grad.grad_slug}}">{{grad.grad_ime}}</option> {% endfor %} </select> <label>Materialize Select</label> </div> <button class="btn waves-effect waves-light" type="submit" name="select"> <i class="material-icons right">send</i> </button> </form> </div> {% endblock %} -
Library that can track API usage for Django Rest Framework
So I created a basic api for a basic website, and now I want to be able to track which people are using it and what are they using it for. Any recommendations? (I've tried DRF-Tracking, but it's not logging anything. Help with that would also solve my problem) -
Django translations - underscore as alias of gettext for list items - UnboundLocalError
I'm struggling trying to understand why the _ used as an alias for gettext is not working for translating items of a list. I am using Python 3 and importing gettext this way: from django.utils.translation import gettext as _ The snippet of code failing is this: def register(request): request_data = {k: v for k, v in request.data.items()} if "username" not in request_data: raise ValidationError({"username": [_("The username field must be included and cannot be empty.")]}) When sending a request to this view I get the following error: UnboundLocalError at /v1/register/ local variable '_' referenced before assignment On the other hand, a snippet of code in the same file that is not failing is the following: def collaborator_workspace_list_email_recovery(request): username = request.data.get("username") if not username: raise ValidationError(_("Username must be provided in the request body!")) How can I use _ for translating items of a list (as for the example above)? -
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")