Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Queryset with values filtered from another queryset
If I have a queryset qs1 like this: <QuerySet [{u'name': u'John', u'birthdate': u'1980-01-01'}, {u'name': u'Larry', u'birthdate': u'1976-12-28'}, .....']} I need to use all values associated with key 'name' from qs1 to query another model and get qs2 like this: <QuerySet [{u'student_name': u'John', u'grade': u'A'}, {u'student_name': u'Larry', u'grade': u'B'}, .....']} After this, I have to combine qs1 and qs2 so the final_qs like this: [{u'name': u'John',u'birthdate': u'1980-01-01', u'grade': u'A'}, {u'student_name': u'Larry', u'birthdate': u'1976-12-28', u'grade': u'B'}, .....']} How would I achieve this? I have code like this: qs1 = Person.objects.values('name', 'birthdate') for t in qs1: qs2 = Grades.objects.filter(student_name=t['name']) .values('student_name', 'grade') My qs1 looks OK. However, my qs2 becomes this: <QuerySet [{u'student_name': u'John', u'grade': u'A'}]> <QuerySet [{u'student_name': u'Larry', u'grade': u'B'}]> Because of qs2, I am not able use zip(qs1, qs2) to construct final_qs the way I want. -
Django Push Notification with Android App
I am working on an Android project where I am using DJANGO as my backend. There are 2 kinds of android app I needed to create.Suppose they are App1 and App2. Now I am sending message from App1 to App2 and vice versa and i also need real time update in both the app for which i am using django push notification.But I am not getting really good examples on how to implement this django as a backend in Firebase cloud messaging between both of my android apps.I am really new to this .Please help me I am really stuck in this from quite a few days and I dont what to do. -
Update field in rendered Django Form
I'm having a hard time figuring out how to update a Field in Django Form while editing the Form. In my form I have a ModelChoiceField and ChoiceField: first is a list of Car manufacturers, second is a list of models available for this manufacturer. Obviously I don't want to fill second field with models for every manufacturer but only for one selected in first ModelChoiceField. Here's my example Form: class PostForm(forms.ModelForm): make = forms.ModelChoiceField(queryset=Manufacturer.objects.all()) model = forms.ChoiceField() ... In my template after I render PostForm I disable model field with jQuery and wait for user to select some value in make field. And then use AJAX to request values for model field (in this sample code I only return single item): $('#id_make').change(function () { $.ajax({ url: '{% url 'get_models' %}', data: {'make': $('#id_make :selected').text()}, dataType: 'json', success: function (data) { $('#id_model').append($('<option>', { value: 1, text: data.model})).removeAttr('disabled'); } }); }) With this done I do see updated options in <select> element for model ChoiceField, but after I select new value in model ChoiceField and submit form I receive: Select a valid choice. 1 is not one of the available choices." '1' is id of the element that I appended to … -
Setting the name of a javascript variable using Django variable
Curious one - how do you set a javascript variable’s name to that of a Django variable? I need something like: var “{{django_variable}}” = I’ve tried this but the script just sees var “” = Any pointers? -
Overriding Django Username Value
I want to make my (Django built-in User class) username field more obfuscated. Is there any downside to this code (testing+working): @receiver(pre_save, sender=User) def presave_user_override_username(sender, instance=None, created=False, **kwargs): #Reference: https://stackoverflow.com/questions/11561722/django-what-is-the-role-of-modelstate if instance._state.adding is True: while True: rstr = random_string_generator(20) # eg. UlBxNgZV04bbLNE5A7Fz if not User.objects.filter(username=rstr).exists(): instance.username = rstr break Users will be created with django-allauth with Social Providers only for now. In the off chance that I decide to allow email sign-up, I can have them login with their e-mail address. Right? Any foreseeable issues or better approaches? -
Python - Django 2.0 - URL patterns, passing arguments
First of all I am completely new to web development and Python, however I am enjoying the language. I am writing a very basic web page which has a text box where a user can type in a username, then hit the Ok button which submits a form using a GET request. The GET passes the username as an argument and searches the auth_user table in the database. My problem is I am not able to pass the username argument, please help if you can Django 2.0 url patterns urls.py app_name = 'just_gains' urlpatterns = [ path('lifecoaching', views.LifeCoach, name='life_coaching'), path('lifecoaching/resultslifecoaching/<user_name>', views.LifeCoachSearchResults, name='results_life_coaching'), ] forms.py class LifeCoachSearch(forms.Form): user_name = forms.CharField(label='Username', max_length=100, required = False) views.py def LifeCoach(request): if request == 'GET': form = LifeCoachSearch(request.GET) if form.is_valid: user_name = form.cleaned_data['user_name'] LifeCoachSearchResults(request,user_name) else: form = LifeCoachSearch() return render(request, 'just_gains/life_coaching.html', {'form': form}) def LifeCoachSearchResults(request, user_name): testUser = User.objects.filter(username__startswith=user_name) context = {'TestUser': testUser} return render(request, 'just_gains/results_life_coaching.html', context) HTML (lifecoaching) <form action="{% url 'just_gains:results_life_coaching' %}" method="GET" > {% csrf_token %} {{ form }} <input type="submit" value="OK"> </form> HTML (resultslifecoaching) <ul> <li><a>print usernames that match the argument</a></li> </ul> Thanks -
django REST urls.py does not resolve endpoint
Noob here. I am using https://github.com/Seedstars/django-react-redux-base which is great and straight forward Django REST + React.js starter project. This is Django 1.11. My problem is with the Django REST backend not resolving the API endpoints correctly. I have added an application profiles that should return a user profile when queried by: /api/v1/profiles/getprofile/(some_name) Here is my top-level urls.py: from django.conf import settings from django.conf.urls import include, url from django.views.decorators.cache import cache_page from base import views as base_views urlpatterns = [ url(r'^api/v1/accounts/', include('accounts.urls', namespace='accounts')), url(r'^api/v1/getdata/', include('base.urls', namespace='base')), url(r'^api/v1/profiles/', include('profiles.urls', namespace='profiles')), url(r'', cache_page(settings.PAGE_CACHE_SECONDS)(base_views.IndexView.as_view()), name='index'), ] My profiles/urls.py: from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from . import views urlpatterns = [ url(_(r'^getprofile/(?P<display_name>.*)/$'), views.PublicProfileView.as_view(), name='getprofile'), ] With This setup, when I query http://localhost:8000/api/v1/profiles/getprofile/test, I get the IndexView in the response, basically html containing the frontend. However if I comment out r'' from the top level urls.py I get the expected JSON payload for the 'test' profile that I have in the database. Why would the resolver skip r'^api/v1/profiles/ and resolve straight to r''? Am I doing this wrong? -
Error connecting Django 2.0 with sql server 2014 using python 3.6
I am new in Django and I am trying to connect it with Sql server. As I read there is a third party connector for this. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Program Files\Python36\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Program Files\Python36\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Program Files\Python36\lib\site-packages\django\db\models\base.py", line 114, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Program Files\Python36\lib\site-packages\django\db\models\base.py", line 315, in add_to_class value.contribute_to_class(cls, name) File "C:\Program Files\Python36\lib\site-packages\django\db\models\options.py", line 205, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Program Files\Python36\lib\site-packages\django\db\__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Program Files\Python36\lib\site-packages\django\db\utils.py", line 202, in … -
XML parsing and mathematical addition DJANGO REST
How to read data from xml by URL and fold with the entered number in the field, html forms ? DJANGO REST FRAMEWORK XML: <item> <title>USD</title> <pubDate>29.01.18</pubDate> <description>320.66</description> <--required number <quant>1</quant> <index/> <change>0.00</change> <link/> </item> eg: You enter the number: result = 10 * 320.66 print result //3206.6 P.S. Google Translate. I can explain to you more clearly what I need in Russian. Please help :) -
Django ignores timezone
I am trying to print a range of timestamps which are stored in a table. The timestamps are stored in the following format. 2018-01-28 15:00:00-05:00 2018-01-28 16:00:00-05:00 2018-01-28 17:00:00-05:00 2018-01-28 18:00:00-05:00 2018-01-28 19:00:00-05:00 2018-01-28 20:00:00-05:00 2018-01-28 21:00:00-05:00 2018-01-28 22:00:00-05:00 2018-01-28 23:00:00-05:00 2018-01-29 00:00:00-05:00 2018-01-29 01:00:00-05:00 2018-01-29 02:00:00-05:00 Now I am trying to access the rows that match a range and print the timestamp using the below code. timenow = datetime.datetime.now() forecasts = Forecast.objects.filter(timestamp__range=(timenow,timenow + timedelta(days=1))) for forcast in forecasts: print(forcast.timestamp) Output: 2018-01-28 21:00:00+00:00 2018-01-28 22:00:00+00:00 2018-01-28 23:00:00+00:00 2018-01-29 00:00:00+00:00 2018-01-29 01:00:00+00:00 2018-01-29 02:00:00+00:00 2018-01-29 03:00:00+00:00 2018-01-29 04:00:00+00:00 2018-01-29 05:00:00+00:00 2018-01-29 06:00:00+00:00 2018-01-29 07:00:00+00:00 However, I keep getting the invalid timestamps. I am not sure what is wrong here since I have already set the TIME_ZONE and USE_TZ variables. TIME_ZONE = 'America/Toronto' USE_TZ = True -
How to subclass AbstractUser in Django?
I'm trying to extent my user model. In the Django documentation for extending the user model it says: ... just want to add some additional profile information, you could simply subclass django.contrib.auth.models.AbstractUser I don't have experience in subclassing models. I've set everything up except for subclassing the model to AbstractUser and can't seem to find good documentation on it. Does anyone have experience subclassing AbstractUser? My models.py: class AuthKey(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) authkey = models.CharField(max_length=100) My admin.py: class AuthenticationKeyInline(admin.StackedInline): model = AuthenticationKey can_delete = False verbose_name_plural = 'AuthenticationKey' # Defines a new User admin class UserAdmin(BaseUserAdmin): inlines = (AuthenticationKeyInline, ) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) -
django: github oauth app always returns 404 not found
I am using this article for social auth with github. Actually I am already using 1 github oauth app, by refering to this article. But this time, I am always getting this, I am using the same config as in the article, Is there any problem with my app? -
I have one questions in Django.. I don't have any logic about that i am learning
I have one list like id name dob 1 xyz 1989-10-31 2 abc 1994-11-29 3 asd 1996- 06 - 28 4 adf 1993 - 05 -06 5 abc 1992 - 07-09 6 tre 1996- 07 -28 I want to show to user like this id name dob year 1 xyz 1989-10-05 2017 2 abc 1992 - 07-09 2017 3 adf 1993 - 05 -06 2017 4 abc 1994-11-29 2017 5 asd 1996- 06 -28 2017 6 tre 1996- 07 -28 **2018** i can give starting year by my self but it show first five user to starting year then next five can see next year means 2018 i want do it continues ...... -
How is the python interactive shell connected to Django?
Hello fellow programmers! I am reading about the functionality of the interactive shell reached through running '...python manage.py shell'. This is something that I have done many times before, however I am not quite sure exactly How the actual shell connects with Django. Before asking this question, I have indeed tried to find my way through the official documentation - as well as other posts on this website. This question does not appear to have been presented with an answer a beginner like me can comprehend. I have read that the 'manage.py shell'-command 'gives us an interactive shell with the Python path set up correctly for Django.'. I know that it can be used to interact with a Django project, and to query configured databases and models - however what happens behind the scenes? For example, when writing 'ModelName.objects.all()' - what is the origin of '.objects' and '.all()', because it does not seem to be pure python syntax? How does Django understand this? Is the shell a special python-version provided by Django, with some added syntax that Django understands? Because that would make sense. Thank you from Sweden! -
How to display different custom users after logging in Django
I have 2 custom users, student and teacher. I want that if student is logged in, a particular message is displayed, otherwise if teacher is logged in, another message to show. {% if request.user.is_authenticated %} {% if user is student %} <p>Welcome, {{ user.student.surname }} Thanks for logging in.</p> {% else %} {% if user is teacher%} <p>Welcome, {{ user.teacher.surname }} Thanks for logging in.</p> {% endif %} {% endif %} class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) User.student = property(lambda p: Student.objects.get_or_create(user=p)[0]) User.teacher = property(lambda p: Teacher.objects.get_or_create(user=p)[0]) -
Why my User Registration Page Gives 'The view didn't return an HttpResponse object. It returned None instead.' Error?
I want to create a user registration form in django by following django tutorial part 15. However, here's an error that is on my way. My views.py is from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render,redirect def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('/polls') else: form = UserCreationForm() args = {'form': form} return render(request, 'polls/reg_form.html', args) And, it is giving an error. The view polls.views.register didn't return an HttpResponse object. It returned None instead. -
django update table without form
Why i can't update my table when i was wanted to insert to database? def insert3(request): inputasset3 = InputAsset3.objects.all() DT = datetime.datetime.now().date() for a in inputasset3 : if a.nama_field == "Subang Field" and a.date.date == DT: InputAsset3.objects.update(InputOil_Target=InputOil31) InputAsset3.objects.update(InputOil_Target=InputGas31) else: input1 = InputAsset3.objects.create( id_Kode_field = get_object_or_404(Asset3,pk=1), nama_field = "Subang Field", Gas_Target = Asset3.objects.values_list('Gas_Target',flat=True)[0], Oil_Target = Asset3.objects.values_list('Oil_Target',flat=True)[0], InputOil_Target=request.POST.get('InputOil31', False), InputGas_Target=request.POST.get('InputGas31', False) ) input1.save() if a.nama_field == "Jatibarang Field" and a.date.date == DT: InputAsset3.objects.update(InputOil_Target=InputOil32) InputAsset3.objects.update(InputOil_Target=InputGas32) else: input2 = InputAsset3.objects.create( id_Kode_field = get_object_or_404(Asset3,pk=2), nama_field = "Jatibarang Field", Gas_Target = Asset3.objects.values_list('Gas_Target',flat=True)[1], Oil_Target = Asset3.objects.values_list('Oil_Target',flat=True)[1], InputOil_Target=request.POST.get('InputOil32', False), InputGas_Target=request.POST.get('InputGas32', False) ) input2.save() if a.nama_field == "Tambun Field" and a.date.date == DT: InputAsset3.objects.update(InputOil_Target=InputOil33) InputAsset3.objects.update(InputOil_Target=InputGas33) else: input3 = InputAsset3.objects.create( id_Kode_field = get_object_or_404(Asset3,pk=3), nama_field = "Tambun Field", Gas_Target = Asset3.objects.values_list('Gas_Target',flat=True)[2], Oil_Target = Asset3.objects.values_list('Oil_Target',flat=True)[2], InputOil_Target=request.POST.get('InputOil33', False), InputGas_Target=request.POST.get('InputGas33', False) ) input3.save() break return render(request,"index/datasaved.html",{}) -
Django local development, Chrome Blocking requests to local server in frame
Im developing a web application using the local dev server provided by Django. My local web-app is to be emmbeded in an iframe of a remote site. But when testing Chrome loads the remote site encappsulating webpage (page which is meant to wrap my web-app in an iframe but blocks requests towards my local dev server in the iframe, which makes testing impossible. I have looked in chrome's console and get the following error: Refused to frame 'https://localhost:8000/' because it violates the following Content Security Policy directive: "child-src 'self' https://* shopify-pos://*". Note that 'frame-src' was not explicitly set, so 'child-src' is used as a fallback. My questions: 1) Why is Chrome blocking requests? 2) Is this error being caused because I am using localhost? and framing work fine on Chrome once I deploy on a production server with domain name? 3) Is there anyway that I may circumvent this error while I am on local host for testing purposes? -
How to highlight code when posting on a website dynamically?
I'm having a website made with django it is basically a tutorial website and i want to highlight code dynamically into my tutorials what should i do? -
Django environment error in pulled Pycharm project
I created a new Django project in pycharm and ran it on my system. Works fine without any issues. I pushed the project to github. But when my teammates pull the same project, they face issues with the configuration. There are questions available on SO regarding this but none of them seemed to solve my issue and pycharm throws the same Error: Django is not importable in this environment. Here are some of the troubleshooting techniques I tried but to no use: Checked the project python interpreter on my teammates system. It is correctly setup. Pushed the project first with and then without the .idea folder. I thought there might have been some issue with the config there but both didn't work. Created a new virtual environment which gets setup correctly but again does not work. Is there something obvious that I am missing? Any pointers as to which files to ignore and which files to push in Django while working in a team so that the configurations do not conflict? -
form object has no attribute 'email' in django
I have a registration form made of 2 forms, from which email field gets saved in both User and Student models. Now, I made an update account info view. Problem is, I want that email will get updated the in both models. But I get error: 'StudentEditForm' object has no attribute 'email' Here is my code: class StudentEditForm(forms.ModelForm): email = forms.EmailField(required=False) name = forms.CharField(max_length=30) surname = forms.CharField(max_length=50) photo = forms.ImageField(required=False) phone = forms.CharField(max_length=15, required=False) class Meta: model = Student fields = ('email', 'name', 'surname', 'phone', 'photo') class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')], null=True, blank=True, default=None) photo = models.ImageField(upload_to='students_images', null=True, blank=True, default=None) phone = models.CharField(max_length=15, null=True, blank=True, default=None) def __str__(self): return self.surname User.student = property(lambda p: Student.objects.get_or_create(user=p)[0]) def profile_edit(request): user = request.user student = request.user.student if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) user.email = form.email form.save() return render(request, 'index.html') context = { "form": form, } return render(request, "registration/profile_edit.html", context) Again, I need that I will be able to update the email … -
Django foreign key issue
I have a requirement where I am creating user and want to define foreign key relation by creating other user and link both. Mean user1 is created by user2 and user2 is stored in different model. user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) Not sure about how to implement this. Help appreciated! -
Django somehow cannot determine simple annotate function
I'm trying to create an annotation on a queryset class that simply adds a boolean that is the result of some standard queries. CustomQueryset(models.QuerySet): """ An extension of the traditional queryset to support filtering on accepting_offers """ def annotate_with_accepting_offers(self): """ Add a lovely little variable to the SELECT that says if the listing is accepting offers. A <thing> is accepting offers when its: + not cancelled + expire date is today or in the future + has spaces left """ return self.annotate(accepting_offers=Q(cancelled=False) & Q(expire_date__gte=date.today()) & Q(spaces_left__gt=0)) This unfortunately does not work, any ideas what annotation would? If this was SQL, the top line would look like: SELECT *, (cancelled=False AND expire_date >= ? AND spaces_left > 0) AS accepting_offers -
Python/Django: Offering a zip file for download from io.BytesIO buffer
I'm trying to put a zip file into an io.BytesIO buffer and then offer that for download. Below is what I've got (part of a longer views.py, I'm just posting the relevant part). But I'm getting the error message "AttributeError at / 'bytes' object has no attribute 'read'". Can anyone tell me what I'm doing wrong? from django.http import HttpResponse from wsgiref.util import FileWrapper from zipfile import * import io buffer = io.BytesIO() zipf = ZipFile(buffer, "w") zipf.write ("file.txt") zipf.close() response = HttpResponse(FileWrapper(buffer.getvalue()), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=file.zip' return response -
How can i delete database table in django?
I changed my models and made migrations. Then i changed my models another one time and when try python manage.py migrate i get error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, shop Running migrations: Applying shop.0004_auto_20180128_1331...Traceback (most recent call last): File "/home/morilon/dj/intshop/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/home/morilon/dj/intshop/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 301, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: table "shop_brand" already exists So my question is - how can i delete table "shop_brand"??? I already tried flush and sqlflush but that only delete data from table but not actually table "shop_brand". I use django 2.0.1 and python 3.6