Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-webpush: not able to find user in the request object
I am using DRF, and have set up the auth middleware using JWT backend. I used a package safwanrahman/django-webpush which enable sending notifications, based on VAPID. I got the package working with all setup in place, The API to save information is called and executed successfully. The only problem right now is that the user information is not saved. My findings say that this is because I am using DRF. The way DRF injects a user into the request is may be different from how traditional Django does. And hence the request.user in the view function of the package in not found. @require_POST @csrf_exempt def save_info(request): ... # the request.user mostly does not exist web_push_form.save_or_delete( subscription=subscription, user=request.user, status_type=status_type, group_name=group_name) ... Right now i am thinking to make a clone of the repo and make changes directly in order to debug and find the exact issue/solution. Would that work? -
Prevent webpage from scrolling to the top when submitting a form
I have created a form that submits via javascript but each time I submit the form the webpage scrolls to the top. How do I stop that from happening?. I have tried preventDefault() but that stops the form from submitting all together. My form: class myform(forms.Form): columns = forms.MultipleChoiceField(required=False, label=False) def __init__(self, columnList, *args, **kwargs): self.columnList = columnList super(myform, self).__init__(*args, **kwargs) self.fields['columns'].widget = forms.SelectMultiple() self.fields['columns'].choices = self.columnList My HTML: <p> Select tables and download as excel file:</p> <form id="myform" method="POST" name="Tables_selected"> {% csrf_token %} {{ form.as_p }} <input id="mybutton" type="button" class="btn btn-info" value="Download excel" onclick="redirect()"> </form>` Javascript: <script type="text/javascript" > $(function(){ $('#id_columns').change(function(){ $('#myform').submit(); return false; }); }); function redirect() { location.href="{% url 'download_excel' %}"; } </script> I have tried this, but it prevents the form from being submitted, as well as the redirect: $(function(){ $('#id_columns').change(function(){ $('#myform').submit(function(e) { e.preventDefault(); ); }); }); -
Django pk is not working properly in anchor tag
Recently I created a model to save IeeeXtreme rank of our college and created another model with it for connecting xtreme version with its team. model.py is: class Xtreme(models.Model): version=models.IntegerField(default=9,primary\_key=True) team\_no=models.IntegerField(default=1) def \_\_str\_\_(self): return str(self.version) class Team(models.Model): version=models.ForeignKey(Xtreme,on\_delete=models.CASCADE) team\_name=models.CharField(max\_length=50) global\_rank=models.IntegerField(default=1) region\_rank=models.IntegerField(default=1) country\_rank=models.IntegerField(default=1) college\_rank=models.IntegerField(default=1) def \_\_str\_\_(self): return str(self.version) and then I created a tamplate xtreme.html to load the specific version data into template. In main index page I loaded all versions of IeeeXtreme for our college and want to connect each version with its data, so I used PrimaryKey to load it through url . url.py is: from django.contrib import admin from django.urls import path,include from . import views # from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('',views.main,name='main'), path('xtreme/<int:pk>/',views.xtreme,name='xtreme') ] views.py is: from django.shortcuts import render,get_object_or_404 from django.utils import timezone from django.http import HttpResponse from .models import * def main(request): xtreme=Xtreme.objects.all().order\_by("-version") context={ "xtreme":xtreme, } return render(request,'index.html',context) def xtreme(request,pk): xtreme=Xtreme.objects.filter(version=pk).order\_by("-version") team=Team.objects.filter(version\_\_version=pk).order\_by("college\_rank") post = get\_object\_or\_404(Xtreme, pk=pk) context={ "team":team, "xtreme":xtreme, "post":post, } return render(request,'xtreme.html',context) index.html {% load static %} <section class="sec4" id="xtreme"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h1> IEEEXtreme</h1> </div> {% for j in xtreme%} <div class="col-sm-12"> <a href="{% url 'xtreme' [pk=post.pk](https://pk=post.pk)%}"><h3>IEEEXtreme {{j.version}} Rank of our college.</h3></a> </div> {% endfor %} </div> </div> … -
Creating a record in django model through a POST request
I'm pretty much new to Django and Rest Framework. So I trust you guys to help me fix my issue here. I'm on Python 2.7 and Django 1.11. My models - class Item(models.Model): title = models.CharField(max_length=140) user = models.ForeignKey(User) created_date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField(blank=True, null=True) completed = models.BooleanField() completed_date = models.DateTimeField(blank=True, null=True) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30, null=True, blank=True) last_name = models.CharField(max_length=30, null=True, blank=True) ... ... ... I'm trying to post a record to Item model which should get the user email from the request headers and should create the foreign key relation for that particular record. My Serializer for the Item model- class ItemSerializer(serializers.ModelSerializer): user = serializers.RelatedField(source='User',read_only=True) class Meta: model = Item fields = '__all__' My Viewset for Item model - class ItemViewset(viewsets.ModelViewSet): serializer_class = ItemSerializer queryset = Item.objects.all() def perform_create(self, serializer): print 'Im in here', self.request.user user_id = User.objects.get(email=self.request.user) serializer.save(user= user_id) I've checked few blogs and other questions on StackOverflow and reached till this point. Now when I try to post a record am getting a TypeError as below Got a `TypeError` when calling `Item.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid … -
Django 3.0.5 runserver not working, no message after executing
I downloaded Django 3.0.5 on Windows, and when I went to start a new project and attempted to use runserver, I got nothing in the command prompt. No message. Just new prompt C:\Users\\Desktop\wordcount>python3 manage.py runserver C:\Users\\Desktop\wordcount> Anyone know what's going one. -
how to check if a sqlite field is available in django
i want to make something like this, select tipe from table_name where username == user.username im using sqlite, what i have already tried is using this method Entry.objects.get(headline__exact="Cat bites dog") that i got from the django documentation, but i cant find where to put the column that i want to print, because i only want to check one column, and if that column field is equal to teacher then i want to do something with it. -
How to wirte queryset for django to get models count
Model.py class InventoryData(models.Model): AssetID = models.CharField('Asset ID', max_length=30, unique=True) SerialNumber = models.CharField('Serial Number', max_length=30, unique=True) Make = models.CharField(max_length=30, blank=True, null=True) Model = models.CharField(max_length=30, blank=True, null=True) class Meta: verbose_name = 'Inventory Data' verbose_name_plural = 'Inventory Data' def __str__(self): return self.AssetID Views.py def home(request) # ----- For Models ----- # stnd = obj.objects.filter(AssetID__startswith='ASPL-LAPT').order_by('Model').values_list('Model', flat=True).distinct() dev = obj.objects.filter(AssetID__startswith='ASPLB-DEV').order_by('Model').values_list('Model', flat=True).distinct() mac = obj.objects.filter(Make__startswith='Apple').order_by('Model').values_list('Model', flat=True).distinct() desk = obj.objects.filter(AssetID__startswith='ASPLB-DSK').order_by('Model').values_list('Model', flat=True).distinct() # ----- For Counts ----- # cnt = obj.objects.filter(Model__in=mac).distinct().count() context = {'stnd': stnd, 'dev': dev, 'mac': mac, 'desk': desk, 'cnt': cnt, } return render(request, 'App/home.html', context) this is output i am getting: in my DB i have Make as Apple, Lenovo and Model as two models [MacBook Pro 13.0", MacBook Pro 15.0", T440, T450, T540p], each model has 10 laptops, but when i count i am getting total count as 20 for Mac Book and count as 30 for Lenovo Laptops, i need count for every model as MacBook Pro 13.0" -- 10 MacBook Pro 15.0" -- 10 T440 -- 10 T450 -- 10 T540p -- 10 with below query i am getting below table, cnt = obj.objects.filter(Model__in=mac).count() please help me how to write query for table 2 Table1 Table2 -
django // How to refresh or reload inside {% include 'need_refresh_template' %}
Environment django 2.2 python 3.6 Question I attached ACE editor in my template and I'm trying to make live preview with ajax in the template. This is Ace editor template <!-- ACE editor --> <div style="width: 100%; height: 300px;"> <div id="editor"></div> </div> <!-- Preview --> <div style="width:100%; height: 300px;> {% include 'terms_include.html' %} </div> <script> var editor = ace.edit("editor"); editor.setTheme("ace/theme/twilight"); editor.session.setMode("ace/mode/css"); editor.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true }); $('#id_preview').click(function () { var css_data = editor.getValue(); $.ajaxSetup({ headers: { "X-CSRFToken": '{{csrf_token}}' } }); $.ajax({ url: '{% url 'terms_ajax_preview' %}', type: 'POST', data: { css : css_data } }) }); </script> And this is another template which is attached in the first template by include tag <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ contexts }} <script> {% if contexts %} alert('{{ contexts }}'); {% endif %} </script> </body> </html> views.py def terms_ajax_preview(request): if request.is_ajax(): get_text = request.POST.get('css', '') print(get_text) context = { 'contexts': get_text } return render_to_response('api/terms_include.html', context) # return render(request, 'api/terms_include.html', context) print(get_text) is working very well. However I don't have any idea how render context data and reload template inside of include tag. How should I return to display the data added to that template? -
Looping over a specific field in a django form
Learning Django by creating an eBay like bidding application. One of my models is a simple bid class that will record every user's bid for a particular listing. models.py class Bid(models.Model): bid = models.DecimalField(max_digits=10, decimal_places=2) user = models.ForeignKey(User, on_delete=models.CASCADE) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) forms.py def listing_view(request, id): form = BidForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.listing_id = id # check bid is higher than starting bid or other bids or flash error message current_bid = instance.bid starting_bid = instance.listing.starting_bid query = Bid.objects.all().filter(listing=id) In forms.py, I am writing a view to validate that the bid the user entered is larger than existing bids. It's incomplete because I am stuck on creating this comparison. The easy way is to loop over the 'query' variable and do the comparison, but is there a more elegant solution? I found a solution using the all() function, something like: all(current_bid > i in my_list) But this only works for comparing against a list, not form objects Is there a way to loop over query (i.e. for each in query) and get check whether current_bid is greater than all of the 'each.bid' in 1 line? Something like this: all(current_bid > i for … -
How to add lines usning '-' in python Requests
I am working with python Requests in Django and I need a similar functionality to the 'quote_plus' module, I need my words to be joined by a '-' instead of '+'. Is there a module for that? If not then how do i do it? -
How to include description in django api for swagger
I am using django in built user api with drf and swagger. How to make display of the description of api in swagger to the right of user module api class UserViewSet(viewsets.ModelViewSet): """ description: Operations about user. --- retrieve: Return a user instance. list: Return all users. create: Create a new user. delete: Remove an existing user. partial_update: Update one or more fields on an existing user. update: Update a user. """ permission_classes = [permissions.DjangoModelPermissions] queryset = User.objects.all() serializer_class = UserSerializer I am not able to get the descrption in side of user module -
django send_mail result format customization
When I send an email, the result is all without spaces. Is there a way to add spaces and/or format it? # Send Email send_mail( 'Inquiry - ' + property + ' - from my website', 'Property - ' + property + 'Client Email' + email + message + '', 'email@gmail.com', ['email@gmail.com'], fail_silently=False ) This is my result now : Property - Cuixach 2Client Emailtofol@gmail.covmessage example I would like something like this: Property - Cuixach 2 Client Email - email@gmail.com message: Lorem ipsum -
is it possible to return a HttpResponseRedirect from signal?
I'm working with an EDX integration so in my company developed a plugin to extend some functionality, one of them was the Auth0 integration. One problem was that when we logged out we just clean the Django session but the Auth0 session was activated cause never touched it. So I tried to solve this problem using signals, user_logged_out, I thought that it could be a nice solution but when I tried to log out from Auth0 it didn't work. I create a view that handles that, was just an API call, return HttpResponseRedirect(logout_url) but when I tried to call from the signal was impossible to do the logout. I tried with redirect(reverse(view_url)), also, I create a class instance and then called the function but I failed. My solution was to modify the frontend code to call the new view to complete the logout but I'm pretty interested on why I failed. -
Django: django-tables2 Show just one row in a DetailView
I am using django-tables2 to display information in my database. BuildingDetailTable and EnergyTable are in the same template and want them to be the equivalent of a DetailView of one object in my database. At the moment when I select a row in the BuildingListTable in my BuildingListView the page goes to the correct building_detail page, but the BuildingDetailTable and EnergyTable display all objects in the database and I don't know how to filter them to just the row for the object of interest. My abbreviated code is: #models.py class AnnualUse(models.Model): elec = models.IntegerField(default=0, verbose_name='Elec kWh') gas = models.IntegerField(default=0, verbose_name='Gas ccf') wtr = models.IntegerField(default=0, verbose_name='WTR kgal') fiscal_year = models.ForeignKey(FiscalYear, on_delete=models.CASCADE) building = models.ForeignKey('Building', on_delete=models.CASCADE) def __str__(self): return '%s %s' % (self.building, self.fiscal_year) class Building(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) acronym = models.CharField(max_length=3) full_name = models.CharField(max_length=200) area = models.IntegerField() notes = models.TextField(blank=True) use_type = models.ForeignKey(UseType, on_delete=models.CASCADE) zone = models.ForeignKey(Zone, on_delete=models.CASCADE) def __str__(self): return self.acronym def get_absolute_url(self): return reverse('building_detail', args=[str(self.id)]) # tables.py class BuildingListTable(tables.Table): acronym = tables.Column(linkify=True) class Meta: model = Building fields = ('acronym', 'full_name', 'use_type', 'area') class EnergyTable(tables.Table): class Meta: model = AnnualUse fields = ('fiscal_year', 'elec', 'gas', 'wtr') class BuildingDetailTable(tables.Table): class Meta: model = Building fields = ('acronym', … -
Python Django ConnectionAbortedError [WinError 10053]
So im facing a weird issue while making a request to my api. It works fine using something like postman. I get my response no issue but if I make a request from my frontend(on a seperate domain) the connection gets closed for some reason. Here is my code I make ajax request using axios axios.get(mydomain/api/oauth) .then(response => { console.log(response) }).catch(error => { console.log(error.response.data) }) which hits my backend method that should return a response like so def oauth(request): auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT ) url = auth_client.get_authorization_url([Scopes.ACCOUNTING]) request.session['state'] = auth_client.state_token return HttpResponse(url) But at this point I get this alarm ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine And like I said if I make this same request through postman I get my response. So I don't know what I am missing. I have applied cors thinking maybe its because my frontend is on seperate domain from backend but no luck. Plus the alarm is kind of vague... anybody face similar issue? -
Ajax in Django To Populate Form Field
I am trying to learn to use ajax and could use some help. I want to click a button and have that populate a django form field, Exporter. Here is what I have. I know my script is not sufficient, but I am novice and would hope to use this as a functioning example for myself. So upon click of button #populate, the Exporter form field should populate with 'Me'. Thanks! views.py def Ajax(request): if request.is_ajax(): exporter = 'Me' data = json.dumps(exporter) return HttpResponse(data, content_type='application/json') proforma.html <button id="populate"> Populate </button> ... <table class="table2" width=100%> <tr class="bigrow"> <td rowspan = 2 >Exporter: {{form.Exporter}}</td> <td colspan = 2 >Pages:</td> </tr> </table> ... $("#populate").click(function() { $.ajax({ url: "/ajax/more", success: function(data) { $("#exporter").load(); } } }); }); </script> forms.py class ProformaForm(forms.ModelForm): class Meta: model = Proforma fields = [ 'Name', 'Shipment', 'Exporter'] widgets={ 'Exporter': forms.TextInput(attrs={'id': 'exporter'}), } -
How to make forms dynamic in Django
This question is more theoretical than practical. So, this is a Django project about tracking workouts. I have several models in this project. 1) Workout. It contains fields user and date. 2) Exercise. It contains fields workout (which connects to the model above), name, sets, repetitions, and weight. My idea is as follows: You have an HTML table for each of the workouts, which contains each exercise in a new row. You can add and delete exercises "on the fly" by adding or deleting rows and the data inside <td> tags is editable in the table itself. My question is: 1) How to implement the models (or forms) into an HTML table and make the data editable. 2) How to save models automatically. Kind of like auto-save in Google Docs or something like that. This includes the addition or deletion of exercises and the information about them. I understand that this is a lot to ask, so replies about any part of the project are welcome. I also suspect that a REST API will be needed for this. I have not explored what that is in-depth and how that might help me solve my problem. So, if that is the … -
Displaying ModelAdmin fields in the same line issue
I delved in Django Documentation(https://docs.djangoproject.com/en/3.0/ref/contrib/admin/) and I found out I can display fields name in the same line by wrapping with tuple. So this is how I did: class MovieAdmin(admin.ModelAdmin): fields = (('title','length'),'release_year') admin.site.register(Movie, MovieAdmin) But my admin site shows only removed horizontal line between fields names, not displaying two names in the same line. Here's my screenshot: enter image description here Using Django 3.0.3, Python 3.8. Thanks. -
Deploy MAX (Model Asset Exchange) to Heroku
I want to deploy MAX model that is cloned from IBM's git repository to my heroku account. Can I deploy above git repository to my heroku account? And if so, is the way I will have to do same at the way of deploying original django or rails applications? -
I am not able to access my admin in Django
I have Ubuntu VM with Apache Server on which i am running my application. I have inserted some login and registration file using Filezilla. But my registration, Login and admin page is not working. It is giving me Exception Type: OperationalError Exception Value: attempt to write a readonly database I tried the following after doing some Stackoveflow. chown root db.sqlite3. Unfortunately, I still get the same error when trying to access above page. Any help would be greatly appreciated! Probably something to do with changing user permission which i have no idea where to start in diagnosing what permission issue is going on. -
django passwordless cannot create account
I got an unusual issue that I've stumbled upon when implementing django-rest-framework-passwordless. After integrating the module in my Django app when I make the first API request it gets processed, the user gets created and everything works flawlessly, but when attempting to create another account it crashes. IntegrityError at /passwordless/auth/email/ UNIQUE constraint failed: auth_user.username Request Method: POST Request URL: http://127.0.0.1:8000/passwordless/auth/email/ Django Version: 2.2.10 Python Executable: /home/terkea/django_react_template/src/venv/bin/python Python Version: 3.6.9 Python Path: ['/home/terkea/django_react_template/src', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/terkea/django_react_template/src/venv/lib/python3.6/site-packages'] Server time: Tue, 14 Apr 2020 02:04:41 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'corsheaders', 'rest_auth', 'rest_framework.authtoken', 'drfpasswordless', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'api'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] As it says in the django.allauth docs I've disabled the username and made the email mandatory but for some reason, it doesn't wanna pick up on those changes. ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' -
Heroku admin page needs to be styled
I built a website using Django/bootstrap and launched with Heroku. The site looks great, but my admin page looks horrible. No styling. How can I apply styling to my https//mywebsite.herokuapp.com/admin/ page?? Thanks, Tad -
storing files in models.py from views.py
I am trying to fill a Django model field with a pdf that is altered by the user's input in views.py. My Models.py is structured like so: class Model(models.Model): file01 = models.FileField(upload_to=upload_location, null=True, blank=True) My Forms.py is structured like so: class Form(forms.ModelForm): class Meta: model = Apply fields = ['file01'] My Views.py is structured like so: def View(request): string = 'hello world' file01 = form.cleaned_data.get('file01') canvas = canvas.Canvas(BytesIO(), pagesize=letter) canvas.drawString(10, 100, string) canvas.save() BytesIO().seek(0) new_pdf = PdfFileReader(BytesIO()) existing_pdf = PdfFileReader(open("media/01.pdf", "rb")) page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) PdfFileWriter().addPage(page) PdfFileWriter().write(open("newfile01.pdf", "wb")) #Here is where I hit a wall VVV file01 = 'newfile01.pdf' form.save() return redirect('home') the string is successfully printing on the document but it is being output to src directory. I am struggling to find an example of a situation like this in the Django docs (storing of altered files in models.py). Any help would be greatly appreciated, including links to related Django documentation. -
Django Robots.txt Change Content-Type Header
Firefox error: The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature.+ Using https://django-robots.readthedocs.io/en/latest/ It should probably be: content="text/html; charset=utf-8" or "text/plain; charset=UTF8" not 'text/plain' Current code: url(r'^robots\.txt/', include('robots.urls')), Alternatives? path('robots.txt', TemplateView.as_view(template_name="robots.txt", content_type='text/plain')), url(r'^robots.txt', lambda x: HttpResponse("User-Agent: *\nDisallow:", content_type="text/plain"), name="robots_file"), How do you combine include('robots.urls') with the alternatives or is it not possible? curl -s -D - 127.0.0.1:8000/robots.txt/ HTTP/1.1 200 OK Date: Tue, 14 Apr 2020 01:05:52 GMT Server: WSGIServer/0.2 CPython/3.7.3 Content-Type: text/plain -
Creating and editing objects with different features Django
I'm new to web developing with Django. I'm creating a website where I have multiple objects with different features: Character: Name, description, morality, strength. Item: Name, description, owner. Adventure: Name, description, characters, places, duration. Some of this features are the same for the objects (like name and description) but some aren't. Users will be able to create and edit each one of these objects. I would like to not have to program code to create and edit each one individually and just have to do it once for an object that can be any of these and that will only have the features corresponding to that object, but I don't know how. I tried making an object with a type which would be "Character" or "Item" depending on what it was and then picking the features using an if Object.name == "Character" but that didn't work. What should I do? Another problem that I have is that for my Adventures I can only choose one character and I would like to be able to choose an undefined amount of characters. Since I'm still learning I'm not sure how to do that exactly.