Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError while running a unit test in Django
I am inheriting an existing project and since I want to implement unit testing for the future modules, I have tried to run a very simple test like: class CalcTests(TestCase): def test_add_numbers(self): """ Test that two numbers are added together """ self.assertEqual(add(3, 8), 11) However, it shows the Import Error ImportError: cannot import name 'ConfigSerializer' from partially initialized module 'api.serializers' (most likely due to a circular import) (/Users/nick/work/shiftwork_backend/api/serializers/__init__.py) so I looked at the init.py in the serializers file and it looked like this: from .default import * from .backup import * from what I understood, it's a not-so-good practice to use asterisks so instead, I imported all the serializer classes manually by naming every single one of them. However, I still get the same error. If you want a better reference, below is the whole error message: ====================================================================== ERROR: api.serializers (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: api.serializers Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/Users/nick/work/shiftwork_backend/api/serializers/__init__.py", line 1, in <module> from .default import * File "/Users/nick/work/shiftwork_backend/api/serializers/default.py", line 10, in <module> from api import views File "/Users/nick/work/shiftwork_backend/api/views/__init__.py", line 1, in <module> from .base import * … -
"<Order: Order None>" needs to have a value for field "id" before this many-to-many relationship can be used
I am trying to fix an error related to my e-commerce project to show the context in Admin through PDF.html so I am trying to fix it but I got this error and I don't know how to solve it. "<Order: Order None>" needs to have a value for field "id" before this many-to-many relationship can be used. here is the views.py @staff_member_required def admin_order_pdf(request, order_id): html = render_to_string('pdf.html', {'order': Order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) class Order(models.Model): items = models.ManyToManyField(OrderItem) here is the url path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') -
my images are appearing as a broken file in django
im trying to build a webdite that allows the users to post product image and description for products they want to sell. but i am getting a broken image thumpnail. this is my settings.py file """ Django settings for mum project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'tbe4^5o02%t@$e4n551llb@_5d_!l+8j2+je_a5gl6610zmfu)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'products.apps.ProductsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'mum.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mum.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } … -
Azure Active Directory Authentication from Django-REST-Framework and ReactJS App
Seems like something pretty basic to implement, but I've been struggling for several days with it now. Trust me, I've asked enough questions here and on GitHub developer repos regarding it. Essentially: User navigates to domain.com/admin This URI is for internal company users only Thus, the user needs to be verified against the organizations Azure AD If they are a user, it takes them to the dashboard; If not, they are rejected from entering Simple, right? I'm finding not so much. I've been trying to do it server-side with DRF. Mind you, my Django backend, does not serve any static assets. It is strictly and API that consumes and provides data. It at no point uses Django Templates. I'm finding most of the libraries are out dated, have poorly written documentation, or just don't work for my use case (DRF). I've tried a handful and can't get any of them working. The ones I've tried: python-social-auth python-social-auth-django drf-social-oauth2 django-rest-framework-social-oauth2 I understand that this can also be done client-side with ReactJS libraries and supposedly it is secure. I haven't tried yet. I have no preference for either server-side or client-side just as long as user's information can be put in the … -
Django Annotate - Can I used the fields created in annotate for another field created in annotate?
I am calculating the sum of scores by dept and the number of users in each department in annotate like this: queryset = Depts.objects.annotate(total_pts=Sum('userprofiles__user__activity_user__activity_category__pts'), total_users=Count('userprofiles', distinct=True)).order_by('-total_pts') I also want to send back as part of the return data avg_score = total_pts / total_users. Is there a way to add this into the annotate, or chain them together, or otherwise add this to the return queryset? Thank you. -
Postgres db FATAL: password authentication failed for user
I need help. So I am hitting a wall and have been looking around for solutions but nothing seems to be working for me. I am trying to get the backend to connect to the DB but it keeps returning the error below: django.db.utils.OperationalError: FATAL: password authentication failed for user "app". If I try changing the db_host to localhost or 127.0.0.1 it just throws back an error saying it can't find anything on port 5432. but unless I'm missing something the user and password match and have been added in the correct locations. I would appreciate any help that can be offered. I've tried wiping the containers and images and restarting and nothing seems to be working. does anyone have ideas as to what the issue may be? error Traceback (most recent call last): api_1 | File "manage.py", line 10, in <module> api_1 | execute_from_command_line(sys.argv) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line api_1 | utility.execute() api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute api_1 | self.fetch_command(subcommand).run_from_argv(self.argv) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv api_1 | self.execute(*args, **cmd_options) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute api_1 | output = self.handle(*args, **options) api_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 83, in … -
Django+Axios: Multiple Files upload (foreignkeys) [READ FIRST]
Greeting! (feel free to edit this post, i am exhausted ...) I have a form in ReactJs that allows multiple files upload for a single post. ISSUE i can't save these files(images) when they hit Django ( django setup is good, the issue is coming from axios). Code Sample updatePost = (data) => { let formData; const hasFile = Boolean(data.images.length); if (hasFile) { formData = new FormData(document.getElementById('postForm')) // for (let dataKey in data) { // if (dataKey === 'details') { // formData.append("details", [...data["details"]]); // } // else if (dataKey === 'images') { // formData.append("images", [...data["images"]]); // } // else { // formData.append(dataKey, data[dataKey]); // } // } for (let val of formData.entries()) { console.log(val[0] + ', ' + val[1]); } } else { formData = data; } if (!Boolean(data.id)) { return this.createPost(formData, this.axiosConfig({ 'hasFile': hasFile })) }; return axios.put( `${data.path}`, formData, this.axiosConfig({ 'hasFile': hasFile }) ); } axiosConfig = (param = {}) => ({ headers: { 'Authorization': `Token ${this.fetchToken()}`, 'content-type': param.hasFile ? 'multipart/form-data' : 'application/json' } }) return of console.log(...) name, sfdfsd Service.js:57 description, Et animi inventore et. Placeat sit laudantium voluptas et nihil architecto nemo aperiam. Adipisci voluptatem accusamus atque molestias qui. Service.js:57 category, 7 Service.js:57 subcategory, 39 Service.js:57 … -
How to set a table to UTF-8 in Django?
I am trying to update 2 tables with the SQL command like so: ALTER TABLE sessions MODIFY username VARCHAR(50) CHARACTER SET utf8; ALTER TABLE users MODIFY username VARCHAR(50) CHARACTER SET utf8; However, I need to do this in Django. Is there a way to set these table columns to utf8 through Django and then apply to the database via migration? -
I am trying to consume a method that I have in django but it generates an error of is not JSON serializable
@action(detail=False, methods=['post']) ## etiqueta que define el metodo def generateGuia(self, request): contrasenaEncriptada = 'contra' client = Client('url/soap') header_value = header arrayGuias = [ '' ] envios2 = [{ 'box':{ 'objEnvios': [{ 'EnviosExterno': { 'idePaisDestino': 1 . . . 'objEnviosUnidadEmpaqueCargue': { 'EnviosUnidadEmpaqueCargue':{ . . . } } } }] } }] data3 = client.service.CargueMasivoExterno(envios = envios2, arrayGuias = arrayGuias, _soapheaders=[header_value]) print(data3) ## respuesta sin necesidad de serializer return response.Response({ 'token': data3 }) response : Object of type boxResponse is not JSON serializable -
Physical printing with printer
Is there a framework that Django has (or is compatible with) that can print stuff from its web-based app to physical printers that are connected to the client side. Let's assume one printer per client, and the more simple case: the printing is triggered by human user doing something in the app (though if possible, automatic printing would be cool) . I found an old post with a suggestion here but I don't quite understand it (particularly the manual settings of the browser (Notes, Firefox, Chrome, how and where is this done, what programming language are those code lines written in?). The post also mentioned "connect the printer to the server"? If the app is hosted on a server such as Heroku, or Amazon, etc., how is this possible? -
changing cart items quantity in shopping cart using vanilla javascript
I am building an eCommerce website with Django and I am trying to change the quantity items in my shopping cart using pure javascript. I have been able to select and click on the increase and decrease buttons using a query selector but when I click on any of those buttons only the first item in the cart updates the remaining buttons do not increase the quantity of the items associated with it what should I do? This is the javascript code var minusButton = document.getElementsByClassName("btn minus1") for (var i = 0; i < minusButton.length; i++) { minusButton[i].addEventListener("click", function(event){ var quantity = document.getElementsByClassName("cart-quantity-input") for (var i = 0; i < quantity.length; i++) { var quantity = quantity[i].value-- //console.log(quantity) } })} this is the HTML code <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cart</title> <link rel="stylesheet" type="text/css" href="{% static 'css/cart.css' %}"> </head> <body> <!-- navigation menu --> {% include "topnav.html" %} <div class="maincontent"> <h1 class="hhh1" style="font-size:50px; margin:0px; margin-bottom:30px">Your Cart</h1> <div class="centerblock"> <!-- DYNAMIC CONTENT GOES HERE --> <div class="cart-row"> <span class="cart-item cart-header cart-column">ITEM</span> <span class="cart-price cart-header cart-column">PRICE</span> <span class="cart-quantity cart-header cart-column">QUANTITY</span> </div> <div class="cart-items"> {% for item in items %} <div> <div class="cart-item cart-column"> <img class="cart-item-image" src="{{item.product.imageURL}}" width="100" … -
How to solve 403 forbidden error in django?
Well I am trying delete comment. only the author of comment can delete the comment or remove the comment but on every comment it showing me 403 forbidden. and not removing the comment. views.py def comment_remove(self,request,pk): comment = self.get_object() if self.request.user == comment.author.user: comment = get_object_or_404(Comment,pk=pk) post_pk = comment.post.pk comment.delete() return redirect('posts:post_detail',pk=post_pk) urls.py app_name = 'posts' urlpatterns = [ path('<int:pk>/remove/',views.comment_remove,name='comment_remove'), ] If more detail is require than tell me. I will update my question with that information. -
websocket failed with 'Invalid frame header'
I created a simple chat app and deployed it to AWS EC2. I built the frontend with Vue.js and use javascript's WebSocket. In the backend, I used Django, channels, and Postgres. It works fine on local but WebSocket is disconnected after some time on the server. I used Nginx for deployment. I also set proxy_read_timeout to 600s for the Nginx WebSocket configuration. this.chatSocket = new WebSocket(GlobalConstants.WEBSOCKET_URL + '/ws/chat/' + id + '/') this.chatSocket.onmessage = (m) => { let data = JSON.parse(m.data) let messageData = {} messageData[data.type] = data.message let message = { author: data.sender == this.currentUser ? 'me' : data.sender, type: data.type, data: messageData } this.receiveMessage(message) if (data.sender != this.currentUser) { this.addParticipant(data.sender) } } This is nginx configuration. server { listen 80; server_name x.x.x.x; location / { proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; proxy_pass "http://127.0.0.1:8000"; } location /ws/ { proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_read_timeout 600s; } } Please help me. -
Django login using social account with custom adapter
I am trying to implementing logging in with Google on my django app. However, if a user with the same email as my google account exists it prompts me to a signup page, I would like to create an adapter that if user exists with the social account email, it will show a message that user exists, and if it does exists but it is inactive, it will remove it and login the new user instead. So far I have implemented this: class SocialAccountAdapter(DefaultSocialAccountAdapter): def clean_email(self, email): if Profile.objects.filter(email=email).exists(): if Profile.objects.filter(email=email, is_active=False).exists(): p = Profile.objects.filter(email=email, is_active=False).delete() elif Profile.objects.filter(email=email, is_active=True).exists(): raise forms.ValidationError("A user with this email already exists.") return email def clean_username(self, username): if Profile.objects.filter(username=username).exists(): if Profile.objects.filter(username=username, is_active=False).exists(): p = Profile.objects.filter(username=username, is_active=False).delete() elif Profile.objects.filter(username=username, is_active=True).exists(): raise forms.ValidationError("A user with this username already exists.") return username My intention is that if a user for instance with a gmail is logged in and tries to login but an inactive user with their gmail already exists it will remove the inactive user and login the new user instead. -
Django Sum in Annotate
Good afternoon, I am really struggling with getting a sum using Annotate in DJango. I am using User object and the following models: class Depts(models.Model): dept_name = models.CharField(max_length=55) dept_description = models.CharField(max_length=255) isBranch = models.BooleanField(default=False) def __str__(self): return "{}".format(self.dept_name) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') title = models.CharField(max_length=75) dept = models.ForeignKey(Depts, on_delete=models.CASCADE, related_name="dept", null=True) class ActivityLog(models.Model): activity_datetime = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='activity_user') activity_category = models.ForeignKey(ActivityCategory, on_delete=models.CASCADE, null=True, related_name='activity_cat') activity_description = models.CharField(max_length=100, default="Misc Activity") class ActivityCategory(models.Model): activity_name = models.CharField(max_length=40) activity_description = models.CharField(max_length=150) pts = models.IntegerField() def __str__(self): return '%s' % (self.activity_name) What I need to do is get a group of departments with aggregating the sum of the pts earned by all the users activitylogs. So a user is part of department, they do activities, each activity is of a type activity_category and has associated points. How can I query using the ORM to get a sum of points for everyone in each department? Thank you, I cannot seem to wrap my mind around it. -
Django Compare Foreign Key Value to Attribute of another Model
I'm still relatively new to Django, but I decided to try to build a personal portfolio of personal projects I've worked on. I've set it up so that you land on the home page. From there, you can click on a language. Then if I've used a framework for that language, I want to display it to the screen or if I have a project I did not using a framework in that language, it would be displayed here as well. To do this, I've set up a foreign key from frameworks to languages and from JobNoFramework to Language. I have put in a framework object for Django to test it. If I change the comparison operator to !=, it displays, but as soon as I make it == it doesn't work, even though if I say {{frameworks.language}} - {{languages.language}} I get Python - Python. I'd really appreciate any help. Here's the relevant code: Models: from django.db import models from datetime import date # Create your models here. class Language(models.Model): language = models.CharField(max_length = 30) image = models.ImageField(upload_to='images/') def __str__(self): return self.language class Framework(models.Model): framework = models.CharField(max_length = 30) language = models.ForeignKey(Language, on_delete=models.CASCADE) def __str__(self): return self.framework class JobNoFramework(models.Model): job … -
Make User Profile Visible to All Users Include AnonyMouseUser() on Django
I'm trying to create UserProfileView with user's username in the url. Actually, it works somehow with the actual settings. The issue is, any username extension in the url redirects to the logged in user's profile. And, no info comes to the template when I try to go to profile without signing in. Here's my code, any help is appreciated. models.py class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) email = models.EmailField(max_length=150) bio = models.TextField(max_length=280, blank=True) avatar = models.ImageField(default='default.jpg', upload_to='avatars/') def __str__(self): return '@{}'.format(self.user.username) def save(self): super().save() img = Image.open(self.avatar.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size, Image.BICUBIC) img.save(self.avatar.path) views.py class UserProfileView(SelectRelatedMixin, TemplateView): model = Profile template_name = 'accounts/profile.html' select_related = ('user',) def get_context_data(self, *args): context = super().get_context_data(*args) profile = Profile.objects.filter(user=self.kwargs) context['profile'] = profile return context def get_success_url(self): return reverse('accounts:profile', kwargs={'username': self.object.user.user.username}) urls.py urlpatterns = [ path('<str:username>/', views.UserProfileView.as_view(), name='profile') ] profile.html (how I call the related data in the template) <h3>{{ user.profile }}</h3> <p>{{ user.profile.email }}</p> <p>{{ user.profile.bio }}</p> <h3>{{ profile }}</h3> -
writing data from parent model to another database with django routers
I have models, for example ParentModel and ChildModel where ParentModel is a parent to a child model and those models belong to different apps, for example pm_app and c_app: #pm_app class ParentModel(model.Model): #some fields #c_app class ChildModel(ParentModel): #some other fields and I have django routers in my project. class ParentModel: def db_for_write(self, model, **hints): # some options return 'default' class ChildModel: def db_for_write(self, model, **hints): # some options return 'other_db' When ChildModel is filled with some data so does the ParentModel, but router doesn't work at that moment, default db stays empty, the entry appears in the 'other_db'. So is there a way to resolve this issue? I didn't add the code from the actual project, because I think it is unnecessarily complicated. -
Defining custom signup for django-allauth
I have been trying to user a custom signup form in django-allauth. However, I get the error: django.core.exceptions.ImproperlyConfigured: Module "main.forms" does not define a "SocialAccountSignupForm" class Below is my custom social account form: from allauth.account.forms import SignupForm class SocialAccountSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(SocialAccountSignupForm, self).__init__(*args, **kwargs) def clean(self): email = self.cleaned_data.get("email") username = self.cleaned_data.get("username") if Profile.objects.filter(email=email).exists(): if Profile.objects.filter(email=email, is_active=False).exists(): p = Profile.objects.filter(email=email, is_active=False).delete() elif Profile.objects.filter(email=email, is_active=True).exists(): raise forms.ValidationError("A user with this email already exists.") if Profile.objects.filter(username=username).exists(): if Profile.objects.filter(username=username, is_active=False).exists(): p = Profile.objects.filter(username=username, is_active=False).delete() elif Profile.objects.filter(username=username, is_active=True).exists(): raise forms.ValidationError("A user with this username already exists.") super(SocialAccountSignupForm, self).clean() return self.cleaned_data And in my settings file I have: ACCOUNT_SIGNUP_FORM_CLASS = 'main.forms.SocialAccountSignupForm' I do not understand why this is causing me this error as the class is inside my main/forms.py file. -
Django POST save and delete
I'm attempting to save records into a model using the modelform (this part is working as intended) and delete records from the same model using a checkbox (can't figure this piece out). I am creating a comprehensive view so I'm not creating using a def variable(reqeust, id) function and my intention is to have both POST methods redirect back to the same page. How would I go about deleting a model record using a checkbox and POST? I will add an @login_required decorator later. Here is my code: models.py: class ReportDirectory(models.Model): report_name = models.CharField(max_length=300, unique=True, blank=False) report_desc = models.TextField() report_type = models.CharField(max_length=300) report_loc = models.TextField() slug = models.SlugField(unique=True, max_length=300) last_update = models.DateTimeField(null=True) main_tags = models.CharField(max_length=300) # Renames the item in the admin folder def __str__(self): return self.report_name class Favorite(models.Model): directory_user = models.ForeignKey(User, on_delete=models.CASCADE) user_report = models.ForeignKey(ReportDirectory, on_delete=models.CASCADE) favorited = models.BooleanField() def __str__(self): return str(self.directory_user)+" - "+str(self.user_report) views.py: from django.shortcuts import render,redirect from django.views import generic from .models import ReportDirectory, Favorite from django.contrib.auth.models import User from .forms import FavoriteForm def report_directory(request): favorite = Favorite.objects.filter(directory_user=request.user.id, favorited=True) reports = ReportDirectory.objects.exclude(favorite__directory_user=request.user.id, favorite__favorited=True) favform = FavoriteForm(initial={'directory_user':request.user,},) context = { 'reports':reports, 'favorite':favorite, 'favform':favform } if request.method =='POST' and 'favorited' in request.POST: form = FavoriteForm(request.POST) if form.is_valid(): … -
IntegrityError at /posts/12/new-comment/ NOT NULL constraint failed: posts_comment.author_id
Well i am adding commenting system in my project but got an integrity error. I dont know how to solve this. I have already asked this question one time but now one answer it. But now i am asking it again i hope someone will answer it with brief detail. I shall be very thankful to you. view.py class CommentCreateView(CreateView): redirect_field_name='posts/post_detail.html' model = Comment form_class = CommentForm template_name = "posts/snippets/comment_form.html" def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) models.py class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post,related_name='comments', on_delete=models.CASCADE) body = models.TextField() create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.author.username def get_absolute_url(self): return reverse("posts:post_detail", kwargs={"pk": self.pk}) traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/posts/12/new-comment/ Django Version: 3.0.3 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts', 'profiles'] Installed Middleware: ['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'] Traceback (most recent call last): File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: posts_comment.author_id) was the direct cause of the following exception: File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File … -
Heroku Django Admin returns 'FileNotFoundError at /admin/projects/project/add/'?
I am trying to setup a Django admin page to be able to update my project portfolio directly. Everything works fine until I click on the 'add project' button. Then I'm hit with an error: I do not understand what it is looking for. Any insight would be helpful as I've tried searching google/stack and haven't found a similar issue with a solution. If you need more information, let me know and I'll update my question. -
Django-channels Is it possible to send a message and wait for a response?
There is a very handy way to send a message and wait for a backward message in django-channels testing module: from channels.testing import WebsocketCommunicator communicator = WebsocketCommunicator(app, url) connected, subprotocol = await communicator.connect() await communicator.send_json_to(data=my_data) resp = await communicator.receive_json_from(timeout=my_timeout) Is it possible to write code of real consumer in same style? I mean something like that: class MyConsumer(AsyncJsonWebsocketConsumer): async def some_method(): await self.send_json(some_json) response = await self.receive_json(timeout=some_timeout) # do something with response -
TypeError: 'module' object is not iterable errors occurs when I create my first Django apps
During creating my first apps in Django named 'main' but it gives an error provides below. I check all of the previous answers but not capable to solve my problems. Can anyone help me to solve the issue? Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 591, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I create my views … -
Incompatible foreign key when attempting to link tables in Django?
I am trying to make a couple basic models, and link them together with a foreign key. First tool class tool1(models.Model): tool_id = models.CharField( max_length=100, primary_key=True, verbose_name="Tool", ) description = models.CharField( default="", max_length=100, verbose_name="Description", help_text="Describe tool here", ) dateOfAdd = models.DateField( default=datetime.today, verbose_name="Date" ) Referencing tool class Tool2(models.Model): tool1 = models.ForeignKey( Tool, default=None, on_delete=models.PROTECT blank=True ) For some reason the other tools I reference work, but this one will not. I get the following error: django.db.utils.OperationalError: (3780, "Referencing column 'tool1' and referenced column 'tool_id' in foreign key constraint [FK Name] are incompatible.") I cannot figure out why this is happening because the referencing tool is successfully referencing multiple other tools, but it will not link to this one. What is the reason for this error? And how can I fix it so that I can link the tables?