Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best practice of unique_together & auto-populated created_by work together?
I use the below codes for a long time and nothing is wrong. Now, when I start using djagno-rest-framework, I start wondering the way I used to do. I have a model Diary like this: class Diary(models.Model): date = models.DateField(verbose_name=_('Date'), default=today) created_by = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: unique_together = (('date', 'created_by')) With this DiaryModelForm, it works fine: class DiaryModelForm(forms.ModelForm): class Meta: model = Diary exclude = ['created_by'] def full_clean(self): super().full_clean() try: self.instance.validate_unique() except forms.ValidationError: self.add_error(field='date', error=_('The diary with this date has already existed.')) In the create/update views I use them like this: def diary_create(request): instance = Diary(created_by=request.user) if request.method == 'POST': form = DiaryModelForm(request.POST, instance=instance) if form.is_valid(): instance = form.save() def diary_update(request, pk): instance = get_object_or_404(Diary, pk=pk, created_by=request.user) if request.method == 'POST': form = DiaryModelForm(request.POST, instance=instance) if form.is_valid(): instance = form.save() They work fine. By just passing a different instance, I can easily handle logic of create/update views. The processes seems consistent. When I start using django-rest-framework, I try to convert what I do with from ModelForm to ModelSerializer, but I found that hard. Some method names (like full_clean) between thses two class are a little different. And some ways I found in their doc seems convenient, but not the … -
502 bad gateway for django site
I deployed my Django app to gcloud and everything uploads with no error but when I go on the site it comes up with a 502 bad gate way. I've checked the logs and this error pops up. textPayload: "Container called exit(1)." insertId: "6067eaaf00085f11035507b0" resource: {2} timestamp: "2021-04-03T04:10:23.548428287Z" severity: "WARNING" labels: {1} Any ideas on this? I've been stuck on this all day, I have my app.yaml done properly (to my knowledge) and the database in settings.py runs fine. -
Error after changing from sqllite3 data base to PostgreSQL
I have been running into some error after changing from sqllite3 database to PostgreSQL.Here is some of the error. ValueError at /post/None/ Field 'id' expected a number but got 'None'. Request Method: GET Request URL: http://127.0.0.1:8000/post/None/ Django Version: 3.1.6 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'None'. Exception Location: /home/mike/.local/share/virtualenvs/mercy-TKuV6FoL/lib/python3.7/site-packages/django/db/models/fields/__init__.py, line 1778, in get_prep_value Python Executable: /home/mike/.local/share/virtualenvs/mercy-TKuV6FoL/bin/python Python Version: 3.7.5 Python Path: ['/home/mike/Web/mercy', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/mike/.local/share/virtualenvs/mercy-TKuV6FoL/lib/python3.7/site-packages'] Server time: Sat, 03 Apr 2021 06:52:29 +0300 and here is some code in the views.py file def post(request, id): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:3] post = get_object_or_404(Post, id=id) if request.user.is_authenticated: PostView.objects.get_or_create(user=request.user, post=post) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = post form.save() context = { 'form': form, 'post': post, 'most_recent': most_recent, 'category_count': category_count, } return render(request, 'post.html', context) -
Why is my Pillow app not working with Django
I tried to include ImageField to my models in models.py of the model Topic. When I tried to migrate the model. It is not working. It says that I need to install pillow (which I did and when I tried again it is still not working. Please refer to this video The video thats shows how this doesn't work Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): text = models.CharField(max_length = 200) date_added = models.DateTimeField(auto_now_add = True) image = models.ImageField(upload_to = 'backgroud_images', null = True, blank = True) owner = models.ForeignKey(User,on_delete = models.CASCADE) def __str__(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic,on_delete = models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = "Entries" def __str__(self): return self.text[:50] the INSTALLED_APPS list from settings.py.Is it because I didn't include pillows in here? INSTALLED_APPS = [ 'learning_logs', 'users', 'bootstrap4', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Ubuntu/Django/Postgres degrading server performance over several hours until server becomes unresponsive
I have a website running on an AWS EC2 instance with Django and Postgres. Also I have a python script constantly running and writing to the database. CPU and RAM seem fine, but after several hours the server starts slowing down and eventually becomes unresponsive. I can't even SSH into it to check what's going on. The only option is to force reboot it. What troubleshooting would you recommend? -
How can i register my new router inside urls file
I'm working on a small project using Django Rest Framework, and I create my first application successfully called (contact), now i created a second one called List, I would like to know how can I register the router again that's what I did to register my first application called ( contact ) I created a file called router.py inside my contact/api/ router.py from django.urls import path from contact.api.views import ContactView from rest_framework import routers router = routers.DefaultRouter() router.register(r'contact', ContactView, basename="contact") and I have included router.py in my urls.py by doing : from django.contrib import admin from django.urls import path, include from contact.api.router import router urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ] NB : Until the moment everything is OK Now how can i register my second file router.py of my list application inside urls again -
ValueError: badly formed hexadecimal UUID string
In my system I'm trying to auto generate a unique random string for each users to be passed later on in the URL as the reference to that account and I recently read about the UUID in django models. And this is how my model looks like: class User(AbstractBaseUser, PermissionsMixin): card_number = models.CharField(max_length=20, unique=True) first_name = models.CharField(max_length=150) middle_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) address = models.CharField(max_length=200) account_code = models.UUIDField(max_length=200, default=uuid.uuid4(), editable=False) And I ran into an error when start creating superuser in the terminal: Traceback (most recent call last): File "C:\Users\User\PycharmProjects\ViajeroProject\viaje\manage.py", line 22, in <module> main() File "C:\Users\User\PycharmProjects\ViajeroProject\viaje\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 113, in handle error_msg = self._validate_username(username, verbose_field_name, database) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 234, in _validate_username self.UserModel._default_manager.db_manager(database).get_by_natural_key(username) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\base_user.py", line 45, in get_by_natural_key return self.get(**{self.model.USERNAME_FIELD: username}) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 425, in get num = len(clone) File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 269, in __len__ self._fetch_all() File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line … -
Else statement is not working. Getting error: TypeError: markdown() missing 1 required positional argument: 'text'
Django code is to create an Entry Page where Visiting /wiki/title, where TITLE is the title of an encyclopedia entry, should render a page that displays the contents of that encyclopedia entry. The view should get the content of the encyclopedia entry by calling the appropriate util function. If an entry is requested that does not exist, the user should be presented with an error page indicating that their requested page was not found. But if statement is working fine, but else statement is not working. When I am browsing http://127.0.0.1:8000/wiki/CSS, it should navigate me to that dedicated page. But I am getting an error: markdown() missing 1 required positional argument: 'text'. Please advise how to mitigate this error? views.py from markdown import markdown from django.shortcuts import render from . import util #EntryPage using title def entry(request, entry): #markdowner = markdown() entryPage = util.get_entry(entry) #Displays the requested entry page, if it exists if entryPage is None: return render(request, "encyclopedia/nonExistingEntry.html", { "entryTitle": entry }) # Title exists, convert md to HTML and return rendered template else: return render(request, "encyclopedia/entry.html", { "entry": markdown().convert(entryPage), "entryTitle": entry }) urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", … -
Large software project development tips & suggestions
Can anyone give me any insight as to how they typically go about building a rather large software project with lots of moving parts? Do you start with the frontend? Backend? How do you draw out architecture for backend/state maps for frontend? Do you do this? When do you actually begin to program it? All the projects I have done, I've kind of just jumped in, but those are much smaller and are less impacted by scalability issues any help would be appreciated -
How do I render images saved in my database as a field of a model
I have a model class NewListing(models.Model): title= models.CharField(max_length= 20) image= models.ImageField(upload_to= "static", default="static/default_image.jpg", null=True) description = models.TextField() Starting_Bid= models.IntegerField() time= models.CharField(max_length= 30) and the model's form class NewListingForm(ModelForm): class Meta: model= NewListing fields= ["title", "image", "description", "Starting_Bid"] In my views.py, i want the index url to display a list of all the Listings so i wrote this def index(request): return render(request, "auctions/index.html", { "listings": list(NewListing.objects.all()) }) This is my index.html where i tried to display each listing in its own div {% for listing in listings %} <div> <h3> <a href='listings/{{listing.title}}'> {{listing.title}}</a> </h3> <p>{{listing.description}}</p> <img src='static/{{listing.image}}'> <p>{{listing.time}}</p> </a> </div> {% endfor %} The problem is whenever i try to render this page, I get a broken thumbnail instead of the image. How do i fix this? -
Django: Override for delete_selected not working
I created a custom user model (users_user) to be used instead of Django's default auth_user model. When i got to the default Admin site and open the User object, it correctly shows the list of records for my custom user model. But when I delete one of those records, it seems to be referencing the default auth_user model. I get the error: IntegrityError at /admin/users/user/ insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(3) is not present in table "auth_user". users/models.py from django.db import models from PIL import Image from django.conf import settings from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) #~~~ CUSTOM USER ~~~ class UserManager(BaseUserManager): def create_user(self, email, username, password=None): print('username in UserManager.create_user(): ' + username) if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, #todo: confirm, is this right? ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, username=username, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, username, password): print('username in UserManager.create_superuser(): ' + username) """ Creates … -
Django slow load table with large data - duplicate query
I'm working with a django example and seem to be getting duplicate queries and slow load time - I see duplicates in the django debug toolbar. The following is the 3 main files in the project. Are there any optimizations to be made on the functions in the model : # views.py class IndexView(ListView): template_name = "myapp/index.html" paginate_by = 100 model = Company <!-- index.html --> ... </thead> <tbody> {% for company in company_list %} <tr> <td>{{ company.name }}</td> <td>{{ company.get_order_count }}</td> <td>{{ company.get_order_sum}}</td> </tr> {% for contact in company.contacts.all %} <tr> <td>&nbsp;</td> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td>Orders: {{ contact.get_order_count }}</td> <td></td> </tr> {% endfor %} {% endfor %} </tbody> <tfoot> ... # models.py class Company(models.Model): name = models.CharField(max_length=100) industry = models.CharField(max_length=100, blank=True) # get all orders associated with this company def get_order_count(self, page_obj): orders = 0 for order in self.orders.all(): orders += 1 return orders def get_order_sum(self): total_sum = 0 for contact in self.contacts.all(): for order in contact.orders.all(): total_sum += order.total return total_sum class Contact(models.Model): company = models.ForeignKey(Company, related_name="contacts", on_delete=models.PROTECT) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def get_order_count(self): orders = 0 for order in self.orders.all(): orders += 1 return orders class Order(models.Model): order_number = models.CharField(max_length=100) company = … -
IntegrityError Django Postgres when deleting
This is the error, I get it when I delete a TaskList, which is related to ChartDay which is related to MemberRemaining all with on_delete CASCADE, If a delete TaskList the Charts related to it should be deleted, same way happens with ChartDay to Chart and MemberRemaining to ChartDay. Why am I getting this error? insert or update on table "chart_memberremaining" violates foreign key constraint "chart_memberremainin_chart_day_id_e25c792b_fk_chart_cha" DETAIL: Key (chart_day_id)=(7) is not present in table "chart_chartday". -
How to solve 401 Unauthorized error in Socket.IO Django framework?
I am trying to get the Socket.IO work with my Django server. Here is my setup: Frontend js: const socket = io.connect('127.0.0.1:8001'); socket.on('connect', () => { console.log('socket id: %s\n', socket.id); }); Django server: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() sio = socketio.Server(async_mode='eventlet', cors_allowed_origins='*', logger=True, engineio_logger=True) @sio.event def connect(sid, environ, auth): print('connect ', sid, auth) static_files = { '/public': './static', } application = socketio.WSGIApp(sio, application, static_files=static_files) eventlet.wsgi.server(eventlet.listen(('', 8001)), application) Dependencies Django==2.2.11 django-cors-headers==3.0.0 eventlet==0.30.0 gunicorn==19.7.1 python-socketio==4.6.1 ... When I run the js, the server will return 401 unauthorized error before reaching the connect function. Frontend: GET http://127.0.0.1/socket.io/?EIO=3&transport=polling&t=NYKlRjO 401 (UNAUTHORIZED) Django server log: (11053) accepted ('127.0.0.1', 34906) 127.0.0.1 - - [02/Apr/2021 15:39:31] "GET /socket.io/?EIO=3&transport=polling&t=NYKlTB8 HTTP/1.1" 401 253 0.002482 But the weird thing is if I commented out the connect event, everything like other events work just fine: # @sio.event # def connect(sid, environ, auth): # print('connect ', sid, auth) Anyone knows why if I set the connect event and the socket suddenly stop working? -
Need to display books by the same author for a bookstore web app
I am working on a bookstore web app and need help displaying books by the same author when a hyperlink of their name is clicked. The problem I am running into is the program is grabbing the id number of the book instead of the author_id and displaying the information for the book with that id. I need it to display all of the books in the database by the same author. models.py class Product(models.Model): # model to create table on database products genre = models.ForeignKey('Genre',related_name='products',on_delete=models.CASCADE) author = models.ForeignKey('Author',related_name='authors',on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='static/media',blank=True) image2 = models.ImageField(upload_to='media/%Y/%m/%d',blank=True) image3 = models.ImageField(upload_to='media/%Y/%m/%d',blank=True) publisher = models.CharField(max_length=100, db_index=True) release_date = models.DateTimeField(null=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_detail',args=[str(self.slug)]) class Author(models.Model): # model to create table on database author first_name = models.CharField(max_length=200, db_index=True) last_name = models.CharField(max_length=200, db_index=True) biography = models.TextField(blank=True) created = models.DateTimeField(auto_now=True) class Meta: ordering = ('-first_name',) index_together = (('id'),) views.py def book_author(request, id=None): item = Product.objects.get(id=id) context = { 'items': Product.objects.all(), 'book_list': Product.objects.all().filter(author_id = id), 'id': item.id, 'name': item.name, 'cover': item.image, 'author': item.author, 'author_id': … -
RuntimeError: Model class himalayadashbords.clients.models.Client doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I"m using cookie cutter and I ve this error with codes: clients/apps.py: from django.apps import AppConfig class ClientConfig(AppConfig): name = 'clients' settings.py: LOCAL_APPS = [ "himalayadashbords.users.apps.UsersConfig", "himalayadashbords.clients.apps.ClientConfig", "himalayadashbords.queries.apps.QueriesConfig", "himalayadashbords.dashboard.apps.DashboardConfig", # Your stuff: custom apps go here ] clients/models.py: from django.db import models class Client(models.Model): name = models.CharField(max_length=50, unique=True) QBO_id = models.CharField(max_length=100) QBO_refreshtoken = models.CharField(max_length=100) fiscalmonth = models.IntegerField(default=1) def __str__(self): return self.name dashboard/views.py: from himalayadashbords.clients.models import Client from himalayadashbords.queries.QBOQueries.qQBOInvRevenues import avNEclients listofcpy = Client.objects.all().only("pk", "name") error debug: File "/Users/xxx/PycharmProjects/cool/himalayadashbords/himalayadashbords/clients/urls.py", line 3, in <module> from .views import ( File "/Users/xxx/PycharmProjects/cool/himalayadashbords/himalayadashbords/clients/views.py", line 8, in <module> from .models import Client File "/Users/xxx/PycharmProjects/cool/himalayadashbords/himalayadashbords/clients/models.py", line 3, in <module> class Client(models.Model): File "/Users/xxx/PycharmProjects/cool/himalayadashbords/venv/lib/python3.8/site-packages/django/db/models/base.py", line 113, in __new__ I've already tried: to change apps.py with name = himalayadashbords.clients and verbose="clients" try to do my query in module client than import it in dashboard but I've same issue -
Django Administration: Delete record from custom user model
I have created a custom user model (users_user) which works for registering new users (creating new custom user records) and logging in. But if I go to the Admin page, and try to delete a user record from there, it seems to be trying to delete records from the default user model (auth_user). I get the error: IntegrityError at /admin/users/user/ insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(3) is not present in table "auth_user". Is there a way I can keep the standard Django Administration pages (screenshot below), but reference my custom user model instead of the standard auth_user model? users/models.py from django.db import models from PIL import Image from django.conf import settings from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) #~~~ CUSTOM USER ~~~ class UserManager(BaseUserManager): def create_user(self, email, username, password=None): print('username in UserManager.create_user(): ' + username) if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, #todo: confirm, is this right? ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, username=username, … -
How to access two models in a single view to print their fields using single html file?
I have two models in my django application (Client and Installment). My models.py is given below: models.py from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.name def get_absolute_url(self): return reverse('client_details',kwargs={ 'pk' : self.pk}) class Installment(models.Model): client = models.ForeignKey(Client, null=True, on_delete=models.CASCADE) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField() installment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.installment_month def get_absolute_url(self): return reverse('installment_confirmation') And to show the client details I have a view called 'clientDetailView' and is shown below: view.py class ClientDetailView(DetailView): model = Client model = Installment And the template for this is called 'client_details.html' is also given below: <!DOCTYPE html> {% extends "property_details/base.html" %} {% block content %} <body> <legend class="border-bottom mb-4"><h3>{{ object.name }}</h3></legend> <article class="media content-section"> <div> <p class="text-muted">Client CNIC: {{ object.CNIC }}</p> <p class="text-muted">Date of Birth: {{ object.dob }}</p> <p class="text-muted">Type of Property: {{ object.property_type }}</p> <p class="text-muted">Date of Agreement: {{ object.date_posted|date:"F d, Y" }}</p> </div> </article> <legend class="border-bottom mb-4"><h5>Installment History</h5></legend> <article class="media content-section"> <div> <!--<p class="text-muted">Installment Month: {{ object.installment_month … -
Specifying both 'fields' and 'form_class' is not permitted (Django)
I have created a validator for my UpdateView but I got this error (in title). These are my codes. Forms.py class HotelBookingAdForm(forms.ModelForm): class Meta: model = HotelBookingAd fields = '__all__' def clean_sales_price(self): sales_price = self.cleaned_data["sales_price"] if sales_price > purchase_price: raise forms.ValidationError("Error") print("error") return sales_price Views.py class HotelUpdate(AuthorsAccessMixin,FieldsMixin,FormValidMixin,UpdateView): model = HotelBookingAd form_class = HotelBookingAdForm template_name = "account/article-create-update.html" Models.py class HotelBookingAd(models.Model): purchase_price = models.IntegerField() sales_price = models.IntegerField() after i try to reach HotelUpdate view i got the Error --> Specifying both 'fields' and 'form_class' is not permitted. (in web browser). also i have removed fields from HotelBookingAdForm and got this error in console : Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form HotelBookingAdForm needs updating. Can anybody help me to fix this problem? Thanks! -
Cookies not being store in the browser but it does in Postman
Working with Next.js and Django Rest Framework, I'm authenticating users using JWT. First, when the user successfully logs in to the page, a cookie (which contains the JWT token) is sent to the browser. When the user tries to access a specific page, this cookie is used to validate the petition. This works fine using Postman (when I fetch a protected URL, the server returns what I spect) but I'm having trouble storing the cookie in the browser. Django | login function @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def login(request): ... response = Response() response.set_cookie(key='jwt', value=token, httponly=True, max_age=86400) response.data ={ 'message': 'success', } return response And here is how I'm fetching /api/login Next | Login.js var axios = require('axios'); var FormData = require('form-data'); var data = new FormData(); data.append('email', this.state.email); data.append('password', this.state.password); data.append('X-CSRFToken', csrftoken); data.append('mode', 'same-origin'); data.append('Content-Type', 'application/json'); var config = { method: 'post', credentials: 'include', #I'm probably having issues with this url: 'http://localhost:8000/api/login', data : data }; axios(config) .then(res=> { console.log('success'); #I got loged, but the cookies is not stored }) .catch( error=>{this.setState({isError:true})} ); -
I need help to create sql query
id | game_id | point 1 | 100 | 1 2 | 200 | 1 3 | 200 | 0 4 | 300 | 0 5 | 100 | 1 6 | 100 | 1 7 | 200 | 0 8 | 100 | 1 I need create a sql query and django query for get logs grouped by local game_id and count the points that correspond to the game_id, it should look something like this game_id | point 100 | 4 200 | 1 300 | 0 -
ModelChoiceField javascript onChange arguments
I am new to JavaScript as well as Django. The project has a Students model with multiple fields, and I have implemented a ModelChoiceField form which drops down and allows for selecting a particular record in the Students table. forms.py: class StudentChoiceField(forms.Form): students = forms.ModelChoiceField( queryset=Student.objects.values_list().order_by("last_name"), empty_label="(select student)", widget=forms.Select(attrs={"onChange":'refresh()'}) ) def __init__(self, *args, **kwargs): super(StudentChoiceField, self).__init__(*args, **kwargs) # without the next line label_from_instance does NOT work self.fields['students'].queryset = Student.objects.all().order_by("last_name") self.fields['students'].label_from_instance = lambda obj: "%s %s" % (obj.last_name, obj.first_name) The label_from_instance is overridden, so that the drop-down form displays just two of the fields (there are eleven total in the model). When a student is selected, I want to update some textfields in the page to display the remaining fields of the model. Currently, have implemented a javascript function refresh() which is invoked for the onChange event of the StudentChoiceField form. index.html (all_students_choice is the StudentChoiceField form): {% extends "base.html" %} {% block content %} <body> <script> function refresh(){ var id = document.getElementById("id_students").value; console.log(id); } </script> <div class="container"> <form method=POST action=""> {% csrf_token %} {{ all_students_choice }} </form> </div> </body> {% endblock %} I have confirmed through browser console that the javascript function is getting invoked, and printing the value of … -
Django files not found when served with Apache
I deployed my Django project on a Linux server using Linode. When I run it by the python manage.py runserver command on port 8000 everything looks fine. However, when I use apache2 I get the following error when loading the website: FileNotFoundError at / [Errno 2] No such file or directory: 'research_files/data.xlsx' Request Method: GET Request URL: http://453.33.13.202/ Django Version: 3.1.5 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: 'research_files/data.xlsx' In /etc/apache2/sites-available I've created a django_project.conf file which has the following instructions: Alias /research_files/ /home/alexa/django_project/research_files/ <Directory /home/alexa/django_project/django_project/research_files> Require all granted </Directory> <Directory /home/alexa/django_project/django_project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/alexa/django_project/django_project/wsgi.py> WSGIDaemonProcess django_app python-path=/home/alexa/django_project python-home=/home/alexa/django_project/venv WSGIProcessGroup django_app Then I've enabled that file by running sudo a2ensite django_project and also given access to the folder by running: sudo chown :www-data django_project/research_files sudo chmod 664 django_project/research_files What may be causing this error? -
Django static files referencing
I'm trying to link some pictures to my Django app from the static folder, but instead it creates a new static folder inside the templates directory. My HTML: {% load static %} <!DOCTYPE html> {% extends 'milk_app/base.html' %} {% load staticfiles %} {% block title_block %} Homepage {% endblock %} {% block body_block %} <!-- Home page for Hosts --> {% if user.userprofile.account == "Host" %} <div class="container"> <div class="row"> <div class="home_hover_pictures col-4"> <a href="home.php"><img class="img-responsive" src="{% static 'images/listing-property.jpg' %}"></a> <h4>Create a new listing</h4> </div> <div class="home_hover_pictures col-4"> <a href="home.php"><img class="img-responsive" src="{% static 'images/your-properties.jpg' %}"></a> <h4>Show your rented properties</h4> </div> <div class="home_hover_pictures col-4"> <a href="home.php"><img class="img-responsive" src="{% static 'images/scroll-others.jpg' %}"></a> <h4>Scroll other properties</h4> </div> </div> </div> <!-- Home page for Tenants (not the beer) --> {% elif user.userprofile.account == 'Tenant' %} <!-- Home page for not logged users --> {% else %} <br><br> <section > <div> </div> </section> {% endif %} {% endblock %} My folder looks like this: 1. APP_APP 2. ACTUALAPP 3. STATIC * images - the actual images.jpgs 4. TEMPLATES * creating a new **{% static 'images** folder - creating a new image here So my VS Code is creating a new file somewhere I don't want … -
EOF occurred in violation of protocol (_ssl.c:1125) on python:3.8-slim-buster
I recently updated a django api from 2.2 to 3.1. I updated the dockerfile and related bash files like django-cookiecutter did https://github.com/pydanny/cookiecutter-django/commit/b22045bcd4ebf563ccdcf226fb389a6bb71e2654#diff-1872e6a6f0bbcb27f2eda185ac89eed05eb7a402b298e58bcbef29bf039c2c13 The upgrade mostly went well except now in production we cannot send email. I have a minimal management command I run in production to test email settings from django.conf import settings from django.core.mail import send_mail from django.core.management.base import BaseCommand class Command(BaseCommand): """ Sends an email to the provided addresses. """ help = "Sends an email to the provided addresses." def add_arguments(self, parser): parser.add_argument("emails", nargs="+") def handle(self, *args, **options): self.stdout.write(f"send_email from: {settings.EMAIL_FROM_FIELD}") for email in options["emails"]: try: send_mail( "expert-system test email", "a simple email", settings.EMAIL_FROM_FIELD, [email], ) except BaseException as e: self.stdout.write(f"Problem sending email: {e}") This returns $ python manage.py send_email harry@test.com send_email from: test@test.com Problem sending email: EOF occurred in violation of protocol (_ssl.c:1125) Another stackoverflow suggested testing if tls 1.1 is supported. $ python -c "from urllib.request import urlopen ; print(urlopen('https://www.howsmyssl.com/a/check').read())" b'{"given_cipher_suites":["TLS_AES_256_GCM_SHA384","TLS_CHACHA20_POLY1305_SHA256","TLS_AES_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","TLS_DHE_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256","TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256","TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","TLS_DHE_RSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384","TLS_DHE_RSA_WITH_AES_256_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256","TLS_DHE_RSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA","TLS_DHE_RSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA","TLS_DHE_RSA_WITH_AES_128_CBC_SHA","TLS_RSA_WITH_AES_256_GCM_SHA384","TLS_RSA_WITH_AES_128_GCM_SHA256","TLS_RSA_WITH_AES_256_CBC_SHA256","TLS_RSA_WITH_AES_128_CBC_SHA256","TLS_RSA_WITH_AES_256_CBC_SHA","TLS_RSA_WITH_AES_128_CBC_SHA","TLS_EMPTY_RENEGOTIATION_INFO_SCSV"],"ephemeral_keys_supported":true,"session_ticket_supported":true,"tls_compression_supported":false,"unknown_cipher_suite_supported":false,"beast_vuln":false,"able_to_detect_n_minus_one_splitting":false,"insecure_cipher_suites":{},"tls_version":"TLS 1.3","rating":"Probably Okay"}' How do I get email to send on production?