Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CORS requests creating 403 Forbidden Error only on server
I have an application which uses Django for the backend and react for the frontend so I setup django-cors-headers. When I tested the application locally with the settings I added, I had no issues. But I deployed to my server, I kept getting 403 error on API requests (except GET requests). Below is my settings.py file (only the relevant settings): import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<my-secret-key>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['<my-server-ip>'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'frontend', 'services', 'rest_framework', 'dj_rest_auth', 'rest_framework.authtoken', 'user', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ) } CORS_ALLOWED_ORIGINS = [ "http://<my-server-ip>:8000", "http://localhost:8000", "http://127.0.0.1:8000", "http://0.0.0.0" ] CSRF_TRUSTED_ORIGINS = [ "http://<my-server-ip>:8000", "http://localhost:8000", "http://127.0.0.1:8000", "http://0.0.0.0" ] CORS_ALLOW_CREDENTIALS = True I make the API requests from React using axios … -
Django Serializer how to hide/show related fields
I have three 4 Model Quiz, Question, Multichoice, and Answers When using serializer to display a Quiz Data, the data is displayed as follows [ { "id": 333, "title": "Practice Exam : Class 12 Physics (Current Electricity) ", "description": "", "url": "b75038cf-e309-45da-9a91-02a4ff1ea231", "category": 52, "random_order": true, "pass_mark": 0, "draft": false, "durationtest": "10:00", "get_questions": [ { "id": 6155, "content": "<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">The equivalent resistance between P and Q in the given figure is approximately:&nbsp;</span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(A) 10&Omega; </span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(B) 5&Omega; </span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(C) 6&Omega; </span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(D) 20&Omega; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;B</span></span></p>\r\n<gdiv></gdiv>", "category": 52, "sub_category": 178, "getanswers": [ { "id": 17065, "content": "A", "correct": false, "question_id": 6155, "question": 6155 }, { "id": 17066, "content": "B", "correct": true, "question_id": 6155, "question": 6155 }, { "id": 17067, "content": "C", "correct": false, "question_id": 6155, "question": 6155 }, { "id": 17068, "content": "D", "correct": … -
Django workaround to use window function call in an aggregate function?
I'm trying to calculate customer order frequency. First use a window function to get the previous order date then annotate the days since the last order. from django.db.models import Avg, F, Window from django.db.models.functions import ExtractDay, Lag, TruncDate orders = ( Order.objects .annotate( prev_order_date=Window( expression=Lag('paid_at', 1), partition_by=[F('customer_email')], order_by=F('paid_at').asc(), ), days_since_last=ExtractDay( TruncDate('paid_at') - TruncDate('prev_order_date') ), ) ) Then group by customer_email before calculating the average frequency. customer_data = ( orders.values('customer') .annotate(avg_frequency=Avg('days_since_last')) ) Unfortunately this throws an error. Does anyone know of a workaround or know of an alternate way to calculate the average frequency? psycopg2.errors.GroupingError: aggregate function calls cannot contain window function calls -
Django request.session empty between views using JWT
I'm having trouble with using request.session in Django (using JWT for authentification) to keep some user's parameters. I am well aware I have to specify INSTALLED_APPS = [ 'django.contrib.sessions', MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', but I think there is something I don't get and I think it is related to the fact I am using JWT. I can store some data in request.session when doing an API call (view) but it won't exist anymore on another one. @api_view(["POST"]) def updateFilters(request): # récupère les filtres dans la session filtres = request.data for key, value in filtres.items(): request.session[key] = value #it's ok here return Response("Filters updated") @api_view(['POST']) def testAPI(request): #empty here !!!!! print(request.session.items()) return Response("Test") Could someone explain what is wrong and maybe propose a solution ? Thank you for your help -
Django - pagination based on search criteria
I am having issues getting results when clicking on page 2 and above - most likely due to url issues. I have a list of names and if I search on e.g. "John" I want them to be separated by pages if number of names > e.g. 10. My Views are as follows: (searching works fine) def name_search(request): if 'q' in request.GET: q=request.GET.get('q', '') pvt_list = pvt_data.objects.filter(full_name__icontains=q) #Pagination p = Paginator(pvt_list, 10) # Show 10 contacts per page. page_num = request.GET.get('page', 1) try: page = p.page(page_num) except PageNotAnInteger: page = p.page(1) except EmptyPage: page = p.page(1) context = {'items' : page} return render(request, 'home/name_search.html', context) else: return render(request, 'home/name_search.html') My urls.py file is urlpatterns = [ ... path('name_search', views.name_search, name='name_search'), ... ] My html file is {% for pvt in items %} {{ pvt.full_name }} {% endfor %} <div class="pagination"> <span class="step-links"> {% if items.has_previous %} <a href="?page={{ items.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ items.number }} of {{ items.paginator.num_pages }}. </span> {% if items.has_next %} <a href="?page={{ items.next_page_number }}">next</a> {% endif %} </span> </div> When I search, I get the following link 'http://127.0.0.1:8000/name_search?q=John' with the first 10 names correct. When I click on next button I get … -
Query data that belongs to a certain user and compare to similar data from another user
I am a month into working with django and this is giving me trouble.I have a table Invoice that stores invoices .The contents for one invoice are structured as below.The invoices have an appointment field that has a field doctor that stores details of the doctor belonging to the appointment.The invoice also has a doctor_amount which belongs to the doctor in the appointment.I need to get all the doctor_amounts that belong to one doctor and sum them.I then need to find the doctor who has the most amount.I have tried a lot and do not know which attempt is even close so I can put here.So I will just leave it open so I can get independent insight. I will really appreciate the help. { id:1, status: "cleared", appointment:{ id: 3, doctor:{ id: 10, name: "kev", } amount: 10000, doctor_amt: 9000, } } views.py class TopDoctorView(APIView): def get(self, request, format=None): all_invoices = Invoice.objects.all() serializers = InvoiceSerializer(all_invoices, many=True) try: result = {} invoices = serializers.data result = res return Response(result, status=status.HTTP_200_OK) except Exception as e: error = getattr(e, "message", repr(e)) result["errors"] = error result["status"] = "error" return Response(result, status=status.HTTP_400_BAD_REQUEST) -
ESP8266 not connecting to django server
I've created a local server on my pc with django and im trying to send a GET request from my esp8266 01 module which just gives a message and a POST request which send data that is stored in a JSON file. The server works fine with postman but doesnt connect with a esp. The http request gives error code -1 This is code only for GET ESP Code: #include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> ESP8266WiFiMulti WiFiMulti; void setup() { Serial.begin(115200); // Serial.setDebugOutput(true); Serial.println(); Serial.println(); Serial.println(); for (uint8_t t = 4; t > 0; t--) { Serial.printf("[SETUP] WAIT %d...\n", t); Serial.flush(); delay(1000); } WiFi.mode(WIFI_STA); WiFiMulti.addAP("username", "password"); } void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { WiFiClient client; HTTPClient http; Serial.print("[HTTP] begin...\n"); if (http.begin(client, "http://127.0.0.1:8000/polls/")) { Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); // httpCode will be negative on error if (httpCode > 0) { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { String payload = http.getString(); Serial.println(payload); } } else { … -
Django login required error ERR_TOO_MANY_REDIRECTS
My django application worked fine before using LoginRequiredMiddleware, after I used LoginRequiredMiddleware i have got this error. This page isn’t working 127.0.0.1 redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'login_required.middleware.LoginRequiredMiddleware', # 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REPORT_BUILDER_ASYNC_REPORT = True WSGI_APPLICATION = 'mymachine.wsgi.application' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'index' LOGOUT_REDIRECT_URL = 'login' LOGIN_URL = 'login' CSRF_COOKIE_HTTPONLY = False url.py urlpatterns = [ path('login/', LoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('', IndexView.as_view(), name='index'), ] view.py class LoginView(CreateView): """ Login """ template_name = "registration/login.html" defaults = dict() def __init__(self, **kwargs): super(LoginView, self).__init__(**kwargs) def on_create(self, request, *args, **kwargs): return render(request, self.template_name, self.defaults) def init_component(self, request): logout(request) self.defaults['name_space'] = reverse('auth') self.defaults['form'] = LoginForm def get(self, request, *args, **kwargs): self.init_component(request) return self.on_create(request, *args, **kwargs) def post(self, request, *args, **kwargs): form = LoginForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user: login(request, user) request.session["company_id"] = 1 return redirect(settings.LOGIN_REDIRECT_URL) elif user is None: context = {'name_space': reverse('auth'), 'form': LoginForm, 'message': _("username or password is incorrect"), 'add': 'try Again'} return render(request, 'registration/login.html', context) This is the url that appears in chrome. http://127.0.0.1:4050/login/?next=/login/ I have tried must of the answers in the … -
Django: how to refresh html content on new database entry
I am developing a MQTT Dashboard app with django. I have a mqtt thread running in background, periodically polling for data from remote device and saving it as a database (MariaDB) row. I also have a view that displays this row in simple table. Now, what I want to do is to refresh this view (without page reload) when new data appears and my question is how to do that. I thought of two different approaches: Use JS's setInterval triggering ajax call to periodically refresh content. Problem here is that I'm not really proficient with JavaScript nor jQuery so I would love to get simple example how to do that Somehow refresh data from within on_message function which is called when mqtt gets new data. Problem here is that I have no clue if it is even possible I would appreciate any explanation of above or even more some description of different, more proper way to do that. Here is my code: part of template with content i want to refresh: <div class="row mb-4 justify-content-center text-center"> <h1 class="text-uppercase text-white font-weight-bold">{% translate "Parameters" %}</h1> <table id="device-parameters-table"> <thead> <tr> <th scope="col">{% translate "Parameter" %}</th> <th scope="col">{% translate "Value" %}</th> <th scope="col">{% translate … -
In my form there is an image upload section. If user not upload any file, then it gives MultiValueDictKeyError. How to get rid of it?
I am working on a project for a Django web-based application. In this project, there is a section in which I take info from the user through an HTML form. I added a section "image upload " but it gives a MultiValueDictKeyError error when the user does not upload any file. I tried this but not working for me. This is error section : error image This is my addpost.html section. It consists of a form through which, I am taking info. <form action="{% url 'addpost' %}" method='POST' enctype="multipart/form-data" novalidate> {% include 'includes/messages.html' %} {% csrf_token %} {% if user.is_authenticated %} <input type="hidden" name="user_id" value="{{user.id}}"> {% else %} <input type="hidden" name="user_id" value="0"> {% endif %} <div class="row "> <div class="tex-center"> <div class="row"> <div class="col-md-6 text-left"> <div class="form-group name"> <input type="text" name="author" class="form-control" placeholder="Author" {% if user.is_authenticated %} value="{{user.first_name}}" {% endif %} readonly> </div> </div> <div class="col-md-6"> <div class="form-group name"> <input type="text" name="title" class="form-control" placeholder="title" required> </div> </div> <div class="col-md-6"> <div class="form-group name"> <input type="text" name="location" class="form-control" placeholder="location" required> </div> </div> <div class="col-md-6"> <div class="form-group name"> <input type="text" name="short_desc" class="form-control" placeholder="Write short description" required> </div> </div> <div class="col-md-12"> <div class="form-group message"> <textarea class="form-control" name="full_desc" placeholder="Write full description"></textarea> </div> </div> <input type="file" … -
Django static folder works on a local server but doesn`t work on the remote server
Django static folder works on a local server but doesn`t work on the remote server. What could be the reason? -
Django Prefecth - call root elements field in filter
Here is my code, I am retrieving a Feed and all related data using the query. I am also checking if the user who is retrieving the feed is also a friend of the user who posted the feed. For friend relationships, I am using the Friends model. viewer_id and feed_id will be given by the system. I want to replace ?????? with a field from Feed model (like user_id who posted the Feed) feed = Feed.objects.select_related( 'user_info', 'images' ).prefetch_related( 'tags', Prefetch( "friends_set", queryset=Friends.objects.filter(user=viewer_id, follows=??????), to_attr="friends" ), ).get(id=feed_id) -
Django: how to add a step among the auth login code
I'm building out my first Django Project, and I'm always grateful that authentication steps are provided in modern frameworks, but I'm having trouble seeing how/where to customize the login process to do an additional step behind the scenes. I followed a tutorial to use the Django authentication, and everything is working great. I made a registration/login.html page that includes 'next' for where to take the users. I include the Django urls for authentication in mysite/urls.py: urlpatterns = [ path('familytree/', include('familytree.urls')), path('admin/', admin.site.urls, name='admin'), path('accounts/', include('django.contrib.auth.urls')), ] In settings.py, I specify that I want users to go to the dashboard page after logging in: LOGIN_REDIRECT_URL = 'dashboard' LOGOUT_REDIRECT_URL = 'landing' The question: I'd like to add one other step: after a user successfully authenticates, I'd like to make a record in a new logins table, and then let them continue on to the dashboard. Where's the right place to add this step? At first I was thinking I could change the LOGIN_REDIRECT_URL to some other step (and then have that proceed to dashboard), but what I want isn't really a url.... not sure if middleware would be more appropriate? OR is there some way to sort of extend the login code … -
Django - inline formset validation
I'm trying to validate my inline formset cost value's to make sure that it adds up to 100. The formset is returned 5 times so foreach the value should be added until 100 is hit. If it's more or less than that show an error & not allow the user to hit the create button. Models.py class EstimatedBudgetForm(forms.ModelForm): def clean(self): # get forms that actually have valid data count = 0 for percentage in self.cost: try: if percentage.cleaned_data: count += percentage except AttributeError: # annoyingly, if a subform is invalid Django explicity raises # an AttributeError for cleaned_data pass if count != 100: raise forms.ValidationError('Percentage must equal 100%') Views.py EstimatedBudgetChildFormset = inlineformset_factory( Project, EstimatedBudget, fields=('project', 'item', 'cost', 'time'), can_delete=False, form=EstimatedBudgetForm, extra=5, widgets={'item': forms.Select(attrs={'disabled': True})}, ) -
image upload to server using django restful api from android app using retrofit
I have been unable to upload images from android app using retrofit to server using django api. When i try to send images from android app, no errors will be shown and it also does not hit the server but using postman it works perfectly fine. What could be the reasons behind it? -
fix error 404 image not found django-allauth
i have add custom model for user signup and i add Imagefield so when user upload his photo during signup its work and uploaded to my folder but when i try to get image for user and display photo in profile page it's say GET /images/modern-mosaic-wallpaper-rose-gold-black_53876-58064.jpg HTTP/1.1" 404 4835 my code | models.py : class User(AbstractUser): user_pic = models.ImageField(upload_to='images/',null=True, blank=True) forms.py : class CustomSignupForm(SignupForm): first_name = forms.CharField(required=True,label='First Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter First Name '}) ) last_name = forms.CharField(required=True,label='Last Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter Second Name '}) ) user_pic = forms.ImageField(required=True,label='Your photo') def save(self, request): user = super(CustomSignupForm, self).save(request) user.user_pic = self.cleaned_data['user_pic'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return user profile_page.html : <img src="{{user.user_pic}}" style="width:100%;height:100%"> settings.py : ACCOUNT_FORMS = { 'signup': 'blog_app.forms.CustomSignupForm', } AUTH_USER_MODEL = 'blog_app.User' everything work , the image successfully uploaded but i cant get image for user it says error 404 not found but the image already in images folder how to display image for user ? -
How to cumsum two models related by an intermediate model using Django ORM
Problem Let's say I have one table called Price which is a timeseries with a timestamp, a value and the difference of previous day. To simplify the table I have put only the dates not the hours, mins, etc.: timestamp value difference 2021-01-21 500 500 2021-01-22 1000 500 2021-01-23 1500 500 2021-01-24 2000 500 2021-01-25 2500 500 Those values might be incorrect and a user might correct it at any point in time using a second table called CorrectedPrice. A user can correct the start value even before the date of the first Price value: timestamp value 2021-01-15 1000 2021-01-23 500 By merging those two informations the resulting queryset between date 2021-01-22 and 2021-01-26 should be: timestamp value 2021-01-21 1500 2021-01-22 2000 2021-01-23 1000 2021-01-24 1500 2021-01-25 2000 Django Models We have a Stock model: class Stock(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.Charfield(unique=True) A Price model: class Price(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) value = models.IntegerField() difference = models.IntegerField() # done with a signal on pre_save timestamp = AutoCreatedField() stock = models.ForeignKey(Stock, on_delete=models.CASCADE) and then we have the CorrectedPrice model: class CorrectedPrice(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) value = models.IntegerField() timestamp = AutoCreatedField() stock = models.ForeignKey(Stock, on_delete=models.CASCADE) What … -
Getting error "SuspiciousFileOperation" after Django Version Update Django: 3.1.9 from Django: 3.1.8
I am getting this error after updating to Django: 3.1.9, on Django: 3.1.8 it works fine. I have a Files model with a FileField as below: class JobFiles(BaseModel): category = models.CharField(max_length=50, choices=FILE_CATEGORY) job_file = models.FileField('JobFile', upload_to=user_directory_path) I specified the upload_to option so that it gets uploaded differently per Category: def user_directory_path(instance, filename): import uuid if not instance.job_file_name: instance.job_file_name = filename if instance.category == 'Job Card': return f'job_card/{uuid.uuid4()}' if instance.category == 'Photos': return f'job_card/photos/{uuid.uuid4()}' if instance.category == 'Other': return f'job_card/other/{uuid.uuid4()}' return f'job_card/other/{uuid.uuid4()}' The code generating the error (double checked the file exists and it is wrapped in a file object): from django.core.files import File def test() job_files = job_card.job_card_file or JobFiles(category='JobCard') # Get path to a temp file that was processed (existence and other checks already done) doc = '/tmp/mergedfile.pdf' with open(doc, mode='rb') as f: job_files.job_file = File(f) job_files.save() The error I am getting: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/code/job_cards/views.py", line 311, in job_card_maintenance_create job_files.save() File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 790, in save_base updated … -
How can use exclude query in django
I have 2 table orderProduct and orderRequest i want to exclude that order from orderProduct table which are in the orderRequest table, but it show the error 'ForwardManyToOneDescriptor' object has no attribute 'orderProduct' Models.py class OrderProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) description = models.CharField(max_length=90) quantity = models.IntegerField() order_cancel = models.BooleanField(default=False) class OrderRequest(models.Model): order_status = models.CharField(max_length=10) order = models.ForeignKey(Order, on_delete=models.CASCADE) view.py class OrderProduct_View(TemplateView): template_name = 'purchase/orderProduct.html' def get(self, request, *args, **kwargs): checkOrder = OrderRequest.objects.exclude( orderProduct_id__in=OrderRequest.order.orderProduct ) args = {'checkOrder': checkOrder} return render(request, self.template_name, args) -
How to add a user input folder in my webpage so that they can put notes inside it?
I am working on a web notes app. I want to create a folder based on user input so that they can manage what types of notes they want to put in it. Like in a usual notes app. Website layout: -
How to test a view that requires a user to be authenticated in Django?
I have the following view that requires a user to be authenticated to access it, otherwise redirects to the login page: In my urls.py file: from . import views urlpatterns = [ path("settings", login_required(views.Settings.as_view()), name="settings"), ] In my views.py file: class Settings(View): def get(self, request): return render(request, "project/settings.html") How can I test this view? Here is what I tried: class TestViews(TestCase): def setUp(self): self.user = User.objects.create( username="testUser", password="testPassword", ) def test_settings_authenticated(self): client = Client() client.login(username="testUser", password="testPassword") response = client.get("/settings") self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, "project/settings.html") But this returns a 302 status, implying the user was not authenticated. -
Setting up Heroku Postgres from SQLite3 at Django
I have recently hosted my CRM System at heroku. But since I was only using SQLITE3, the database encounters errors at heroku. how will I setup my settings.py to fix this? I have updated settings.py yet it shows NameError: name 'os' is not defined but whenever I put import os, it shows: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte please help me, here is the code for my settings.py: from pathlib import Path import os import django_heroku import dj_database_url import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. # BASE_DIR = Path(__file__).resolve().parent.parent # This line should already exist in your settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # This is new: dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # 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 = 'm)3ag$=da^%ifkti+u!rg@!x3b_%my$*#6vorp1!@vdy!i^i*!' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Thrid party apps 'crispy_forms', "crispy_tailwind", # Local apps 'clients', 'agents' ] 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', … -
Facebook Login By Using Custom User Model Django
I have a custom User model named Account. I have an activation system so by default is_active is False. In manual login, users receive an e-mail address for an activation link then login to their account. But also I added social media login. I use django-allauth for that. When I login with facebook, it says that user is inactive because my is_active is set to False by default. How can I solve this question and make the social account user to login to the website without any problem? Can i set the is_active=True only for social media users? or do i have to do something else? -
Can I add a form in django html?
I want to add comments form a specific html which has it's own views and models and I do not want to create a new html file like comment.html which will only display the form and its views. I want users to be able to comment right underneath a post, so that users don't have to click a button such as "add comment" which will take them to a new page with the "comment.form" and then they can comment. But I'm stuck. I can add comments manually from the admin page and it's working fine, but it seems that I have to create another url and html file to display the comment form and for users to be able to add comments(btw I'm trying to build a sports related website). Thanks in advance! My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py : class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) My views.py : def addcomment(request): model = Comment form_class = CommentForm template_name … -
Data doesn't get submitted to database from Django forms using classed based views
I'm am trying to make a registration page for Companies and the whole flow is working fine using froms in Django. Though when I fill out the form with data and hit submit it redirects me to my index page and doesn't show any error. But when I check the database in /admin the object/data is not submitted. Any idea what the "error" could be? I'm using class based views and I've added my model in admin.py admin.site.register(Company) My urls.py path looks like this: path('createCompanyProfile/', CompanyFormView.as_view(), name = "createCompanyProfile"), models.py: class Company(models.Model): companyName = models.CharField(max_length = 145) description = models.TextField() websiteURL = models.CharField(max_length = 100) relationToDjango = models.TextField() phoneNumber = models.CharField(max_length = 11) email = models.CharField(max_length = 100) mainContact = models.CharField(max_length = 50) streetName = models.CharField(max_length = 45) houseNumber = models.CharField(max_length = 25) postalCode = models.CharField(max_length = 4) region = models.CharField(max_length = 45) def __str__(self): return '{} {} {} {} {} {} {} {} {} {} {}'.format(self.companyName, self.description, self.websiteURL, self.relationToDjango, self.phoneNumber, self.email, self.mainContact, self.streetName, self.houseNumber, self.postalCode, self.region) class CompanyForm(ModelForm): class Meta: model = Company fields = '__all__' views.py: class CompanyFormView(FormView): model = Company template_name = "company/createCompanyProfile.html" form_class = CompanyForm success_url = '/' def form_valid(self, form): return super(CompanyFormView, self).form_valid(form) createCompanyProfile.html <form …