Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use a variable in a Django template between {% %}
It's my first approach to matplotlib. I have been trying for a while to print my plots in a template. I know how if I do this for just one image, but now I'm trying to modify it and call different images. I got this and it works perfectly: <img src="{% static "/consulta/imagenes/rosavientos.png" %}"> But I'm trying to use this path: "/consulta/imagenes/rosavientos.png" like this: <img src="{% static {{ my_path }} %}"> But ID or literal expected after static. Is it possible to do this in any way? PS: I also tried this: In my view: ruta_estatica = "<img src = \"{% static '/consulta/imagenes/" + nombre_png + ".png' %}\">" In the template: {% autoescape off %}{{ respuesta3 }}{% endautoescape %} -
Django: How do I run database powered API tests during Continuous integration
I'm using CircleCI to deploy my application to Heroku. Running unit tests is trivial, but what happens if I want to run a battery of API tests that change a database and the success or failure of the API call depends also on what's in the database, not just what it returns? Is there a way to set up an interim database just for those tests that somehow would also exist, only temporarily while CircleCI runs the tests? I'd appreciate any pointers to the right direction on this. -
Django Unittesting: How to create temporary test only view?
I'm writing a django app which includes a utility to extract information from a html table on some url and downloads some files accordingly (assume the function is named extract_table_do_x). To test this utility I want to create a temporary page with a mock html table and run extract_table_do_x on it, but I don't want this page to be part of the main app. How to do so? -
Update data from html table Django/Python [duplicate]
This question is an exact duplicate of: Update all data from html table Django/python to database I created a system where the user has to search a folio number in the system, and based on this folio the system will bring data related to that folio as it showns below: My problem is that once the data is up, user has to fill all the input with data, and then uploaded into the system to be processed. The logic I did so far is updating but is saving the same data in every box, what am I doing wrong? I have asked this question before, but people says that I have to do it with ajax, any idea on how to do it with django? views.py def search_folio(request): if request.method == 'POST': form = FolioSearchForm(request.POST) if form.is_valid(): folio_number = request.POST.get('folio_number', '') folio = 'FOLIO' + str(folio_number) folio_query = InventoryTicketCollection.objects.filter(folio=folio) context = { 'lineas_de_reporte': folio_query, 'folio': ' | ' + folio } return render(request, 'inv-search-folio.html', context) else: form = FolioSearchForm() if request.GET.get('tan-id'): tan_id_list = request.GET.getlist('tan-id') tan = request.GET.getlist('tan') for item in tan_id_list: linea = InventoryTicketCollection.objects.get(id=item) # change its attribute to True linea.tan = tan # update db with the new value … -
Django Model Form No POST Data
I've seen other questions on Stack Overflow similar to this one yet very different so please don't be so quick to vote to close. Essentially, I've been trying to make a very simple login form following the techniques I've found on every tutorial online. For some reason, filling and submitting the form does not return any POST request data. Here is my code: View def signon(request): if request.method == 'POST': form = SignOnForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username = username, password = password) logger.info(user) return HttpResponse('Username: {} Password {}'.format(username, password)) return HttpResponse("Error {}".format(request.POST)) if request.method == 'GET': form = SignOnForm() return render(request, 'signon.html', {'form': form}) Template <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <title>Sign into Account</title> </head> <body> <form method = "POST"> {% csrf_token %} {{ form }} <input type = "submit" value = "Sign In"> </form> </body> </html> Form class SignOnForm(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput) class Meta: model = User fields = ['username', 'password'] I'm using the User class provided by Django, and for some reason upon submitting the completed form, no POST data is returned and hence why is_valid always fails. Any ideas? -
Django lambda function gives wrong results
I'm trying to get number of calculations per month in last 12 months in Django. I have function as follows: def calculations_per_month_last_12_months(member_number): items = list(Calculations.objects .filter(user__member__number=member_number) .filter(price_date__gte=datetime.datetime.now().today() - relativedelta(months=12)) .annotate(month=TruncMonth('price_date')) .values('month') .annotate(total=Count('id')) .values('month', 'total') .order_by('month')) result = [] for month in range(12): date = timezone.now() - relativedelta(months=month) month_results = list(filter(lambda i: date <= i['month'] < (date + relativedelta(months=1)), items)) month_result = 0 if month_results: month_result = month_results[0]['total'] result.append({ 'month': date.strftime('%B'), 'total_calculations': month_result }) return result In items I got what I want but the problem is in for loop. For example I get for may what needs to be for june. The result that I get for one user is: [{ 'month': 'June', 'total_calculations': 0 }, { 'month': 'May', 'total_calculations': 1 }, { 'month': 'April', 'total_calculations': 4 }, { 'month': 'March', 'total_calculations': 0 }, { 'month': 'February', 'total_calculations': 0 }, { 'month': 'January', 'total_calculations': 0 }, { 'month': 'December', 'total_calculations': 0 }, { 'month': 'November', 'total_calculations': 0 }, { 'month': 'October', 'total_calculations': 0 }, { 'month': 'September', 'total_calculations': 0 }, { 'month': 'August', 'total_calculations': 0 }, { 'month': 'July', 'total_calculations': 0 }] Thus, total_calculations for may should be total_calculations for june and so on.. The price_date in the database for … -
In Django1.8, coercing to Unicode: need string or buffer, NoneType found
This is model.py file. from django.db import models class SignUp(models.Model): email = models.EmailField() full_name = models.CharField(max_length = 120, blank = False, null = True) timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) updated = models.DateTimeField(auto_now_add = False, auto_now = True) def __unicode__(self): self.email This is admin.py file. from django.contrib import admin from .models import SignUp admin.site.register(SignUp) As you can see, there are only two fields to register name and email. When I fill the field on the admin page such as email->abc@abc.com, name->Hello and press save button, I get error like as follows. coercing to Unicode: need string or buffer, NoneType found Please help me. -
Django - bulk create in django rest framework
I was trying to do bulk create in Django Rest Framework, but it is throwing an error, stating that Invalid data. Expected a dictionary, but got list. The following is my serializer: serializer.py class DisplayCountsSerializer(serializers.ModelSerializer): class Meta: model = DisplayCounts fields = [f.name for f in model._meta.fields] views.py class UpdateDisplayCount(viewsets.ModelViewSet): queryset = DisplayCounts.objects.all() serializer_class = DisplayCountsSerializer def post(self, request, *args, **kwargs): print(request.data) serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) But this is giving an error saying: Invalid data. Expected a dictionary, but got list The following is my JSON data: [ { "ad_id": 2, "display_count": "76" },{ "ad_id": 3, "display_count": "86" } ] What might be the problem. Kindly help. -
Django 1.11 - how to print SQL statements with substituted variables
What I want to do, is to make Django (1.11.x) debug server log SQL queries in such a way, that I can redirect them to *.sql file and immediately execute. For this I need a SQL statements where all the variables are already substituted, so I DON'T want this: WHERE some_column in (:arg1, :arg2, ...) but I want this instead: WHERE some_column in ('actual_value_1', 'actual_value2', ...) Can you please help me figure out how to do this? Please note, that I don't want the SQL query to be printed in the browser (in some debug app like django_debug_toolbar) but printed to the console. Please note, that I don't want to type Django QuerySet queries in console - I want to type URL in browser, so make an actual HTTP request to Django debug server and see it printing a SQL query in such a way I can execute it later using SQL Plus or any other console tools. -
Django 1.11 adding an abstract base model to admin
I have a base model with abstract=True. # models.py class Media(models.Model): title = models.CharField(unique = True, max_length=200) excerpt = RichTextField(config_name = 'extralight', blank=True, null=True) class Meta: abstract = True Model image, sound and document are subclasses of media model. I want to get all the list of media models. What is the best way of adding abstract media model to django admin? -
Extending the user model: SimpleLazyObject error when using user.is_authenticated()
So, to begin, I have extended the default Django user to include a user avatar. I'm now beginning to think if I have done this as good as I could have done, as although the user_avatar field is now referencable - I'm receiving some issues at various points. models.py: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile') user_avatar = models.ImageField(storage=site_media_upload_location, null=True, blank=True) views.py: class PostLikeAPIToggle(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, post=None, year=None, month=None, day=None, format=None): post = self.kwargs.get("post") obj = get_object_or_404(Post, slug=post) url_ = obj.get_absolute_url() user = self.request.user updated = False liked = False if request.user.is_authenticated(): if user in obj.likes.all(): liked = False obj.likes.remove(user) else: liked = True obj.likes.add(user) updated = True data = { 'updated': updated, 'liked': liked } return Response(data) When checking that this user is authenticated (the request.user.is_authenticated()) I receive the following error: 'UserProfile' instance expected, got <SimpleLazyObject: <User: default_user>> I've tried a number of things, such as: user = self.request.userprofile.user user = self.request.user.userprofile and also: if user.userprofile.is_authenticated(): but to no avail. I'm wondering if anyone can quickly provide some pro-tips on how to navigate around this issue... -
Extending django's `runserver` command adding arguments
In an attempt to try to generalize a django app, so it can be run with different configurations defined in yaml files, I wanted to extend the runserver command to take the locations of these configuration files as arguments. I followed a guide by Chase Seibert, but when I try to run the command with my "added" arguments, it doesn't seem to work. I have a feeling it is because of the location of the management/commands directory, but moving that around (with the __init__.py isn't helping). Any suggestions? Thanks! My app structure my_app/ __init__.py static/ templates/ manage.py app1/ app2/ my_app/ management/ __init__.py commands/ __init__.py runserver.py models.py views.py settings.py urls.py My extension of runserver from django.core.management import call_command from django.core.management.base import BaseCommand from django.core.management.commands.runserver import BaseRunserverCommand from .env import PATH_CFG_SIM, PATH_CFG_PARAM class Command(BaseCommand): ''' Runs the built-in Django runserver with initial schema and fixtures Note: cannot use auto-reloading because that casues resetdb to be called twice. ''' # remove this option from the --help for this command option_list = (o for o in BaseRunserverCommand.option_list if o.dest != 'use_reloader') help = 'Starts a lightweight web server testing.' args = '[optional port number, or ipaddr:port] appname appname' def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument('--cfg-sim', … -
Django models, deserialize PrimaryKeyRelatedField
I have a microservice application, which needs to pass an object from service to service, and the receiver needs to save that object to the db. The object I am trying to pass has a field which is a foreign key to another table. That is: class RelatedModel(models.Model): id=models.CharField(max_length=3, primary_key=True) name=models.CharField(max_length=30) class PrimaryModel(models.Model): id=models.IntegerField(primary_key=True) rel_model=models.ForeignKey(RelatedModel) class RelatedSerializer(serializers.ModelSerializer): class Meta: fields = 'all' model = RelatedModel class PrimarySerializer(serializers.ModelSerializer): rel_model = RelatedSerializer() class Meta: fields = '__all__' model = PrimaryModel However, in this case, the serializer on the receiving end was invalid, saying that the related model already existed in the db. I tried using PrimaryKeyRelatedField, but then the receiving serializer does not contain the rel_model at all. How can I deserialize the related field in the receiving serializer? -
Getting result grouped by month in Django
I want to get all members from a Member model and get total calculations that they have done per month. My query is as follows: members_list = Member.objects\ .exclude(deleted=True) \ .annotate(num_calculations=Count('user__calculations'))\ .order_by("-user__date_joined") With this query I get all members and total calculations that they have done. How can I get total calculations per month(last 12 months)? Calculation model is as follows: class Calculations(models.Model): user = models.ForeignKey(to=User) make = models.CharField(max_length=127) model = models.CharField(max_length=127) mileage = models.IntegerField() price_date = models.DateTimeField(auto_now_add=True) sales_price_currency = models.CharField(max_length=10, null=True) And member model is as follows: class Member(models.Model): user = models.ForeignKey(to=User) number = models.CharField(max_length=10) company_name = models.CharField(max_length=100) address = models.CharField(max_length=255) mobile = models.CharField(max_length=50) active = models.BooleanField() deleted = models.NullBooleanField(null=True) -
Wagtail 1.8 Customizing Elasticsearch settings
currently I have some issues with the Elasticsearch config. I am aware of the preconfigured settings from Wagtail in the elasticsearch#.py, but I wanted to use my own settings. For example: Wagtail's Elasticsearch default setting is using the edgengram_analyzer as the index_analyzer and standard for search_analyzer Like it's seen here: elasticsearch2.py Is it possible to change that settings for my own configuration? I tried it, by writing my own analyzers and mappings, but unfortunately Elasticsearch is always using the default configuration after updating the index. I'm also aware of the open issue on github, but I thought I could speed up some things on the official helper channel in stackoverflow :) Thanks! -
Django: how to join and annotate multiple sql tables?
I'm building a sample django app and I can't aggregate properly some sql results. Consider these 3 models: Movie model class Movie(models.Model): source_id = models.CharField(max_length=100, primary_key=True) title = models.CharField(max_length=200, validators=[MinLengthValidator(1)]) Rating model class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.PositiveIntegerField() username = models.CharField(max_length=100, validators=[MinLengthValidator(1)]) Comment model class Comment(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) username = models.CharField(max_length=100, validators=[MinLengthValidator(1)]) body = models.TextField() Then consider the following mysql tables: movie +-----------+-----------+ | source_id | title | +-----------+-----------+ | 15sdfsd4 | Spiderman | +-----------+-----------+ rating +----+--------+----------+----------+ | id | rating | username | movie_id | +----+--------+----------+----------+ | 1 | 4 | jack | 15sdfsd4 | | 2 | 3 | mick | 15sdfsd4 | +----+--------+----------+----------+ comment +----+----------+--------------------+----------+ | id | username | body | movie_id | +----+----------+--------------------+----------+ | 1 | charles | I loved this movie | 15sdfsd4 | | 2 | mick | Nice sound fx | 15sdfsd4 | +----+----------+--------------------+----------+ I would like to query for a list of movie ids and get a summary of the avg rating and the nr of comments. I tried something like ids = ['15sdfsd4','54fdf5d'] m = Movie.objects.filter(source_id__in=ids).annotate(Avg('rating'), Count('comment')) but it give me a comment count of 4 and an avg rating of 1.5 which I can't … -
Python Django Syntax error
I am New to python and I am learning Django right now by following online tutorials I installed python and check by getversion command in python shell so, I started to work on the First project, The problem in this project I am facing is when I run the command in command prompt it gives the output but in python shell it's not working it's giving syntax error, Here below I mentioned the command and error I am facing in my first app, Please review it and guide me I typed the following command in Shell and Prompt of Python django admin startproject mysite It gives the following Error Invalid Syntax Before executing this I run this in command prompt, by cd: comment I changed my directory, for example, i changed my directory to desktop and give the command " django admin startproject mysite" and execute the command and view the result in localhost My issue is why it's not getting in python shell -
How should I do this in django
I was thinking about making a Hostel Allocation Web application. It has models, Student, Room, Hostel. What I want is to create a function that allocates students after each year. For that, I thought in the student view each student after completing his four years of stay can click on vacate hostel after completing his degree, and for others, I want to create something that allocates them, Now there are certain constraints, there are Undergraduate students with degree period 4 years and each year has access to different types of rooms, First-year triple sharing, second and third-year double sharing and fourth-year single rooms. Also, a Hostel has Ph.D. students as well but their stay period is not defined. So, what I was thinking is that First years should be allotted by uploading a CSV file and I have made that part, So the next part is to allot subsequent years based on their preferences, So how could I make something like this in Django that allows them to make it based on their preference, I was thinking each student would be given a unique token, and while filling for rooms one student can do for a room, and that token … -
No module name django.core.wsgi apache2+ubuntu+mod_wsgi
I have set up my wsgipythonpath and daemonprocess but the error log shows the above error no module named django.core.wsgi, i am sharing my conf, what could be the error, and how can i check if apache can acess my django installation or not. I am able to host with same config on my local system but not on a remote server WSGIPythonPath /home/env_mysite/lib/python2.7/site-packages <VirtualHost *:80> ServerName localhost DocumentRoot /home/unixadmin/PBpy WSGIScriptAlias / /home/unixadmin/PBpy/PBpy/wsgi.py WSGIDaemonProcess PBpy python-path=/home/env_mysite/lib/python2.7/site-packages ErrorLog /home/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory "/home/unixadmin/PBpy"> Require all granted </Directory> -
dump javascript variables into a file using Javascript function
I am trying to pass some javascript variable from a javascript function to the python code. ` function submit_this(url) { var i,j;var arr = []; for(i=0; i<Hello.length; i++) { arr[i]=[]; for(j=0;j<Hello[i].length; j++) { arr[i].push(document.getElementById(Hello[i][j]).value); } } } ` Hello is a 2d array which is a json object and is passed to javascript by using python (json.dumps()) This javascript function is embedded inside the script tag of html. I am trying to put this varible (arr) into some file so that it could be used by the python code. This is implemented inside a view function of Django file view.py Kindly suggest me how can I pass this variable or how to pass it to the python code. Thanks in advance. -
Ordered Dictionary is not updating in python
views.py from collections import OrderedDict request_dict = OrderedDict() def payment(): request_dict[0] = 1 request_dict[1] = 2 tasks.py from Payment.celery import app from celery.task.schedules import crontab from celery.decorators import periodic_task from datetime import datetime, timedelta from . import views @periodic_task(run_every=timedelta(seconds=2)) def addQueueTask(): print('queue_task: ', views.request_dict) My problem is that variable OrderedDict is not updating their value in tasks.py and it keeps empty. What missing is from my side in this code. Output is given below: [2017-06-09 10:57:54,046: WARNING/Worker-2] queue_task: [2017-06-09 10:57:54,046: WARNING/Worker-2] OrderedDict() -
Issues overriding the get_redirect_url function for the RedirectView generic view
So I'm trying to implement a post like Toggle for my Django blog - and I'm looking to override the get_redirect_url such that a user can like posts on my blog. I've outlined the class as follows: class PostLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): slug = self.kwargs.get("slug") obj = get_object_or_404(Post, slug=slug) url_ = obj.get_absolute_url() self.request.user if user.is_authenticated(): obj.likes.add(user) return url_ However, the issue I think is in how I'm getting my post object - I'm currently doing this on the post slug. I have wanted to define SEO friendly post listings, I've therefore defined the url patterns as follows: url_patterns = [ url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.post_detail, name = 'post_detail'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/like/$', views.PostLikeToggle.as_view(), name = 'post_like'), ] I've tried amending the above to reference the "slug" by replacing <post> with <slug> in the url. Didn't work. I then tried to define post in the get_redirect_url function: post = self.kwargs.get("post") obj = get_object_or_404(Post, post=post) Again, didn't work. I'm just trying various things to try and get this to work - but sadly, no luck yet - so I though I would throw it out to the more experienced of you in the Django wrangling community. Thank you. -
Django serve index.html from dist folder generated by webpack and vue
I'm using Vue + webpack with a Django backend for my webapp and I need to be able to serve files from the dist folder from Django when the user hits the root url '/'. The dist folder containing the static files from Vue + webpack has already been created, and I just need to know how to serve those files from Django. I disabled collectstatic on Heroku because all my files will be served from dist folder that was not generated by django. How can I get Django to serve the index.html? Here's what I have so far, but none of my attempts are working. I need some way to configure Django urlpatterns to serve that index.html file settings.py STATIC_ROOT = os.path.join(BASE_DIR, '../dist') STATIC_URL = '/dist/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../dist'), ] urls.py if settings.DEBUG is False: urlpatterns += url( r'^$', 'index.html', 'document_root': settings.STATIC_ROOT) -
Connect Django to redshift database and retrieve data
I have connected django to redshift database with correct credentials as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'redshift_db': { 'NAME': 'test', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'test', 'PASSWORD': 'xxxx', 'HOST': 'xxxxxxxx.redshift.amazonaws.com', 'PORT': 5439 }} I want to know what i should include in my models.py and how I should execute queries from my view -
How can I schedule a task at time from django frontend?
I'm programming an irrigation system with Django and I use Celery to handle asynchronous tasks. In my application the user selects the days and hours that he wants to activate the irrigation, this is stored in the database and he can update them at any time. I know I can schedule tasks like this, but I want to update the time. from celery.task.schedules import crontab from celery.decorators import periodic_task @periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon")) def every_monday_morning(): print("This runs every Monday morning at 7:30a.m.") Another way is to use python-crontab