Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a CRUD API for django auth permission ang groups tables
I'm new to Django and i am working on an application, and i want to create a CRUD API for the Authentication permission and groups tables I do not want to add permissions in models because i don't know all the permissions and groups needed, that's why i want to give access to the user to create the permission and group he want and manage every thing by CRUD API i did not find an example to do that with Django Thanks i am using latest django version and the django rest framework -
django.db.utils.ProgrammingError: relation "web_workspace" does not exist on running tests
I am writing tests in one of my django(Django==3.1.6) projects. After writing and testing around 10 tests, today when i ran them i got an error relation "web_workspace" does not exist resulting in aborting the tests. However, on running the project i.e python manage.py runserver my project runs flawlessly. Here is a screenshot with complete traceback i am getting on running tests I have stripped all the test cases and kept only one just to keep things minimal for this question, and i am still getting this error. Here is the test code for API i am using. from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase def confirm_success_response(self, response, expected_response, match_values=False): self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIsInstance(response.data, dict) self.assertEqual(set(response.data.keys()), set(expected_response.keys())) if match_values: self.assertEqual(response.data, expected_response) class APItests(APITestCase): # pre and post test methods def setUp(self): pass def tearDown(self): pass # methods for tests internal use # Actual API test methods def test_dummy_api(self): url = reverse('test') response = self.client.get(url, None, format='json') expected_response = {'success':True, 'message': "Api passed test"} confirm_success_response(self, response, expected_response, True) Things i have already tried but didn't work: Delete migrations directory and recreating migrations and migrating them. Running app specific migrations as python manage.py makemigrations <app_name> and then migrating … -
Django social auth collect githb data and save into a database
Currently i am using social-auth-app-django to create an interface for users to login and I wish to collect their data in the back end. I've already managed to do the authorization but i cannot access their data. I wish to: Disable the default of saving user info into the auth_user table, as i only wish to store their github information, I don't need any other functionality. Fetch the user's github access token and request their github information via github's API inside the home views function, and save it into another database i created (not auth_user). settings.py AUTHENTICATION_BACKENDS = ( 'social_core.backends.github.GithubOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GITHUB_KEY = 'XXXXXXXXXXXXXXXX' SOCIAL_AUTH_GITHUB_SECRET = 'XXXXXXXXXXXXX' SOCIAL_AUTH_GITHUB_SCOPE = [ "read:user" ] LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = 'home' core's urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("", include('mystats.urls')), path('oauth/', include('social_django.urls', namespace='social')) ] app's urls.py from django.urls import path from . import views urlpatterns = [ path("myoauth/", views.myoauth, name="myoauth"), path("", views.home, name="home") ] app's views.py from django.shortcuts import render def myoauth(request): return render(request, 'app/myoauth.html') def home(request): ################################################ # I want to do something here # access the github access token of a user and use the Github API to … -
Make it so url can only be accessed through redirect
I am redirecting my users from a paypal payment to the register.html so that you can only register once you have paid the subscription. How do I make it so that this redirect is the only way to access the page and not simply by putting mysite.com/register in the browser? I have pages where login is required but obviously this will be before a user has registered so cannot do that. -
Add option to change columns and data dynamically in Django Admin changelist_view
Is it possible to change the columns displayed in a models's admin changelist_view page dynamically? For example: Include a toggle button that depending on its state will change the order of the columns displayed or even display new columns (with new headers) that are already part of the model. Or even maybe add a new column that has operations performed with the model object? More practical example: I have a Region model and within the region I have a Sale related model of all the sales performed in that region. So in the Region changelist_view, if I toggle the button I will display the total sum of the sales per region or, if I untoggle the button, I will display the percentage in relation to the total. -
Wagtail - Expand Orderable / InlinePanel functionality
What I am trying to do is attempted before in different forms: Add Taxonomy to Wagtail, a feature present in most other popular CMSs (Drupal as "Taxonomy", Craft as "Categories, ...). I know Wagtail has some type of implementation called "Collections" but it is not as fully fledged as other implementations and its interface does not cater to large trees. My approach: Build upon Orderable models, as they already give us a nice way to order child items related to an other model (think Menu -> MenuItems). Together with InlinePanel, Orderables give you a nice interface to manage your main Taxonomy name and all of its "nodes". Yet, an Orderable is one-dimensional, it only goes up or down via a sort_order column on the Orderable model. My idea is to provide a second dimension, to go left or right, with a parent column. A super simple data model: class NestedOrderable(Orderable): parent = models.IntegerField(null=True, blank=True, editable=False) class Meta: abstract = True ordering = ['parent', 'sort_order'] Now in the InlinePanel, the sort order gets inserted as a hidden field on each child item. I am trying to now find a way to get this parent attribute to be included into the HTML … -
IntegrityError at /images/create/ NOT NULL constraint failed: images_image.users_like_id
I'm working on a project from the book 'Django3 by example'. I want to add an image from the URL which the user provided. But when I try to save the page it gives me this error: IntegrityError at /images/create/ NOT NULL constraint failed: images_image.users_like_id. I have tried the solutions other posted but it didn't help. Here is my code: models.py from django.db import models from django.conf import settings from django.utils.text import slugify class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='images_created') users_like = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='images_liked') title = models.CharField(max_length=100) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='images/%Y/%m/%d/') description = models.TextField() created = models.DateField(auto_now_add=True, db_index=True) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args, **kwargs) views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import ImageCreateForm @login_required def image_create(request): if request.method == "POST": form = ImageCreateForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) new_item.user = request.user new_item.save() messages.success(request, 'Image added successfully') return redirect(new_item.get_absolute_url()) else: form = ImageCreateForm(data=request.GET) context = {'section':'images', 'form':form} return render(request, 'images/image/create.html', context) forms.py from django import forms from urllib import request from django.core.files.base import ContentFile from django.utils.text import slugify from .models import Image … -
Two django forms result in empty boto3 upload
When using two forms in one template / view, I am getting an empty file uploaded to S3. Removing one of the forms, results in an upload with more than 0 bytes. Example for working view: def test(request): file_form = UploadFilesForm() if request.method == 'POST': file_form = UploadFilesForm(request.POST, request.FILES) file = request.FILES['file'] s3_client = boto3.client('s3', region_name=settings.AWS_ZONE, aws_access_key_id=settings.AWS_KEY, aws_secret_access_key=settings.AWS_SECRET) response = s3_client.upload_fileobj(file, '', bucket'test2.pdf') return HttpResponse('uploaded') return render(request, 'upload.html', {'fileform': file_form}) Not working view: def index(request, company, key): context = { 'company': 'Sample Co.', } if request.method == 'POST': form = CaseForm(request.POST) file_form = UploadFilesForm(request.POST, request.FILES) if form.is_valid(): case = form.save() if file_form.is_valid(): file_form = file_form.save(commit=False) if 'file' in request.FILES: file = request.FILES['file'] if file: file_type = file.content_type extension = file.name.split(".")[-1] s3_client = boto3.client('s3', region_name=settings.AWS_ZONE, aws_access_key_id=settings.AWS_KEY, aws_secret_access_key=settings.AWS_SECRET) response = s3_client.upload_fileobj(file, 'bucket', 'test2.pdf') file_form.filename = filename file_form.case = case file_form.save() return redirect('confirmation') else: form = CaseForm() file_form = UploadFilesForm() return render(request, 'upload.html', {'form': form, 'fileform': file_form, 'context': context}) The file object is definitely there, as I can print(file.file), print(file.read())... Even size is shown correctly. It is just not uploading the bytes to S3. -
Remove add button in Django admin Many-to-many field
How can I remove add button in Many-to-many field selection from Django admin? See this screen Thank you. -
Only show the posts which are published before now ( Scheduling BlogPosts to post in future)
I am building a BlogApp and I am building a Feature that Users can schedule posts to post at the time user is selected. I do it with the help of Timezone. What am i doing I filtering posts which are published before now AND i am Not showing the posts that's time is settled up to post in future. It means when the user is selected time for the Future in DateTimeField in Create BlogPost section then the post is posted but not showing in BlogPosts list. It will be seen or post at the time which is set up by User. The Problem When i filter BlogPosts to show the all BlogPosts which are published now and before, then they are not showing in Page. models.py class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') date_added = models.DateTimeField(auto_now_add=True,null=True) views.py def posts(request,user_id): now = timezone.now() posts = BlogPost.objects.filter(date_added=now) context = {'posts':posts} return render(request, 'posts.html', context} posts.html {% for post in posts %} {{ post.post_title }} {{ post.post_owner }} {% endfor %} I don't know what am i doing wrong. Any help would be appreciated. Thank You in Advance. -
python Django reportlab can't find msyh.ttf file
When I use from reportlab.pdfbase import pdfmetrics pdfmetrics.registerFont(TTFont('msyh', 'msyh.ttf')) I meet a bug that is reportlab.pdfbase.ttfonts.TTFError: Can't open file "msyh.ttf" However, if I download the msyh.ttf file and use an absolute path like pdfmetrics.registerFont(TTFont('msyh', r'C:\Users\xxx\xxx\xxx\xxx\msyh.ttf')) It works. How could I fix this bug ? -
datetime filed shwo me charfield only django
i'm trying to show a date time Field like in the admin page or any other representation for the datetime Field but it did not work i try few thnigs, but nothing work this is my model.py file class Listing(models.Model): creator = models.ForeignKey(User, on_delete=models.PROTECT, related_name="all_creators_listings") title = models.CharField(max_length=60) description = models.CharField(null=True, max_length=500) startingBid = models.FloatField() min_adding_bid = models.FloatField() # adding the min adding bid and add this to the condution flActive = models.BooleanField(default=True) currentBid = models.FloatField(blank=True,null=True) created_date = models.DateTimeField(default=timezone.now) close_date = models.DateTimeField(null=True) # adding the end of the listing blank=True, null=True category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE ,related_name="similar_listings") watchers = models.ManyToManyField(User, blank=True, related_name="watched_listings") buyer = models.ForeignKey(User, null=True, on_delete=models.PROTECT) def __str__(self): return f"{self.title} - {self.startingBid} - {self.currentBid}" def save(self, *args, **kwargs): if not self.close_date: raise ValidationError("close date missing!! Please add the the closing dateand time") if not self.close_date > self.created_date: raise ValidationError("the closing date must be grater than the current date") and this is my forms file class newListingForm(forms.ModelForm, forms.DateTimeField): """Form definition fos New_listing_.""" class Meta: """Meta definition fos New_listing_form.""" # close_date = forms.DateTimeField(initial=timezone.now) ----> not working # close_date = forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) ----> not working # def __init__(self, *args, **kwargs): # super(newListingForm, self).__init__(*args, **kwargs) # self.fields['close_date'] = forms.DateTimeField(input_formats=['%Y-%m-%d %H:%M'],widget=XDSoftDateTimePickerInput(attrs={'minDate':time.date(),'allowTimes':'12:00','class':'cal'}),label='Окончание аренды') # … -
How can I show all users I follow?
I have models: Profile mode class Profile(AbstractUser): following = models.ManyToManyField("self", through=UserFollowing, related_name="followers", verbose_name=_("following"), symmetrical=False) And UserFollowing model class UserFollowing(models.Model): following_from = models.ForeignKey("Profile", related_name="following_from", on_delete=models.CASCADE, verbose_name=_("Following from")) follow_to = models.ForeignKey("Profile", related_name="follow_to", on_delete=models.CASCADE, verbose_name=_("Following to")) created = models.DateTimeField(auto_now_add=True, db_index=True) How can I show all profiles I follow? How Can I setup query set to show al followers and followed Profiles? Profile.objects.filter... ? -
how can i order items based on a method
i wanna know how can i order a listView using a method , like here i wanna order my posts based on numbers of likes , i am using class based views ... here is my code models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) # content = models.TextField() content = RichTextField(blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) post_image = models.ImageField(upload_to='post/cover') category = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() likes = models.ManyToManyField(User, related_name='blogpost_like') def __str__(self): return self.title def get_absolute_url(self): return reverse("core:detail", kwargs={ 'slug': self.slug }) def delete(self, *args, **kwargs): self.post_image.delete() super().delete(*args, **kwargs) @property def comment_numbers(self): return Comment.objects.filter(post=self).count() def number_of_likes(self): return self.likes.count() views.py class PostListView(ListView): model = Post template_name = 'home.html' context_object_name = 'posts' paginate_by = 6 ordering = ['-date_created'] -
Getting items related to selected foreign key in django
I'm building a django app that has customers model and projects model and tasks model. in tasks model I can select the customer name and project but the problem is that in admin panel it shows all the projects, is there any way to show projects only for the selected customer from django.db import models from django.contrib.auth.models import User from suppliers.models import Currency from users.models import Profile class Customer(models.Model): customer_id = models.AutoField(primary_key=True) customer_first_name = models.CharField(max_length=200) customer_last_name = models.CharField(max_length=200) company = models.CharField(max_length=200) customer_phone = models.CharField(max_length=200) customer_address = models.CharField(max_length=200) email = models.EmailField(null=True, blank=True) website = models.CharField(max_length=200, null=True, blank=True) creation_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) notes = models.TextField() def __str__(self): return str(self.customer_first_name) + ' ' + str(self.customer_last_name) class Account(models.Model): max_discount = models.DecimalField(max_digits=2, decimal_places=2) credit_limit = models.DecimalField(max_digits=20, decimal_places=2) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) sales_man = models.OneToOneField(User, on_delete=models.CASCADE) Agent = models.OneToOneField(Profile, on_delete=models.CASCADE) status = models.BooleanField(default=True) reason = models.TextField() class TaskPriority(models.Model): priority_id = models.AutoField(primary_key=True) task_priority_name = models.CharField(max_length=200) def __str__(self): return str(self.task_priority_name) class Project(models.Model): project_id = models.AutoField(primary_key=True) project_name = models.CharField(max_length=200) project_balance = models.DecimalField(max_digits=20, decimal_places=2) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) notes = models.TextField() def __str__(self): return str(self.project_name) class Task(models.Model): task_id = models.AutoField(primary_key=True) task_name = models.CharField(max_length=200) customer_name = models.ForeignKey(Customer, … -
Find best candidates in efficient way, Django
I'm beginner in django and python. I have models : class Employee(models.Model): full_name = models.CharField(max_length = 64) title = models.CharField(max_length = 64) def __str__(self): return f"{self.full_name} ( {self.title} )" class Skill(models.Model): name = models.CharField(max_length = 64) def __str__(self): return f"{self.name}" class Candidate(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name="employee") skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name="skill") def __str__(self): return f"{self.id}: {self.employee} knows - {self.skill}" class Job(models.Model): title = models.CharField(max_length = 64) skills = models.ManyToManyField(Skill, blank=True, related_name="Jobs") def __str__(self): return f"{self.title}" In views.py, i have 'finder' function : def finder(job_id): job = Job.objects.get(id=job_id) # get the specific job relevant_candidates = [] # all the relevant candidates of this kob common = [] # number of common skills between the employee_skill and the relevant_employees_by_title = Employee.objects.filter(title = job.title) # first filter the candidates by the job title job_skills = [] for skill in job.skills.all(): print(skill.id) job_skills.append(skill.id) for employee in relevant_employees_by_title: employee_skills =[] candidateCorrect = Candidate.objects.filter(employee__id = employee.id).values_list('skill', flat=True) for skill in candidateCorrect: employee_skills.append(skill) common_skills = list(set(job_skills) & set(employee_skills)) if (len(common_skills)>0): #if there are common skills relevant_candidates.append(employee) common.append(len(common_skills)) candidates = zip(relevant_candidates,common) candidates = sorted(candidates,key = lambda t: t[1], reverse = True) # sort the candidates by the number of common skiils , descending order candidates = candidates[:50] … -
Django app with offline mode: store datas both in remote and local postgresql database?
I have a problem quite similar with this post but was thinking for an easiest implementation My Django app is deployed on a remote server with Postgresql database (main central remote database). Users online: data are stored both in the remote database and, if possible, in a local postgresql database (local database hosted on a dedicated laptop) Users offline (when server where app is hosted is down): 'central' user need to be able to use Django web app on the dedicated laptop (with PWA) with the most up-to-date local database When back online, the remote database is synchronized Django can use multiple databases. But is my solution possible? I have read for Django sync and collect-offline apps... thanks for advices -
Nested if statment, json, django
My code which is working: def json_response(self, request): ... return JsonResponse({ 'Name': 'Harry' if name.pretty else name.something I want to add nested if statment but i dont know how. It should be something like: 'Name': Harry if name.pretty else name.something(if exists) otherwise name.something_else -
no mail default in form
I am using a form django and I want values that are already defined in my model. But the default value for mail is not showing up in the form. Why? forms.py class ForeningForm(ModelForm): class Meta: model = Forening exclude = ['ordf','kass','adress'] fields=['fname','fphone','mail','homepage','direktansk','anslutenannat',\ 'anteckningar','uppdaterad'] model.py: class Forening(Model): fname=CharField(default='missing',max_length=100) ordf=OneToOneField(Person,on_delete=CASCADE,related_name='ordf') kass=OneToOneField(Person,on_delete=CASCADE,related_name='ka') fphone=PhoneField(default='9999999999') adress=OneToOneField(Adress,on_delete=CASCADE,related_name='ad') mail=EmailField(default='missing@gmail.com') homepage=TextField(max_length=400,default='www.homepage.com') direktansk=BooleanField(default=False) anslutenannat=BooleanField(default=False) anteckningar=TextField(max_length=500,default='missing') uppdaterad=DateTimeField(default=timezone.now) def __str__(self): return 'förening: ' + self.fname class Meta: ordering=('fname','ordf') views.py: class Fcreate(CreateView): form_class=ForeningForm template_name='kammem/create.html' def form_valid(self,form) fname=form.cleaned_data['fname'] venue=form.cleaned_data['venue'] fphone=form.cleaned_data['fphone'] mail=form.cleaned_data['mail'] homepage=form.cleaned_data['homepage'] direktansk=form.cleaned_data['direktansk'] anslutenannat=form.cleaned_data['anslutenannat'] antekningar=form.cleaned_data['antekningar'] uppdaterad=form.cleaned_data['uppdaterad'] -
Halted output from Django until application exit
When i start my Django app I expect it to print me some nice welcomming messages for what host and port I can use to access the website/rest... I do not. I get an output: "My app Stared message from apps.App.ready()" Watching for file changes with StatReloader This is all the text I see until i press CTRL+C Then I see the full log. Using proactor: IocpProactor Performing system checks... System check identified no issues (0 silenced). February 18, 2021 - 13:00:06 Django version 3.1.6, using settings 'project_name.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Using proactor: IocpProactor Why do I not see the logs that was posted hew minutes before the CTRL-BREAK message? Following guides on how to setup your Django project they show that information stright away. -
Django app(with PostgreSQL) monthly price at Google App engine
How much will it cost monthly to deploy simple Django app with PostgreSQL db at Google App Engine? -
Django Request Returns JSON as 'str' instead of 'dict'
I'm working on a Django app that should receive a request from a payment API, instead of the API returning the JSON as 'dict' it returns a string, this makes it hard to use the response as a variable, below is the response and the code. Any help would be appreciated. request.body returns { "Body":{ "stkCallback":{ "MerchantRequestID":"31704-1162534-1", "CheckoutRequestID":"ws_CO_170220211453010899", "ResultCode":0, "ResultDesc":"The service request is processed successfully.", "CallbackMetadata":{ "Item":[ { "Name":"Amount", "Value":1.00 }, { "Name":"MpesaReceiptNumber", "Value":"" }, { "Name":"TransactionDate", "Value":20210217145321 }, { "Name":"PhoneNumber", "Value": } ] } } } } The view def callback(request): callback = json.dumps(request.body.decode('utf-8')) body_data = json.loads(callback) print(body_data) # returns 'str' instead of 'dict' return render(request, 'callback.html') -
Dialogflow front end and database through django and python
I'm currently trying to integrate my dialogflow agent onto a front end website through django and python, whilst trying to store the chat history into mongoDB/firebase so that at the end of the chat, users will have the option to download the whole chat session. However, all implementations seem to need to use google cloud sql , which needs a billing account. Will it need to be implemented through a webhook? This is a project for university hence my team and I are relatively new and clueless on how to do it for free, any help will be appreciated. -
How to push the notification on web browser using django
I create a Todo web application in Django and i deploy it on Heroku. I want to know how can i push the notification in my browser for upcoming task.Thanks in advance. -
Submit form from Paypal script after approved payment in Django
I have a user registration form and I would like the user to pay in order to register for my app. I have the frontend paypal set up for the payment as well as the user registration with a submit button but I do not know how to integrate the two. <div id="paypal-button-container"></div> <script src="https://www.paypal.com/sdk/js?client-id=sb&currency=USD"></script> <script> // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '00.01' } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { // Show a success message to the buyer alert('Transaction completed by ' + details.payer.name.given_name + '!'); }); } }).render('#paypal-button-container'); </script> <button class="w3-button w3-blue w3-padding-large" type="submit"> Buy Now </button> </form> I would like the submit button to be used in the 'onapprove' part of the script but I am not sure how. Alternatively I was thinking of calling my 'buy' function from the views def buy(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): data = form.cleaned_data email = f"{data['email']}" username = f"{data['username']}" form.instance.username = username form.save() return redirect('login') else: form = UserRegisterForm() return render(request, 'users/buy.html', {'form': form}) The other thing is that the …