Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax post data don't arrive to Django
I am developing a Django application. I am trying using jquery and ajax for a POST request but I am not able to find the error. I am basically struggling to send the data from the frontend with ajax to the server. views.py def add_new_question_feedback(request, pk): if request.headers.get('x-requested-with') == 'XMLHttpRequest': question = Question.objects.get(id=pk) feedback = QuestionFeedback( question=question, user=request.user, text=request.POST.get('feedback'), feedback_choice=request.POST.get('feedback_choice')) feedback.save() feedback = serializers.serialize('json', [feedback]) return HttpResponse(feedback, content_type='application/json') models.py class QuestionFeedback(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) text = models.TextField() feedback_choice = models.CharField( max_length=200) is_closed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) template <div class="modal-header"> <h5 class="modal-title">${gettext( "Question Feedback" )} n° ${res[0].pk}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="form-group mt-3"> <label class="form-label">${gettext( "Feedback Type" )}</label> <select name="feedback_choice" id="feedback_choice" class="form-control" required=""> <option value="" selected="" disabled>${gettext( "Select Topic" )}</option> <option value="Wrong Question">${gettext( "Wrong Question" )}</option> <option value="Wrong Answer">${gettext( "Wrong Answer" )}</option> <option value="Other">${gettext( "Other" )}</option> </select> </div> <div class="form-group mt-3"> <label class="form-label">${gettext( "Feedback" )}</label> <textarea name="feedback" id="feedback" rows="10" class="form-control"></textarea> </div> <button type="button" class="btn btn-success mt-3" id="addFeedback"> ${gettext( "Add New Feedback" )} </button> <button type="button" class="btn btn-danger mt-3 ms-3" data-bs-dismiss="modal">${gettext( "Close" )}</button> </div> `; ajax function $("#addFeedback").on("click", function () { $.ajax({ type: "POST", url: "/quiz/add_new_question_feedback/" + questionBtnId, … -
Django IntegrityError : null value in column violates not-null constraint but there is a value in the request
I have a form that tries to add a record in a database using django. When trying to save into the database, i get the error IntegrityError: null value in column "aid" violates not-null constraint, but when I look at the request, I can clearly see a non-null value for the column 'aid' aid '10' uid '2' rid '13' action '' time '' table '' When I print the request.data inside views.py I can see all the values from the request: <QueryDict: {'aid': ['10'], 'uid': ['2'], 'rid': ['13'], 'action': [''], 'time': [''], 'table': ['']}> My question is why django cannot find the PK column> -
Current user does not show up in form from ModelForm whilst relationship has been established in Django
I have two models defined, a Test model and a User model. The Test model relates to the User model with a ForeignKey. The Test model has many different aspects to it, so I have truncated it, but I make a form of it with ModelForm. Then I call the form, and indeed all the entries show up, including a cell for User, however it shows no options or pre-selection for current user. What am I doing wrong? #User as rendered in form in browser: <select name="researcher" id="id_researcher"> <option value="" selected>---------</option> models.py from django.db import models from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) class User(AbstractBaseUser): is_active = models.BooleanField(default=True) def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ full_name = "%s %s" % (self.first_name, self.last_name) return full_name.strip() @property def is_staff(self): "Is the user a member of staff?" return self.staff @property def is_admin(self): "Is the user a admin member?" return self.admin class Test(models.Model): researcher = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="researcher") views.py from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views.generic.edit import CreateView, UpdateView, DeleteView from database.forms import TestForm from database.models import User, Test # Create your … -
Django Many To Many Ordering
I have two tables Subjectlist and Day. Subject list is m2m in Day. So my problem is I'm creating school timetable. So for each days different subjects to be shown, when i add subjects on each days the order of subject is same. #Models.py class SubjectList(models.Model): subject_name = models.CharField(max_length=25) def __str__(self): return self.subject_name class Day(models.Model): day_name = models.CharField(max_length=15) subject_name = models.ManyToManyField(SubjectList) class_number = models.ForeignKey(AddClass, on_delete=models.CASCADE, null=True, blank=True) start_time = models.TimeField(null=True, blank=True) end_time = models.TimeField(null=True, blank=True) def __str__(self): return self.class_number.class_number #Views.py class TimeTableView(APIView): def get(self, request, id): class_number = AddClass.objects.get(id=id) day = Day.objects.filter(class_number=class_number.id) print(day) serializer = DaySerializer(day, many=True) return Response(serializer.data) I want to do like this Monday - English, maths, science, Social Science Tuesady - Maths, Social Science, Englih, Math's but i get like this Monday - English, maths, science, Social Science Tuesday- English, maths, science, Social Science both are in same order even if add subjects in different order. -
Save data from Oracle to sql server using django webpage or python script
I need a short and fast method to copy oracle table to sql server because tables are too large. I have only one model of mssql. models.py class ReceiveMt_sql(models.Model): rcv_no = models.CharField(db_column='RCV_NO', max_length=30, blank=True, null=True) rcv_date = models.CharField(db_column='RCV_DATE', max_length=100, blank=True, null=True) vendor_code = models.CharField(db_column='VENDOR_CODE', max_length=12, blank=True, null=True) rcv_invoice = models.CharField(db_column='RCV_INVOICE', max_length=30, blank=True, null=True) rcv_type = models.CharField(db_column='RCV_TYPE', max_length=1, blank=True, null=True) paid_unpaid = models.CharField(db_column='PAID_UNPAID', max_length=1, blank=True, null=True) print_status = models.CharField(db_column='PRINT_STATUS', max_length=1, blank=True, null=True) user_name = models.CharField(db_column='USER_NAME', max_length=10, blank=True, null=True) u_id = models.CharField(db_column='U_ID', max_length=15, blank=True, null=True) mod_date = models.CharField(db_column='MOD_DATE', max_length=100, blank=True, null=True) width = models.CharField(db_column='WIDTH', max_length=20, blank=True, null=True) length1 = models.CharField(db_column='LENGTH1', max_length=20, blank=True, null=True) remarks = models.CharField(db_column='REMARKS', max_length=300, blank=True, null=True) chtype = models.CharField(db_column='CHTYPE', max_length=50, blank=True, null=True) general_type = models.CharField(db_column='GENERAL_TYPE', max_length=30, blank=True, null=True) action = models.CharField(db_column='ACTION', max_length=1, blank=True, null=True) gate_no = models.CharField(db_column='GATE_NO', max_length=30, blank=True, null=True) save_date = models.CharField(db_column='SAVE_DATE', max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'RECEIVE_MT' views.py class RcvMr(View): def get(self, request): cursor = connections['ORACLE'].cursor() sql = "SELECT * FROM receive_mt WHERE rcv_date>='01-SEP-22'" stmt = cursor.execute(sql) rows = [dict((cursor.description[i][0], value) for i, value in enumerate(row)) for row in cursor.fetchall()] for row in rows: #get data from row and save it to the model print(row) return render(request, 'service.html') -
Please, how do I write a try and except code for a password validation; such that each validation returns its own message to the user?
views.py The issue I have is on the signup function view. What do I write inside the except block to show an error message to the user according to the validationError given. for example: if the error is "Common Password" it should only display common password message to the user and if it is other errors, it should do the same for their independent messages to the user. Thank you in advance. from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout #from django.contrib.auth.models import User from django.core.mail import send_mail from .models import User from django.contrib.auth.password_validation import validate_password,UserAttributeSimilarityValidator,CommonPasswordValidator,MinimumLengthValidator,NumericPasswordValidator # Create your views here. def signup(request): if request.method == "POST": username = request.POST.get("username") fname = request.POST.get("fname") lname = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") password2 = request.POST.get("password2") if password: try: new = validate_password(password,password_validators=None) except: messages.error(request, ) return redirect('home') #if User.objects.filter(email=email): #messages.error(request, "E-mail already exist!") #return redirect('home') #if len(username) > 15: #messages.error(request, "Length of username too long!") #return redirect('home') #if password != password2: #messages.error(request, "Passwords do not match!") #return redirect('home') #if not password.isalnum(): #messages.error(request, "Password must be alphanumeric!") #return redirect('home') user = User.objects.create_user(username=username,first_name=fname,last_name=lname,email=email,password=password) # Welcome E-mail #subject = 'Welcome to ADi meals mobile!' #message = 'Hello {fname}, welcome to … -
Why csrf token must be put in body for POST requests and not in headers in Django Rest Framework?
I would like to know the reason why we must put the csrf token in the body for POST requests (key csrfmiddlewaretoken) and in the headers for the others (key X-CSRFToken)? -
Exclude is not working on djnago queryset
usr_all_friends_shw = Friend.objects.filter(profile_id__in = request.user.profile.friends.all()) uzr_al_cnfr_frn = FriendRequestSave.objects.filter(receiver_request=request.user.profile) sugges= Friend.objects.exclude(profile_id__in=usr_all_friends_shw).exclude(profile_id=request.user.pk) for i in uzr_al_cnfr_frn: bdhc63=Friend.objects.filter(profile_id=i.sender_request.pk) print(bdhc63) sugestion_aftr=sugges.exclude(profile_id__in=bdhc63) It does not show any error but still not excluding elements -
how to use a model field as the default for another field Django?
I want to use a field in a model as the default for a field in a different model. I try to reference the field but when I try to make migrations I'm getting a can't serialize error. Any help would be really appreciated. models.py(look at current bid under Bids) class Auctions(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=200) startingBid = models.IntegerField(max_length=6) currentBid = models.ForeignKey('Bids', on_delete = models.CASCADE, blank=True, null=True) images = models.ImageField(upload_to='images') catagory = models.CharField(max_length=50) closed = models.BooleanField(default=False) sellor = models.ForeignKey(User, models.CASCADE) class Bids(models.Model): auction = models.ForeignKey(Auctions, on_delete = models.CASCADE) currentBid = models.IntegerField(blank=True, null=True, default=Auctions.startingBid) user = models.ForeignKey(User, on_delete = models.CASCADE) error ValueError: Cannot serialize: <django.db.models.query_utils.DeferredAttribute object at 0x7fed612c7250> -
Django function view rewriting to Class View ListView problem with Tag
Im trying to rewrite my whole app from function views to class views. Right now Im struggle with Tag. This how its looks before views.py def tagged(request, slug): tag = get_object_or_404(Tag, slug=slug) articles = Article.objects.filter(tag=tag) paginator = Paginator(articles, 5) page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) context = { "tag": tag, "page_obj": page_obj, } return render(request, "web/home.html", context) And right now Im trying rewrite it to Class View but I dont know how to use get_object_or_404 in class and then filter my model Article by tag class Tagged(ListView): model = Article paginate_by = 5 model.py class Article(models.Model): headline = models.CharField(max_length=100) article_content = models.CharField(max_length=10000) article_author = models.ForeignKey(User, on_delete=models.CASCADE) article_photos = models.URLField(blank=True, max_length=300) yt_links = models.URLField(blank=True, max_length=300) article_image_upload = models.ImageField(blank=True, upload_to="images/") slug = models.SlugField(null=True, unique=True, max_length=100) tag = TaggableManager(blank=True) likes = models.ManyToManyField(User, related_name="article_likes") timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): return { "id": self.id, "headline": self.headline, "article_content": self.article_content, "article_author": self.article_author, "article_image_upload": self.article_image_upload, "tag": self.tag, "yt_links": self.yt_links, "likes": self.likes, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), } -
Django imagefield isn't showing any photo in the template
I'm working on a bookstore using Django. I'm trying to save each book's cover in each book created by the user using imagefield. I implemented every step in Django documentation about using imagefield but it doesn't work. settings.py(in main project): MEDIA_DIR = os.path.join(BASE_DIR,'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' in urls.py (main project): from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include("book.urls")), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in models.py(the book app): class books(models.Model): cover = models.ImageField(upload_to='cover/co', blank=True) When I want go admin I find that the photo is submitted (when I click on the photo url in database nothing is shown to me) but I don't find any created media folders and when I try to request the image in any template It isn't showed to me. when I try to click on the photo in the database in admin this is shown to me: enter image description here These are the paths of the app, project and static: enter image description here I don't know where is the problem and how to solve it as this is my first time to use imagefiled in django model,,, … -
HTML is not rendering properly in Django
I am Naive in Django and HTML and trying to build an App using django. I got to know about the website getbootstrap.com . And I was trying to render the dropdown button from there in my index.html file. The code for the Dropdown button is as follows. <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown button </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </div> And I am expecting a button like below: But I am getting the The button as follows: I want to know where I am going wrong? -
how to solve django.db.utils.NotSupportedError in django
I got an error while running the project in Django. the thing is that unfortunately i upgraded my pip , MySQL client and Django versions this is the error while running python manage.py run server in check_database_version_supported raise NotSupportedError( django.db.utils.NotSupportedError: MariaDB 10.3 or later is required (found 10.1.19). -
show images that are related to django model in admin
I have a Book Model and BookImages model. Book is not related to Images directly ,instead BookImages has Book as foreign key and a Book can have many images. I want to show Book details along with images related to book in admin panel but here Book doesnt have any relation to BookImages. Instead BookImages points to Book Model. How can i show admin view with Book details and all Book Images. Below is exact model code. class Book(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length = 5000) class BookImage(models.Model): book = models.ForeignKey('Book', on_delete=models.CASCADE) image = models.ImageField(upload_to=settings.MEDIA_RELATIVE_ROOT + "/bookimages") Python version is 3.7.12 and django version is 3.2.14 -
List of arrivals, per year
I have these three models (I've summarize them): class Tourist(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Etablissement(models.Model): name = models.CharField(max_length=30) class Arrival(models.Model): tourist = models.ForeignKey(Tourist, on_delete=models.CASCADE) place = models.ForeignKey(Etablissement, on_delete=models.CASCADE) I want, for a Tourist, to have all his arrivals, per year. I've tried this: def detailTourist(request, id): touriste = Tourist.objects.get(id=id) datas = Arrival.objects.annotate(year=TruncYear('arrival_date')).values('year').annotate(total=Arrival.objects.filter(tourist=touriste)).order_by() but it give me an error: sub-select returns 19 columns - expected 1 (the arrival model has 19 field so i guest that's why it says 19. So finnaly, how can I do it please ? -
How to restrict ManyToManyField in ModelViewSet for no super users?
I have 2 models linked by a ManyToManyField relationship. class Site(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Device(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(blank=True, null=True) users = models.ManyToManyField(User, related_name='devices', blank=True) site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='devices') class Meta: verbose_name = "Device" verbose_name_plural = "Devices" ordering = ['name'] def __str__(self): return self.name My Viewset: class SiteViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = (permissions.IsAuthenticated,) serializer_class = SiteSerializer def get_queryset(self): if self.request.user.is_superuser: return Site.objects.all().prefetch_related("devices") else: return Site.objects.filter( devices__users=self.request.user ).prefetch_related("devices").distinct() My Serializers: class SiteDeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = ('id', 'name', ) class SiteSerializer(serializers.ModelSerializer): devices = SiteDeviceSerializer(many=True, read_only=True) class Meta: model = Site fields = "__all__" If I access my view with a superuser, it works well I have all the results. Example: "results": [ { "id": 1, "devices": [ { "id": 1, "name": "test 1" }, { "id": 2, "name": "test 2" } ], "name": "Site test 1" }, { "id": 2, "devices": [ { "id": 3, "name": "Test 3" } ], "name": "Site test 2" } ] I have created another user user1 who is not a super user. I also added this user in the users of the device test 1. When I access the view with this user I … -
raise InvalidSchema(f"No connection adapters were found for {url!r}") in Django API call
I am trying to call an API in Django and I have the following code: @csrf_exempt def intasend_webhook_view(request): if request.method == "POST": payload = request.body response = requests.get(payload) intasend_body = json.loads(response) api_ref = intasend_body.get("api_ref") state = intasend_body.get("state") order = Order.objects.get(pk=api_ref) if state == "FAILED": order.payment_status == "Unpaid" order.save() elif state == "COMPLETED": order.payment_status == "Paid" order.save() return JsonResponse('success', safe=False) What I am basically doing is that I want to change the order status to "Paid" once the payment collection event is called and returns "COMPLETED" status. When I try to perform a test transaction, I get the following error in my shell: raise InvalidSchema(f"No connection adapters were found for {url!r}") requests.exceptions.InvalidSchema: No connection adapters were found for '{"invoice_id": "VYBP5OQ", "state": "FAILED", "provider": "CARD-PAYMENT", "charges": "0.00", "net_amount": "84.00", "currency": "USD", "value": "84.00", "account": "email@outlook.com", "api_ref": "2", "mpesa_reference": null, "host": "http://127.0.0.1:8000", "failed_reason": null, "failed_code": null, "failed_code_link": "https://intasend.com/troubleshooting", "created_at": "2022-10-28T11:55:40.755353+03:00", "updated_at": "2022-10-28T11:55:54.504547+03:00", "challenge": "123"}' [28/Oct/2022 11:55:54] "POST /webhooks/intasend/ HTTP/1.1" 500 97938 I am one year into django programming and I don't know much about APIs. For example, the response above needs to indicate the order is "Unpaid" because the "state" of the transaction is "FAILED" Anyone who can help me to proceed from … -
my previously working projects no longer work
I was writing a project with django, but my projects are not opening, not a single project, almost all projects are on a pc, I don't know why, django installed python installed, all projects were working without any problems before, the error is one by one line errors as below, but I would be glad if you could help in all projects like this I was save my projects on cloud I download them and still doesn't work -
How can I connect different class instances based on their ids?
I have the two following classes: class Position(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() price = models.FloatField(blank=True) created = models.DateTimeField(blank=True) def save(self, *args, **kwargs): self.price = self.product.price * self.quantity return super().save(*args, **kwargs) def __str__(self): return f"id: {self.id}, product: {self.product.name}, quantity: {self.quantity}" class Sale(models.Model): transaction_id = models.CharField(max_length=12, blank=True) positions = models.ManyToManyField(Position) total_price = models.FloatField(blank=True, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) salesman = models.ForeignKey(Profile, on_delete=models.CASCADE) created = models.DateTimeField(blank=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"Total sales price: ${self.total_price}" def get_absolute_url(self): return reverse('sales:detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): if self.transaction_id == '': self.transaction_id = generate_code() if self.created is None: self.created = timezone.now() return super().save(*args, **kwargs) def get_position(self): return self.positions.all() How can I relate each position instance with its related sale instance? I've tried implementing this method: def get_sales_id(self): sale_obj = self.sale_set.first() return sale_obj.id but in this case I will always get the first id of a determined position occurrence. Exaple: pos1: id 1, product, quanity, price ... pos2: id 2, product, quantity, price ... sale1: pos 1, pos 2 ... sale2: pos 1, pos3 ... When I try to merge these, based on the sale id, I get: pos1: id 1, ... , sale_id 1 pos1: id 1, ... , sale_id 1 … -
How can I export Qr code as an images to an excel export in Python and Django
I am trying to create a utility to export Qr code images to an excel file for tagging. I am using qrcode library to generate QR codes and openpyxl library to create the spreadsheet file. So far the spreadsheet export works great without the Qr code column however as soon as i add the code to add qr code to the excel column, my server crashes and stops without any verbose message. Below is my working code snippet without the qr code snippet: import openpyxl from openpyxl import Workbook from openpyxl.styles import Font, Alignment, Border, Side, PatternFill from openpyxl.utils import get_column_letter from openpyxl.styles.colors import BLACK def process_tagging_export(queryset): response = HttpResponse(content_type='application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet',) response['Content-Disposition'] = 'attachment; filename=QR_Code_Tags.xlsx' workbook = Workbook() workbook.remove(workbook.active) header_font = Font(name='Calibri', bold=True) centered_alignment = Alignment(horizontal='center') borders = Border(bottom=Side(border_style='medium', color='FF000000'),top=Side(border_style='medium', color='FF000000'),right=Side(border_style='medium', color='FF000000'),left=Side(border_style='medium', color='FF000000'),) wrapped_alignment = Alignment(vertical='top',wrap_text=True) columns = [ ('Asset Code', 30), ('Asset Name', 30), ] worksheet = workbook.create_sheet( title="QR Code Tags", index=1, ) row_num = 1 fill = PatternFill( start_color='b3b3b3', end_color='b3b3b3', fill_type='solid', ) for col_num, (column_title, column_width) in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title cell.font = header_font cell.border = borders cell.alignment = centered_alignment cell.fill = fill column_letter = get_column_letter(col_num) column_dimensions = worksheet.column_dimensions[column_letter] column_dimensions.width = column_width for item … -
How to add test data into django admin using a script
I am currently trying to create script where once the data has been deleted from django admin, we can add the data into database again for testing purposes. In django when we are adding data, we need to fill every field in django admin but what i want is a script in which I have some test data and when I run, it automatically adds it to the database without the need of django admin. How can I achieve this? -
Rrrule for reccurence
i am using dateutil module rrule ical (https://dateutil.readthedocs.io/en/stable/index.html) in Django for handling date related recurrence. my question is how we can calculate any indication that we give this number of occurrence already done and this number of recurrence remaining. Suppose a person created some recurrence visit in their home town. start date :-- 28/10/2022 freq:-- monthly end date:-30/12/2022 we have rrule count for calculating total number of visit. but my problem is that i want to calculate it dynamicaly like after 30/11/2022 i want some rule that give me the remaining visit :-1 and already done visit 2. thanks total_number_of_visit = rule.count() upcoming_visit = total_number_of_visit- ??? -
it's shows for each and every project - RemovedInDjango30Warning,
can someone tell me how to solve this problem , raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'django.contrib.admin.templatetags.admin_static': cannot import name 'RemovedInDjango30Warning' from 'django.utils.deprecation' (C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py) At first we try to save data's at sqlite3 it works , but few day's back we try to create discussion form and store the data's in sqlite3 it's shows an error continuously for each and every project , can someone give me a guidance to solve this ...... -
KeyError: 'DB_NAME' when doing makemigrations in django
I store all my secrets and database params in the dev.env file. I have 3 different settings files - base, dev and prod. There is an SQLite database in base, and I want to connect to Postgres in dev. So I upload my secrets with the environment variable like this: from dotenv import load_dotenv load_dotenv(os.environ.get('ENV_CONFIG', '')) And I override my database settings in dev settings file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': os.environ['DB_HOST'], 'PORT': os.environ['DB_PORT'], } } But when I run makemigrations with dev settings file: ./manage.py makemigrations --settings=app.settings.dev I get an error: File "/Users/admin/Desktop/Programming/Python/UkranianFunds/src/app/settings/dev.py", line 35, in <module> 'NAME': os.environ['DB_NAME'], File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DB_NAME' I checked and my secret with the key DB_NAME clearly appears in the settings file - I printed it successfully. The name of the database is correct. What are other reasons that cause that? -
The view products.views.get_product didn't return an HttpResponse object. It returned None instead
Here is my code, I am getting the same error again and again. def add_to_cart(request,uid): variant=request.GET.get('variant') product=Product.objects.get(uid=uid) user=request.user cart=Cart.objects.get_or_create(user=user, is_paid=False) cart_item=CartItems.objects.create(cart=cart,product=product) if variant: variant=request.GET.get('variant') size_variant=SizeVariant.objects.get(size_name=variant) cart_item.size_variant=size_variant cart_item.save() return HttpResponseRedirect(request.META.get('HTTP_REFFER')) ValueError at /product/tommy-hilfiger-blue-jeans The view products.views.get_product didn't return an HttpResponse object. It returned None instead. Request Method: GET Django Version: 4.0.4 Exception Type: ValueError Exception Value: The view products.views.get_product didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\MyPc\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 332, in check_response Python Executable: C:\Users\MyPc\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.7