Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count occurrences of values on a single column grouped by week
I'm trying to accomplish this using Django 2.0 ORM, but if you can solve this with a raw SQL query that would be very helpful too. Say for example I have a table with the column "destination", which will always be the name of a city, such as "Los Angeles", "New York", "San Francisco", or "Seattle" (but we don't know in advance how many different cities there could be). I need a SQL query (or Django ORM code) that will get me a count of all the cities for a specified date range, grouped by the record's week (based on created_at timestamp, with weeks starting on Mondays). Here is an example of the output, structured as JSON: { "2017-06-05-2017-06-11": { "Los Angeles": 100, "New York": 50, "Copenhagen": 20 }, "2017-06-12-2017-06-18": { "Los Angeles": 10, "Toronto": 23, "Las Vegas": 21, "Carson City": 8, "Raleigh": 1 }, "2017-06-19-2017-06-25": { "Toronto": 24, "Tokyo": 75, "Kansas City": 123, "Salem": 84, "Bismarck": 22, "Boise": 77, "Las Vegas": 123 } } Note that the results can vary in size, the date ranges all start on a Monday and end on a Sunday (both inclusive), and the city names are variable and unknown. I know there are … -
Django: How to test view with two forms in it
I want to write tests to make sure that if: If product does not exist, if save a new product as well as the item If product does exist, it was just feed in the existing product into the item If there is a problem force the user to fix it. Please note that item has as product foreign key. My addItem function might be incorrect to do meet the above 'targets'. view def addItem(request, **kwargs): template_name = 'app/add.html' product_form = ProductForm(request.POST or None) item_form = ItemForm(request.POST or None) forms = [product_form, item_form] if all([form.is_valid() for form in forms]): instance_product = product_form.save() instance_item = item_form.save(commit=False) instance_item.product = instance_product instance_item.save() return #redirect else: #return blank forms return render(request, template_name, {'forms':forms} html <form method="POST"> {% csrf_token %} {% for form in forms %} {{form.as_p}} {% endform %} <input type='submit'/> </form> Thank you for your time. -
cx_oracle 6 for Oracle 12C version error
I am trying to use oracle 12c as database for my application using Django framework. But I am struck in version related issue Following are the version of library used: Python 3.6 cx_Oracle 6 Oracle instant client 12.2 Oracle 12 C database on server Oracle 10 g on local machine where the cx_oracle is installed OS is windows 7 Following are the steps which I did to install cx_oracle 1. pip install cx_Oracle 2. Download Oracle instant client 12.2 zip file for windows 3. Extracted the zip file 3. Added the above unzipped folder to user PATH variable From CMD I try to execute python import cx_Oracle con = cx_Oracle.connect(uname, pwd, server_ip:port/name) I am getting the error: cx_oracle.databaseerror: dpi-1050: oracle client library must be at version 11.2 or higher Is cx_Oracle having any conflict with oracle 10 g installed at local machine I cannot upgrade the local oracle 10g db because(no rights given) How do I resolved the above issue. How can I make sure cx_Oracle uses the correct Oracle instant client( i.e, 12.2) to connect to server db. -
Django: Use text box data and write that text a file
I am super new to Django and web development. Right now my objective is to create a google like interface and take the text from search box and write it to a file (in other words just want to access text data in the search box). I have created a search page like below search.html {% extends "header.html" %} {% block content %} <div style="display: flex; justify-content: center;"> <img src="/static/images/logo.jpg" class="responsive-img" style='max-height:300px;' alt="face" > </div> <form method="get" action=""> {% csrf_token %} <div style="display: flex; justify-content: center;"> <input type="text" name="query" placeholder="Search here..." required size="70" > <button type="submit">Go!</button> </div> <button type="submit">Search</button> </form> {% endblock %} views.py from django.shortcuts import render def index(request): return render(request, 'search.html') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index') ] Please give me a hint/example of how to go forward from here ? Thanks. -
Why when I add @api_view to my view that I get a 403
I was following along with the Django REST Framework tutorial, http://www.django-rest-framework.org/tutorial/2-requests-and-responses/. However when I add the @api_view decorator I get a 403 when I do a GET on the view. GET /attendance/api/youths/ HTTP 403 Forbidden Allow: OPTIONS, GET Content-Type: application/json Vary: Accept { "detail": "Invalid username/password." } This is my code. @api_view(['GET']) def youths_json(request, format=None): youths = Youth.objects.filter(attending=True) serializer = YouthSerializer(youths, many=True) return Response(serializer.data) When I add the AllowAny permission it still doesn't work. @permission_classes((AllowAny, )) Any ideas? I would like to get this to work and I would really like to use the ListAPIView. -
AuthFailed at /oauth/complete/github/ login social django
Please help me for this problem. AuthFailed at /oauth/complete/github/ Authentication failed: The redirect_uri MUST match the registered callback URL for this application. Request Method: GET Request URL: http://localhost:8000/oauth/complete/github/?error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fv3%2Foauth%2F%23redirect-uri-mismatch&state=WoKzByClduyC14Q1sjY0PeB8ZFIdf2I9 Django Version: 1.11 Exception Type: AuthFailed Exception Value: -
django redirect after form submission not working
new to django so this one probably has a very simple answer but i cannot for the life of me find the specific solution to this. I am simply trying to redirect to a new URL after a form submission with a FileField. I can navigate to the URL separately and it works fine. The file uploads correctly so I know it is validated correctly. But the redirect returns the following error: Reverse for 'success' not found. 'success' is not a valid view function or pattern name. I have tried a bunch of different naming conventions, but none has worked. It looks to me like I have setup the URL and passed it correctly. Would really appreciate some help with this. The simplest problems are the most frustrating! Here are the views. from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from .forms import InvestmentReportForm def upload(request): if request.method == 'POST': form = InvestmentReportForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('success') else: form = InvestmentReportForm() return render(request, 'app/upload.html', {'form': form}) def success(request): return HttpResponse("File successfully uploaded") And my urls.py: urlpatterns = [ path('', views.index, name='index'), path('upload/', views.upload, name='upload'), path('success/', views.success, name='success'), path('performance/', views.performance, name='performance'), ] -
django error "The value of 'fieldsets[0][1]' must contain the key 'fields'." when trying link model to admin panel
i am trying to hook up django admin panel to a model using following code in admin.py under my django app after which i got error admin.E011, appreciate your help please to clear this error "SystemCheckError: System check identified some issues: ERRORS: : (admin.E011) The value of 'fieldsets[0][1]' must contain the key 'fields'. : (admin.E011) The value of 'fieldsets[1][1]' must contain the key 'fields'." my code: from django.contrib import admin from .models import Entry Register your models here. @admin.register(Entry) class EntryAdmin(admin.ModelAdmin): fieldsets = [ ('Regular Expressions', {'feilds' : ['pattern', 'test_string', 'user']}), ('Other Information', {'feilds' : ['user', 'date_added']}), ] list_display = ['pattern', 'test_string', 'user'] list_filter = ['user'] search_fields = ['test_string'] -
How to find ids that requires action based on 3 tables?
I'm working on my first django project which is a sport betting app. My models are: class Game(models.Model): home_team = models.CharField(max_length=100) away_team = models.CharField(max_length=100) class GameResult(models.Model): gameid = models.ForeignKey(Game) result = models.IntegerField(default=None) class GameBet(models.Model): gameid = models.ForeignKey(Game) bet = models.IntegerField(default=None) userid = models.ForeignKey(User) I'm trying to create a view that shows only pending games, which means they have no result (easy part) and no bet placed yet. Here the problem is - in my database I have only bets that was made, like: gameid| userid | userbet 23 | 10 | 2 23 | 11 | 1 23 | 12 | 0 and I'm looking for somethig like this: gameid| userid | userbet 24 | 10 | 1 24 | 11 | 0 When userid #12 hasn't made his bet yet - so it is missing in the database and game should be in his pending games list. My current logic is that I know ids of all games, I know ids of games with result and I know ids of games that I placed my bet. How do I connect these dots and find out games that I still have to bet? all_games = Game.objects.get() games_with_result = GameResult.objects.filter(result__isnull=False) games_with_players_bet … -
How to pass a value from model to view in django?
How to pass codeval variable from models.py to views.py: in models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save import random from django.core.mail import send_mail class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') mobile = models.IntegerField(default=0) code = models.IntegerField(default=0) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) codeval = random.randint(111111,999999) user_profile.code = codeval user_profile.save() receiver = User.objects.get(id=user_profile.user_id).email send_mail(' Confirm your account on Abolombon', 'Thanks for signing up with Abolombon! Your Abolombon verification code is:\n %s\n\n Thank you\nAbolombon.com'%(codeval), 'testpurpose2040@gmail.com', [receiver]) post_save.connect(create_profile, sender=User) in views.py def verification(request, args=codeval): return render(request,'website/verification.html',{'args':args}) I am making an e-commerce site in django where I need user registration option. For this purpose I am using django's build in user registration form. But I need to store some additional info about user like contact number, city etc. I also want to verify user sending a 6 digit code to their corresponding email address. But in django's build in form their is no field to store verification code. So I have created UserProfile model to serve this purpose. And have created code field to store 6 digit random number. I want to store this random number into … -
Django rest custom model creation fails
I have a custom user model as following: class Librarian(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=30, blank=True) # A library has many librarians which_library = models.ForeignKey('Library', related_name='librarians', on_delete=models.CASCADE) I have written serializer as following: class LibrarianSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') email = serializers.CharField(source='user.email') password = serializers.CharField(source='user.password') class Meta: model = Librarian #fields = '__all__' fields = ('id', 'username', 'email', 'password', 'phone', 'which_library') def update(self, instance, validated_data): instance.user.email = validated_data.get('user.email', instance.user.email) instance.user.password = validated_data.get('user.password', instance.user.password) instance.phone = validated_data.get('phone', instance.phone) instance.which_library = validated_data.get('which_library', instance.which_library) instance.save() return instance def create(self, validated_data): print('ok') return Librarian.objects.create(**validated_data) It's view: @api_view(['POST']) def librarian(request, library_id): """ Create a new librarian for a specific library """ if request.method == 'POST': print('View') serializer = LibrarianSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) And I am making a POST request to the corresponding URL with following JSON data: { "username": "sample", "email": "sample@gmail.com", "password": "12345678", "phone": "12345", "which_library": "1" } It throws me Cannot assign "{u'username': u'sample', u'password': u'12345678', u'email': u'sample@gmail.com'}": "Librarian.user" must be a "User" instance error. My goal is to create a Librarian (a user must be automatically created), that's why I am sending username, password, email fields as well. What am I doing wrong? -
Django - call def on button click?
SO I have this simple button in my template: <form method="get"> <input type="text" value="8" name="mytextbox" size="1" /> <input type="submit" class="btn" value="Click" name="print_btn"> </form> In my views.py i have this function: def print_from_button(request): if(request.GET.get('print_btn')): print( int(request.GET.get('mytextbox')) ) print('Button clicked') this prints to console: "GET /myview/mytextbox=8&print_btn=Click HTTP 1.1" 200 I also want 'Button clicked' to be printed, i.e. I want the function executed, not just one statement in the function. -
NoReverseMatch for url in Django template
I'm getting this error: NoReverseMatch at /workoutcal/add/2017/11/1/ Reverse for 'add_workout' not found. 'add_workout' is not a valid view function or pattern name. Because of this template code: <form action="{% url 'add_workout' date.year date.month date.day %}" method="post"> From the urls.py: url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/$', views.AddWorkoutView.as_view(), name = 'add_workout'), I've followed the docs. Don't know why my URL name isn't found. Any ideas? -
Query related to mastodon oauth service
I have one website. I used mastodon oauth service for login to my website and it works fine. Now I want to migrate users of my website to mastodon server, can anybody tell me how to do it? -
TypeError at /app/^detail/(?P1[0-9]+)/$ detail() got an unexpected keyword argument 'pk'
I got an error, TypeError at /app/^detail/(?P1[0-9]+)/$ detail() got an unexpected keyword argument 'pk' . I wrote urls.py urlpatterns = [ path('top/', views.top, name='top'), path(r'^detail/(?P<pk>[0-9]+)/$',views.detail , name='detail'), ] in views.py def top(request): content = POST.objects.order_by('-created_at') page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,"page":page}) def detail(request): content = POST.objects.order_by('-created_at') return render(request, 'detail.html',{'content':content}) in top.html <div> {% for content in page %} <div> <h2>{{ content.title }}</h2> </div> {% endfor %} </div> <div> {% for content in page %} <h2>{{ content.title }}</h2> <p><a href="{% url 'detail' content.pk %}">SHOW DETAIL</a></p> {% endfor %} </div> When I put "SHOW DETAIL" button, this error happens.I really cannot understand why I can't access pk. pk is default value, so I think I can access it from everywhere.I wanna make a system when I put "SHOW DETAIL button",content's detail is shown.What is wrong in my code?How should I fix this?Am I wrong to write url?Or is this error's meaning I should write pk in detail method? -
Unable to use '#' as broker url in celery django
app = Celery('myapp', broker='amqp://user:pass#1@localhost:5672//', backend='rpc://', include=['myapp.tasks']) I get this error ValueError: invalid literal for int() with base 10: 'pass' This code doesn't work, I'm new to python and Django is there an escape sequence for it? Iv tried u"", r"" ,'#' , '##' and '#' , hoping it will escape it but it doesnt. -
How to prefill admin form items (from many-to-many relationship) in Django
I'm looking for a way to prefill items in an admin form (or form view). I took a look on get_changeform_initial_data but if I can prefill simple values, I didn't find any way to send multiple items correctly (I mean with many-to-many relationship). I know that you cannot link object if you don't already have primary key of the parent one but I want to have partial data and send them (like Django admin form does). The aim is to prefill usual sold items in an invoice (but still allow to check and update them before creation). I'm open if you have any idea. I will perhaps try to achieve this in Javascript but want to know there is a correct way in Django. -
module 'txaio' has no attribute 'make_batched_timer'
I am folowing this tutorial enter link description here But I am getting "C:\Program Files\JetBrains\PyCharm 2017.3.1\bin\runnerw.exe" C:\Users\srawa\AppData\Local\Programs\Python\Python36\python.exe C:/Users/srawa/OneDrive/django-practice/example_channel/manage.py runserver 8000 Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. January 01, 2018 - 20:07:53 Django version 1.9.3, using settings 'example_channel.settings' Starting Channels development server at http://127.0.0.1:8000/ Channel layer default (asgi_redis.RedisChannelLayer) Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000221817F76A8> Traceback (most recent call last): File "C:\Users\srawa\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\srawa\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\management\commands\runserver.py", line 81, in inner_run action_logger=self.log_action, File "C:\Users\srawa\AppData\Local\Programs\Python\Python36\lib\site-packages\daphne\server.py", line 19, in run self.factory = HTTPFactory(self.channel_layer, self.action_logger) File "C:\Users\srawa\AppData\Local\Programs\Python\Python36\lib\site-packages\daphne\http_protocol.py", line 188, in __init__ self.ws_factory = WebSocketFactory(self) File "C:\Users\srawa\AppData\Local\Programs\Python\Python36\lib\site-packages\daphne\ws_protocol.py", line 123, in __init__ WebSocketServerFactory.__init__(self, *args, **kwargs) File "C:\Users\srawa\AppData\Local\Programs\Python\Python36\lib\site-packages\autobahn\twisted\websocket.py", line 255, in __init__ protocol.WebSocketServerFactory.__init__(self, *args, **kwargs) File "C:\Users\srawa\AppData\Local\Programs\Python\Python36\lib\site-packages\autobahn\websocket\protocol.py", line 3096, in __init__ self._batched_timer = txaio.make_batched_timer( AttributeError: module 'txaio' has no attribute 'make_batched_timer' What is the problem? -
how to post multiple model data through one serializer in django rest api
I have a two model contact and user class Contact(models.Model): name = models.CharField(max_length=50, blank=True) status = models.BooleanField(default=False) class User(models.Model): username = models.CharField(max_length=50, blank=True) password = models.CharField(max_length=50, blank=True) contact_id = models.ForeignKey(Contact, on_delete=models.CASCADE, blank=True, null=True) For these two model I have two serializer class class ContactSerializerModel(serializers.ModelSerializer): class Meta: model = Contact fields = ('name', 'status') class UserSerializerModel(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password','contact_id') Now I want to design a serializer class which take name, username, password, status field. I want to post as key value pair. First name and status value save in the Contact model then with contact model id save username and password in user table. How to design the serializer class in Django rest API? -
How to serve angular and django ? Seperately or from django server?
I'm new to angular. I just created api using django rest framework. Now, I want angular to use as frontend. Created angular components and stuff, but I got stuck in whether serving different server or from django. Researched and got me to serve from django itself. But how to handle the angular routes with django? Also should I use django view context data (django templates) with angular or use all the api data only using angular? -
what is difference between {{}} and {% %} in django templates
I am very new to django and working on it.. I visited a html file and dont know the difference between {{}} and {% %} in html files used as here {% load static %} Thanks a lot -
Identify ImageField through introspection
OK, I understand that ImageField cannot be identified using get_internal_type() (see here). Applied on a field of type ImageField returns FileField which is the superclass of ImageField. How can I then distinguish ImageField from FileField through introspection? I need such a solution in order to apply a generic functionality to arbitrary models. -
NoReverseMatch at /<url> When rendering form
I am relatively new to Django and am trying to insert data into a table using Django form but am stuck at this error: NoReverseMatch at /vinesF/NewVid Reverse for 'NewVid' not found. 'NewVid' is not a valid view function or pattern name. Here are my view, url and html, any help is appreciated def NewVid(request): if request.POST: form= AddVidForm(request.POST) if form.is_valid(): primaryName= form.cleaned_data['primaryName'] Origin= form.cleaned_data['Origin'] PreferredAudience= form.cleaned_data['PreferredAudience'] Date= form.cleaned_data['Date'] Link= form.cleaned_data['Link'] VPath= form.cleaned_data['VPath'] AddPath= form.cleaned_data['AddPath'] FreshVid= video(primaryName=primaryName, Origin=Origin, PreferredAudience=PreferredAudience, Date=Date,Link=Link, VPath=VPath, AddPath=AddPath) FreshVid.save() return HttpResponse("New Video added") else: return render(request,'vine/Newvid.html', {form:'form'}) else: form= AddVidForm() return render(request,'vine/Newvid.html', {form:'form'}) HTML Code <form method="post" action="{% url 'NewVid' %}" > {% csrf_token %} <!-- This line inserts a CSRF token. --> <table> {{ form.as_table }} <!-- This line displays lines of the form.--> </table> <p><input type="submit" value="Create" /></p> </form> {% endblock %} Here's the url handler: app_name ='vinesF' urlpatterns = [ url(r'^NewVid$',views.NewVid, name='NewVid'), ] -
Images cannot be shown in html
Images cannot be shown in html.I wrote codes in models.py class POST(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='images/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] return render(request, 'top.html',{'content':content}) in top.html <div> {% for item in content %} <div> <h2>{{ item.title }}</h2> <img src="{{ item.image }}"/> </div> {% endfor %} </div> When I access in browser, html is shown.<h2>{{ item.title }}</h2> is shown but <img src="{{ item.image }}"/> is not there.When I see page source in GoogleChrome,<img src="/images/photo.jpg"/> is shown. But when I click the url,404 error happens.My application has image/images folder, in images folder surely my uploaded picture is in there.I really cannot understand why this happens.I wrote MEDIA_ROOT&MEDIA_URL in settings.py so I think image is shown in browser. How should I fix this? -
Django UserCreationForm custom fields
I am trying to create form for user registration and add some custom fields. For doing that, I've subclassed UserCretionForm and added fields as shown in django documentation. Then I've created function-based view and template based on this form. Now, I can successfully create user and this user is added to admin panel as expected. Problem is that, I can't add class and style for this form's fields. Widgets are not working except for username field. I'm adding my scripts here for illustrating my problem more accurately: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=32, help_text='First name') last_name = forms.CharField(max_length=32, help_text='Last name') email = forms.EmailField(max_length=64, help_text='Enter a valid email address') class Meta(UserCreationForm.Meta): model = User # I've tried both of these 'fields' declaration, result is the same # fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',) widgets = { 'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}), 'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), 'last_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), 'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), 'password1': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}), 'password2': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'}), } views.py from django.contrib.auth import login, authenticate from django.contrib.auth.views …