Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check if model a has a User in it?
I have two models class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,) name = models.CharField(max_length=128) #actual creator's name In a html page I want to check if Profile model has current logged in user in it? I am using this line {% if Profile.objects.filter(user=user).exists() %} I know this is wrong, I am beginner to Django and web development. Could some one help with this? Thanks. -
django failing on LiveServerTestCases
My other tests pass fine, but when I use selenium to test, the tests run fine but when a test ends it always produces the following error after completing the tearDown function: File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.py", line 239, in _commit return self.connection.commit() django.db.utils.IntegrityError: FOREIGN KEY constraint failed It doesn't appear to be related to my database as the error only occurs for LiveServerTestCases. -
Django - User should only able to vote once
i want that a user is only able to vote once for a category-request but somehow i get the following error and i dont know how to "properly" call the instance at that point: Cannot assign "1": "CategoryRequests_Voter.voted" must be a "CategoryRequests" instance. models.py # Category Requests Model class CategoryRequests(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) .... # Vote(s) of Category Requests Model class CategoryRequests_Voter(models.Model): voter = models.ForeignKey(User, on_delete=models.CASCADE) voted = models.ForeignKey(CategoryRequests, on_delete=models.CASCADE) published_date = models.DateField(auto_now_add=True, null=True) def publish(self): self.published_date = timezone.now() self.save() views.py def category_request_up_vote (request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) if request.method == 'GET': if CategoryRequests_Voter.objects.filter(voter=request.user, voted=category_request.pk).exists(): messages.error(request, 'You already voted for this request.') else: category_request.up_vote = F('up_vote') + 1 category_request.save() CategoryRequests_Voter.objects.create(voter=request.user, voted=category_request.pk) messages.success(request, 'You have successfully Provided an Up-Vote for this Request') return redirect('category_request_detail', pk=category_request.pk) else: messages.error(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) Thanks in advance -
Django - How to change current form to update on submit?
I’m creating a profile page in my web application & I have a form to when the user makes a form submission I need the data from the form to update in the django admin from the current logged in user. The data populates in the admin however new listings keep getting added every time the user submits this form. I need the the data to update only in 1 field per logged in user and not repeat. Screenshot attached. How do I execute this correctly with my current code? The Custom User Model I’m using is located in from users.models import CustomUser if that helps. Any help i gladly appreciated, Cheers user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver … -
Django urlpatterns - too many values to unpack
I am a beginner in Python and Django working on a simple IoT tutorial found in a book. The project is to control a led circuit from a Django app. After I copied of the code, few errors popped up because of the Python and Django version in the book as they are old versions. I am working on Python 3.7.2 and Django 2.1.4 and upon searching, I couldn't find the way to fix my code. Hopefully someone can direct me to the direction to fix it. the directory of my project is as follows Project1 Project1 __init__.py settings.py urls.py wsgi.py FirstApp admin.py apps.py controller.py index.html models.py serializers.py tests.py views.py The problem that I am facing is in the urls.py which the code for it is: from django.conf.urls import * from django.contrib import admin from rest_framework import routers from FirstApp import views admin.autodiscover() router = routers.DefaultRouter() router.register(r'mode',views.ModeViewSet) router.register(r'state',views.StateViewSet) urlpatterns = [ url(r'^', router.urls), url(r'^api-auth/', 'rest_framework.urls',namespace='rest_framework'), url(r'^admin/', admin.site.urls), url(r'^home/', 'FirstApp.views.home') ] The error traceback is this Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7593e6a8> Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 379, in … -
django rest framework serializers correct way to display date time fields in the user timezone
I have many models with a created field of type DateTimeField with auto_now_add=True. My purpose is to display the user the 'created' field in his local timezone. I have the settings: USE_TZ = True TIME_ZONE = 'UTC' I use PostgreSQL. Is it possible for the serialization output to convert the UTC timezone to the user timezone? Just like DRF does content negotiation to determine the output format (xml/json/browser), I wonder if it is possible to do the same to infer the user timezone. Or maybe doing the same at the queryset level. I'm not sure what's the better way. If it is not possible to detect the user timezone from the request, I could provide the user timezone in a custom HTTP header or parameter, with some javascript setup. But even then, how can I hook that to DRF? -
Send items from forloop populated data in django template through ajax to django view
I have been trying to create a click and populate div with ajax in my django e-commerce application. The project works in such a way that when a customer clicks on a category in men's page it populates another div gender.html {%for cate in cat%} <a href="javascript:getcat()" id="catgend" cats-data="{{cate.catname}}" gen-data="{{gens.gender}}" data-sort-url="{% url 'Home:sortcat' cpk=cate.pk %}" >{{cate.catname}}</a> {% endfor %} <div id="products"> <div class="progress"> <img src="{% static 'img/load.gif'%}"> </div> </div> This sends the data to my django view through the ajax function called getcat but the data sent through is that of the first item in the loop in-respective of the loop item clicked on. below is my ajax function: getcat() function getcat() { $(".progress").show() var cat = $("#catgend").attr("cats-data"); var gender= $("#catgend").attr("gen-data"); var url = $("#catgend").attr("data-sort-url"); $.ajax({ url: url, data: { 'cat': cat, 'gender':gender, }, success: function (data) { $("#products").html(data); } }); $(".progress").hide() } enter code here From my research i discovered its because they have same ID. How do i solve the issue of dynamically changing the id over the same loop. Thanks -
Django Passing Newly Created ID from Models.Manager to Views
I'm trying to pass the newly created id for a new entry from Models.Manager to views, so I can save it as a variable. views.py def save_form(request): item_a = request.POST['item_a'] item_b = request.POST['item_b'] Items.objects.save(item_a, item_b) print (saved.id) return redirect ((reverse('project:index'))) models.py class ItemsManager(models.Manager): def save(self, item_a, item_b) item_a = item_a item_b = item_b saved= Items.objects,create( item_a = item_a, item_b = item_b) return (True, saved) class Items(models.Model): item_a=models.CharField(max_length=255) item_b=models.CharField(max_length=255) objects = ItemsManager() What I'm trying to do is get the id of the saved entry and send it to the views. I tried using return saved, return saved.id and return save.id on the Models Manager to pass it to the views. Right now I have it as True, saved because it's what I've gather is the correct way after reading a few posts. However when I come to the views I'm not getting the id I want. When I try print (saved.id) in views I get: NameError: name 'result' is not defined I also tried in views if save = [0]: print(saved.id) and I get: if saved = [0] ^ SyntaxError: invalid syntax Right now I'm just trying to print, but once I know the value is making it to the … -
How to implement update_or_create inside create method of ModelSerializer
The code: class OTP(AppModel): phone_regex = RegexValidator(regex=r'^[6789]\d{9}$', message="phone no. is invalid.") phone_number = models.CharField(validators=[phone_regex], max_length=10, unique=True) code = models.CharField(max_length=255) def __str__(self): return str(self.phone_number) + ": "+str(self.code) class OTPSerializer(serializers.ModelSerializer): code = serializers.CharField(max_length=None, required=False) class Meta: model = OTP fields = ('id', 'code', 'phone_number') read_only_fields=('id', 'code') @transaction.atomic def create(self, validated_data): phone_number = validated_data.pop("phone_number") otp, created = OTP.objects.update_or_create( phone_number=phone_number, defaults={"code": generate_otp()}) return otp I am trying to do update_or_create inside the create method of the django-rest-framework's ModelSerializer. But, the field phone_number inside the model OTP must be unique. Hence the unique=True. I was able to post a phone_number and create the object. But, posting the same phone_number again throws error otp with this phone number already exists, instead of updating it if it already exists as I have overridden the create method. Please help! -
Django all-auth, thoughts on creating guest account without login
So I've used django-allauth before and it is great for user registration and login features. I'm currently working on a small app that requires some sort of "Guest Check-out", an employee should be able to create a user without the requirement of signing up (creating a password or signin possibility) I could create a separate model for guestaccounts, using the same information used in the user model, this would be the simplest solution but violates the dry principle. Since I inherit from "AbstractBaseUser" to create an useraccount with the email field as the unique identifier, I thought we could split the model into an "CustomAccount" model, requiring an emailadres and setting up a separate model to store all user info and set a guest_flag. We could now create an order with a guest_user, but then we could not register the guests email address or convert them to a registered user later on. On the other hand we could not create a "guest order" twice since we use the email address as a unqiue identifier, or we should not register the emailaddress for guest orders, but then we cannot inform them on order updates... Does anyone have a direction, suggestion about … -
Django - model constructor with reference to another model passed to set(with working ASP.NET example)
I'm moving project from asp.net to django. I got following simple models. Models/File.cs public partial class File { public File() { this.Sheet = new HashSet<Sheet>(); // what I need in Django. } // Model passed to set, set passed to // another model public virtual ICollection<Sheet> Sheet { get; set; } //ForeignKey } Models/Sheet.cs public partial class Sheet { public virtual File File { get; set; } //ForeignKey } My Django equivalent: models.py class File(models.Model): # @classmethod # working on a constructor here # def create(cls): # sheet = cls() # return sheet class Sheet(models.Model): data = models.ForeignKey(File, on_delete=models.CASCADE) So I need a model constructor with reference to another model wrapped in a set method. I know that I can't use __init__. Any thoughts will help. -
Connecting to external web socket api from Django
I am trying to connect to slack RTM(Real time messaging) api and update the database with the messages coming from the slack channel. How should I do that. Should I run a web-socket client in the background? If so, How to integrate the web-socket client with the Django application. Is celery, something that I should look into? I was looking into this for the past few hours. Went through a lot of questions. I am not able to figure out the right approach to do that. Any help is appreciated. -
How to convert excel file to pdf file in django
views.py: def getexcel(request): payload = json.loads(request.body.decode('utf-8')) if payload['type'] == 'excel': response = HttpResponse(content_type='text/xls') response['Content-Disposition'] = 'attachment; filename="EHR.xls"' wb = xlwt.Workbook(encoding='utf-8') #adding sheet ws = wb.add_sheet("sheet1") row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Patient Id', 'OP No', 'First name', 'Middle Name', 'Last name', 'Full Name', 'Age', 'Gender', 'Phone Number', 'Address', 'Email address', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() #get your data, from database or from a text file... patients = models.PatientMaster.objects.filter(Q(emp_dept_id=payload['department_n_key']) & Q(created_on__range=(payload['fromdate'],payload['todate']))) for patient in patients: row_num = row_num + 1 ws.write(row_num, 0, patient.patient_id, font_style) ws.write(row_num, 1, patient.op_no, font_style) ws.write(row_num, 2, patient.first_name, font_style) ws.write(row_num, 3, patient.middle_name, font_style) ws.write(row_num, 4, patient.last_name, font_style) ws.write(row_num, 5, patient.full_name, font_style) ws.write(row_num, 6, patient.age, font_style) ws.write(row_num, 7, patient.gender, font_style) ws.write(row_num, 8, patient.phone_number, font_style) ws.write(row_num, 9, patient.address, font_style) ws.write(row_num, 10, patient.email, font_style) wb.save(response) print(response) return response Here i have done code for download Excel file. Its working fine. at the same way i want to download PDF or convert excel to PDF. For PDF i have tried some code: def getpdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="file.pdf"' p = canvas.Canvas(response) p.setFont("Times-Roman", 55) p.drawString(100,700, "Hello, World.") p.showPage() p.save() return response In the … -
Python passing list of dicts to nested for loop and functions gets list indice must be integer error [on hold]
Trying to make a database population script. There are pages, with each page having a title and a URL. python_pages = [ {"title": "Official Python Tutorial", "url":"https://docs.python.org/3/tutorial/"}, #changed to py3 url #clipping part after last / from all urls (i.e. "index.html" {"title":"How to Think like a Computer Scientist", "url":"http://www.greenteapress.com/thinkpython/"}, {"title":"Learn Python in 10 Minutes", "url":"https://www.stavros.io/tutorials/python/"}, ] #url changed from book django_pages = [ {"title":"Official Django Tutorial", "url":"https://docs.djangoproject.com/en/2.1/intro/tutorial01/"}, {"title":"Django Rocks", "url":"http://djangorocks.com"}, {"title":"How to Tango with Django", "url":"http://www.tangowithdjango.com/"} ] other_pages = [ {"title":"Bottle", "url":"http://bottlepy.org/docs/dev/"}, {"title":"Flask", "url":"http://flask.pocoo.org"} ] Then there are categories of pages, with each category having the following keys and values Category:{Pages] Views:# Likes:# I would like to use one function to create each category (in django although most of this is not django-related). The original script (https://pastebin.com/Q09XJtvX) used a single dictionary for the categories, like so: cats = {"Python": {"pages": python_pages}, "Django": {"pages": django_pages}, "Other Frameworks": {"pages": other_pages} } and the following for loop and functions to make categories and pages: for cat, cat_data in cats.items(): c = add_cat(cat) for p in cat_data["pages"]: add_page(c, p["title"], p["url"]) #print check for c in Category.objects.all(): for p in Page.objects.filter(category=c): print("- {0} - {1}".format(str(c), str(p))) #bracketed numbers are placeholders for later outputs (str c … -
django.urls.exceptions.NoReverseMatch: Reverse for 'account_inactive' not found. 'account_inactive' is not a valid view function or pattern name
I am using django-rest-auth registration api, I overridden that by using my own SERIALIZER and model. So I am getting error. I have tried by setting active at the time user created. But that is not working. Let me know how to resolve this type of problem. [12/Jan/2019 17:24:06] "POST /rest-auth/registration/ HTTP/1.1" 400 68 Internal Server Error: /rest-auth/registration/ Traceback (most recent call last): File "/Users/test/project/vblah/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_auth/registration/views.py", line 46, in dispatch return super(RegisterView, self).dispatch(*args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/generics.py", line 192, in post return self.create(request, *args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_auth/registration/views.py", line 65, in create user = self.perform_create(serializer) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_auth/registration/views.py", line 81, in perform_create None) File "/Users/test/project/vblah/lib/python3.6/site-packages/allauth/account/utils.py", line 183, in complete_signup … -
Transferring Data from a Form to a django View
I have a form: class GenereteReport (forms.ModelForm): olddate = DateField (widget = forms.DateInput (attrs = {'type': 'date'})) newdate = DateField (widget = forms.DateInput (attrs = {'type': 'date'})) class Meta: model = Transactions fields = ['typeOper', 'category'] I need to select data from a database ranging from olddate to newdate class ChartData (APIView): authentication_classes = [] permission_classes = [] def get (self, request, format = None): labels = [] default_items = [] transacts = Transactions.objects.all () for transact in transacts: labels.append (transact.category.name) default_items.append (int (transact.suma)) data = { "labels": labels, "default": default_items, } return response (data) what to do instead of transacts = Transactions.objects.all () to select data in the date range that is in the form from the base link to the repository https://github.com/IvanYukish/PersonalFinanceManager -
Django Model - JOIN Tables without adding models
I have two databases to connect to for my Django App. I have only read access for one of the database, from where I want to pull only a few columns for my model into the other database where I have read and write access. It does not make sense to 'inspectdb' the read access databases with 100+ tables and the 100+ columns for just a few columns. How do I add the column from another database to my existing model in the simplest manner using a join? Can I use a raw sql query with parameters to add the field into my model? class APPNAME(models.Model): class Meta: db_table = 'APPNAME' item= models.PositiveIntegerField(db_column='Item') issue = models.CharField(max_length=200, db_column='Issue') detail = models.TextField(db_column='Detail') created_at = models.DateTimeField(auto_now_add=True, db_column='Create Datetime') updated_at = models.DateTimeField(auto_now=True, db_column='Update Datetime') external_column = How to join this column??? -
Django apps , functionalities and models
This is a pretty beginner question, as i have recently learned Django, I have these questions since i could not find a clear answer for any. Suppose that we want to build a voting system, and we have users with votes, i have a confusion with the admin user, i should create an app called users? or i should use the users default table by django? for each app i'll have a model, and for sure database-wise, for example a user will have many votes on many projects, therefore how can i connect these relationships across models in the right way? Thanks in advance -
Nginx and Django - JWT problems
I'm using Django Rest Framework to create an API. It works great when I run it locally, but when I deploy it to my server I'm having an issue with JWT. When I'm trying to POST new data, I receive an error that says: "detail": "Authentication credentials were not provided." Of course, I'm passing the Authorization header: authorization: JWT eyJ0eXAiOiJK..... On my server, I'm using nginx with the gunicorn. Here's my nginx config: upstream api { server unix:/home/bartalamej/api.sock fail_timeout=0; } server { listen 80; root /var/www/html; index index.html index.html; server_name api.mysite.cz; location /v1 { rewrite ^/v1/(.*)$ /$1 break; include proxy_params; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header REMOTE_USER $remote_user; proxy_set_header Authorization $http_authorization; proxy_set_header USE_X_FORWARDED_HOST True; proxy_pass http://api; } location /media { alias /home/bartalamej/api/media; } location /static { alias /home/bartalamej/api/static; } } Any help would be appreciated :) -
How to make REST api calls that needs auth_token?
I'm working on a Django-REST application that contains APIs that work with login mechanism. I'm able to create API endpoints for login and logouts. Login takes username, password and returns auth_token which is around 30 characters. Logout takes auth_token and destroys it. In between these login and logouts, there are few API calls that make use of auth_token. How is it generally implemented ? How are the requests made with auth_token in general? Where are those tokens stored? How do the backend validates it? Can someone please explain me how it is done basically? -
Test View in Django that requires Login session Sellenium
I would like to test a View in Django using Sellenium that has a decorator, that requires being logged in: @method_decorator(login_required, name='dispatch') This is how mu code looks like: class TestAddOrder(LiveServerTestCase): def setUp(self): self.selenium = webdriver.Firefox() super(TestAddOrder, self).setUp() def tearDown(self): self.selenium.quit() super(TestAddOrder, self).tearDown() def test_add_order(self): selenium = self.selenium selenium.get('http://127.0.0.1:8000/orders/create/') date = selenium.find_element_by_name('date').send_keys('01/31/2019') hours = selenium.find_element_by_id('id_hour').send_keys('18') submit = selenium.find_element_by_name('submit').send_keys(Keys.RETURN).send_keys(Keys.RETURN) And the error: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [name="date"] How can I keep the session of logged in user when trying to automise my test with Sellenium? -
How to retrieve and submit a form in Angular 6 that has been generated by a Django template
I have an Angular 6 app and am trying to display and submit a form that is generated from Django. I retrieve the form and display it using innerHtml. It shows up fine but when I click on the Submit button it doesn't call the function that I have attached to it. If I copy and paste the generated html then the submit button works fine (although I get a 403 response I think because of copying and pasting the CSRF token). Here is the code for my Angular component and template files and also the Django template: login.component.html <div *ngIf="!loggedIn; else successMessage" [innerHTML]="loginForm"></div> <ng-template #successMessage> Logged in </ng-template> login.component.ts import { Component, Input, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { @Input() loggedIn: boolean; id_username: string; id_password: string; loginForm: SafeHtml; constructor(private router: Router, private httpClient: HttpClient, private sanitizer: DomSanitizer) { } ngOnInit() { this.getLoginForm(); } getLoginForm() { this.httpClient.get('https://myserver/account/login/', { responseType: 'text' }).subscribe(res => { this.loginForm = this.sanitizer.bypassSecurityTrustHtml(res); console.log(this.loginForm); }); } login() { console.log("Logging in user"); var response = this.httpClient.post('https://myserver.com/account/login/', { id_username: this.id_username, id_password: this.id_password }).subscribe(res => … -
social auth app django integrity error when user is logged out
Im trying to integrate facebook login to my app. When i associate a facebook account to the user and then logout,The login with facebook is working as intended.But if the user has his facebook disconnected and when i click login with facebook,Im getting an integrity error at : IntegrityError at /oauth/complete/facebook/ duplicate key value violates unique constraint "accounts_user_email_key" DETAIL: Key (email)=() already exists. Im using social-auth-app-django -
Feature Extraction using MFCC
I want to know, how to extract the audio (x.wav) signal, feature extraction using MFCC? I know the steps of the audio feature extraction using MFCC. I want to know the fine coding in Python using the Django framework -
How to add similar posts in Detailview in Django 1.11
I want to add similar posts section to my blog django applition in Class DetailView on detail page