Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send form informations between pages in DJANGO
I have a problem with my Django application. What I want to do, in theory, is simple, but I'm not getting it. I am working with "CLASS BASED VIEWS". What I want to do is the following, I intend to have a page with my form, so when the user clicks on the button to submit the information Django has to perform some mathematical calculations with the information that was on the form and, after calculating everything, should redirect the user to a new page with the result of the calculations. Would someone give me a light on how to do this? Below is a graphic example of the process. CLICK TO SEE THE PROCESS Algorithm: Capture information using form - VIEW 01 / TEMPLATE 01 Perform some mathematical calculations with submitted information Show results on another page - VIEW 02 / TEMPLATE 02 -
google cloud build error: --substitutions flag not found
I am trying to follow the tutorial from google to run a django project on Cloud Run (https://cloud.google.com/python/django/run). I've worked my way down to actually building my container by running: gcloud builds submit --config cloudmigrate.yaml --substitutions _INSTANCE_NAME=INSTANCE_NAME,_REGION=REGION However, it continues to fail with a mysterious error: ERROR: (gcloud.builds.submit) build b1cc40a4-93e5-4935-8838-0ec2f4f9a764 completed with status "FAILURE" zsh: command not found: --substitutions As far as I can tell, the syntax is exactly as specified in the documentation. I've also run the command in bash with the same result. Is there maybe something wrong with my gcloud SDK install? Many thanks in advance for help. -
django-bootstrap-v5 DecimalField Throwing Errors in ModelForm Class
Using the django-bootstrap-v5 module, I get the error: "init() got an unexpected keyword argument 'attrs'" on a DecimalField Widget in the definition of a ModelForm class for a simple Model. The Model is defined as follows: class MenuItem(models.Model): menuname=models.CharField(max_length=20,primary_key=True) description=models.TextField() price=models.DecimalField(max_digits = 5, decimal_places = 2) And the Model Form is defined as follows: class MenuItemForm(forms.ModelForm): class Meta: model=MenuItem fields='__all__' widgets = {'menuname': forms.TextInput(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'class': 'form-control'}), 'price': forms.DecimalField(attrs={'class': 'form-control'}), } The error is thrown on the Line: 'price': forms.DecimalField(attrs={'class': 'form-control'}), If I change that line to: 'price': forms.TextInput(attrs={'class': 'form-control'}), Then no error it thrown. But of course I would rather use a DecimalField widget rather than a TextInput to render the underlying DecimalField in the model. Once again this is using the django-bootstrap-v5 module. Any Ideas? -
Title being displayed both in browser's bar and in body in Django
I am following the book "Django By Example" and I tried to implement tags. I expect the title to be shown only on the browser's title bar. However, the text inside is being displayed both on the browser's title bar but also on the webpage content. If I look at the page source, of that screenshot, it looks like this: </nav> Title goes here <div class="container"> And here is how the first lines of my base.html look like: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %} {% endblock %}</title> And here is the template of the page shown in the screenshot: {% extends 'base.html' %} {% block content %} {% block title %} Title goes here {% endblock %} <div class="container"> <div class="row"> <div class="col-md-8 card mb-4 mt-2 left top"> <div class="card-body"> <div class=""> Here is some content. </div> </div> </div> {% block sidebar %} {% include 'sidebar.html' %} {% endblock sidebar %} </div> </div> {% endblock content %} Do you know how to get rid of the tile being displayed on the page body? -
Pass cropperjs output to OCR in Django
In my Django App someone uploads an image, makes a box selection, clicks the button crop and the image inside the box is cropped using fengyuachen Cropperjs. I want to pass the cropped image to an OCR (in my case I use Pytesseract. I had two independent apps (one for cropping and one for OCR and both works. Now, I want to join them). So, my questions is : How can I pass the cropped Image to the form input that is used by pytesseract to extract the information? I'm new to Javascript so I've been struggling with it. I think this images could help. Someone uploads and image, selects the cropping box and then select the button crop. The image is displayed "Someone" would click on the button Send to OCR and then Django Views recieves the input HTML and JS code <html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.11/cropper.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.11/cropper.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <h1>Upload Image to Crop</h1> <input type="file" name="image" id="image" enctype="multipart/form-data" multiple="true" onchange="readURL(this);" /> <div class="image_container"> <img id="blah" src="#" alt="your image" height="600px" width="600px" /> </div> <!--<div id="cropped_result" ></div>--> <button id="crop_button">Crop</button> {% if ....%} <!-- I am getting multivalue key error, there has to be and if statement here … -
Django complex query from relational model
Using django-rest-framework, I have simple model There is a Book which is getting translated, This book has chapters (each chapter has a name), each chapter has paragraphs. The Translation table contains foreign key to the Chapter(for chapter name) and paragraph range (from-to) because each translator can translate set of paragraphs in one translation, and the translation set can be out of order, but no overlap, for example a Translator1 can translate Chapter 3 paragraph 4 to 10, Translator2 can translate Chapter3 paragraph 20 to 30 but Translator3 cannot translate Chapter3 paragraph 9 to 20 because it leads to duplicate translation. for now this is done manually, I don't know how to set a constraint to prevent it. class Chapters(models.Model): id = models.PositiveIntegerField(primary_key=True) name_fr = models.CharField(max_length=45, db_collation='utf8_unicode_ci') name_en = models.CharField(max_length=50, db_collation='utf8_unicode_ci', blank=True, null=True) def __str__(self): return self.name_fr class TheBook(models.Model): id = models.AutoField(primary_key=True) # Field name made lowercase. chapterid = models.OneToOneField(Chapters,on_delete=models.PROTECT) # Field name made lowercase. paragraphID = models.IntegerField() # Field name made lowercase. paragraphText = models.TextField(db_collation='utf8_unicode_ci') # Field name made lowercase. def __str__(self): return self.paragraphText class Translate(models.Model): id = models.AutoField(primary_key=True) chapterid = models.ForeignKey(Chapters, to_field='id',on_delete=models.SET_NULL,null=True) parag_from = models.IntegerField(blank=True, null=True) parag_to = models.IntegerField(blank=True, null=True) translate = models.TextField(db_collation='utf8_unicode_ci', blank=True, null=True) def __str__(self): return ("{}: … -
xhtml2pdf django-cms 'sekizai.context_processors.sekizai' or use 'sekizai.context.SekizaiContext'
I am using Django-CMS, but when I try to use the xhtml2pdf example in the views.py I get this error: TemplateSyntaxError You must enable the 'sekizai.context_processors.sekizai' template context processor or use 'sekizai.context.SekizaiContext' to render your templates. If I use the example in a Django project without Sekizai no problem, any suggestions? Thanks. settings.py THIRD_PARTY_APPS = ( ... 'sekizai', ... ) base.html {% load cms_tags menu_tags sekizai_tags static i18n %} ... applications/htmltopdf_app views.py from django.shortcuts import render from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa # Create your views here. def render_pdf_view(request): template_path = 'htmltopdf_app/cv_to_pdf.html' context = {'myvar': 'this is your template context'} # Create a Django response object, and specify content_type as pdf response = HttpResponse( content_type='application/pdf' ) response['Content-Disposition'] = 'attachment; filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response ) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response -
Why Django app doesn't work on production server?
I'm trying to get django up and running on my production server but it's not working. Btw, the OS is ubuntu. I will describe everything that i did step by step, so no details are lost. So, I installed mod_wsgi: apt-get install libapache2-mod-wsgi-py3 Installed venv: apt-get install python3-venv Created venv in my django directory: sudo python3 -m venv venv Installed Django: pip install Django Then i created copy of 000-default.conf named dj.conf and populated it with the following code: <VirtualHost *:80> WSGIScriptAlias / /home/path/mysite/mysite/wsgi.py WSGIPythonHome /home/path/mysite/venv WSGIPythonPath /home/path/mysite <Directory /home/path/mysite> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Then I enabled new config and disabled old and restared server: sudo a2ensite dj sudo a2dissite 000-default.conf systemctl reload apache2 sudo service apache2 restart Then I typed ip of my server in browser address bar and I saw the default page! The same that i saw when just bought a VPS, it says "Your new web server is ready to use.". This is not even a default apache page. I also typed netstat -tulpen |grep 80 in console and it gave me this: tcp 0 0 VPS_IP:8080 0.0.0.0:* LISTEN 0 164979 88786/apache2 tcp 0 0 VPS_IP:80 0.0.0.0:* LISTEN 0 22066 773/nginx: master … -
Setting relationship with chosen model class in Django Admin interface
Problem: How to add relationship from chosen model instance to any other Django model dynamically via Django Admin interface? Description: I want to create Categories via Django Admin interface. Each Category has multiple Choices assigned to it. Choice(s) from given Category may be assigned only to objects of another specific Django class (model). Let's present a pseudocode example: class Category: category_name = models.CharField() class Choice: category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="choices") choice_name = models.CharField() class ModelWithChoosableFields: possible_categories = ... # objects of class Category selected_choices = ... # objects of class Choice class Meta: abstract = True class Book(ModelWithChoosableFields): ... class Animal(ModelWithChoosableFields): ... Category with category_name = 'Genre' has three possible Choices: choice_name = 'biography', choice_name = 'thriller' and choice_name = 'poetry'. Category with category_name = 'Animal type' has two possible Choices: choice_name = 'mammal' and choice_name = 'reptile'. Class Book may have one of the Choices from Category category_name = 'Genre' assigned. However, Choices related to category_name = 'Animal type' cannot be assigned to class Book. Analogically, class Animal can only have Choices related to category_name = 'Animal type' assigned to it. In other words, in Admin panel for instance of class Book I want to have a way of … -
Django forms is_valid() for registration, always false
I'm still learning django and I'm trying to create a register and login page. I beleive i created the form right, and the .is_valid() looks good to me also, I have no idea what i did wrong. every time I submit the register form, it fails and renders the else condition, same with the login function, even thought I went into admin to add a user manually. my user model is called 'Users' Forms: class reg_form(forms.Form): username = forms.CharField(label='username', max_length=64) password = forms.CharField(widget=forms.PasswordInput) email = forms.EmailField(label="email", max_length=64) phone = forms.CharField(label='Phone', max_length=64) first_name = forms.CharField(label='First Name', max_length=64) last_name = forms.CharField(label='Last Name', max_length=64) class log_form(forms.Form): username = forms.CharField(label='username', max_length=64) password = forms.CharField(widget=forms.PasswordInput) Register: def register(request): if request.method == 'POST': form = reg_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] user = Users.objects.Create(username=username, email=email, password=password, phone=phone, first_name=first_name, last_name=last_name) Users.save(user) login(request, user) return render(request, 'profile.html') else: return render(request, 'register.html', { 'form': reg_form }) else: return render(request, 'register.html', { 'form': reg_form }) login: def log_in(request): if request.method == 'POST': form = log_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) … -
Pagination of search results only in Django not working
I have implemented a search bar and function into a django web app in the following view: def search_products(request): search_query = request.GET.get('search', '') products = Product.objects.filter(Q(name__icontains=search_query) | Q(brand__icontains=search_query)) paginator = Paginator(products, 40) page_number = request.GET.get('page', 1) page = paginator.get_page(page_number) if page.has_next(): next_url = f'?page={page.next_page_number()}' else: next_url = '' if page.has_previous(): prev_url = f'?page={page.previous_page_number()}' else: prev_url = '' return render(request, 'store/search_products.html', context={'products': page.object_list, 'page': page, 'next_page_url': next_url, 'prev_page_url': prev_url}) The URLs are setup as follows: urlpatterns = [ path('', views.store_view, name='store'), path('wishlist/', views.wishlist_view, name='wishlist'), path('update_item/', views.updateItem, name='update_item'), path('search_products/', views.search_products, name='search_products'), ] And the HTML for the search results is as follows: <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item {% if not prev_page_url %} disabled {% endif %}"> <a class="page-link" href="{{ prev_page_url }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% for n in page.paginator.page_range %} {% if page.number == n %} <li class="page-item active" aria-current="page"> <a class="page-link" href="?page={{ n }}">{{ n }} <span class="sr-only"></span> </a></li> {% elif n > page.number|add:-4 and n < page.number|add:4 %} <li class="page-item"> <a class="page-link" href="?page={{ n }}">{{ n }}</a> </li> {% endif %} {% endfor %} <li class="page-item {% if not next_page_url %} disabled {% endif %}"> <a class="page-link" href="{{ next_page_url }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> … -
Django Annotate ExpressionWrapper Does not Return Expected Type
I have the following models: class Creditor(models.Model): terms_of_payment = models.IntegerField( blank=False, null=False ) class Invoice(models.Model): creditor = models.ForeignKey( Creditor, blank=False, null=False, on_delete=models.CASCADE ) reception_date = models.DateField( blank=True, null=True ) I am getting type int for due_on from the following queryset, instead of datetime.date and can't figure out why. invoices = Invoice.objects.annotate( due_on=ExpressionWrapper( F('reception_date') + F('creditor__terms_of_payment'), output_field=DateField() ) ) The database I'm using is MySQL. So basically if reception_date=datetime.date(2021, 5, 13) and terms_of_payment=2, I expect to get datetime.date(2021, 5, 15) but I'm getting 2021515 which is <class 'int'>. -
Including fields from a OneToOneField in Django Admin
I am attempting to add the fields from a OneToOneField into my admin view. Here is an example of how my models look. class Customer(BaseUser): name = CharField() address = CharField() secondary_information = OneToOneField("SecondaryCustomerInfo", on_delete=SET_NULL, null=True) class SecondaryCustomerInfo(models.Model): email = EmailField() And I tried adding in the fields as an inline like this. class SecondaryCustomerInfoInline(admin.StackedInline): model = SecondaryCustomerInfo class CustomerAdmin(admin.ModelAdmin): inlines = [SecondaryCustomerInfoInline] But I get the error <class 'user.admin.SecondaryCustomerInfoInline'>: (admin.E202) 'user.SecondaryCustomerInfo' has no ForeignKey to 'user.Customer'. I'm used to putting the OneToOneField on the secondary model but my coworker asked that I put it on the main Customer model since we will be accessing that information more often. I think switching things around is what is tripping me up. How would I include the fields from SecondaryCustomerInfo on the admin view for Customer? -
When i update my models.py file in Django i get an error :- AttributeError: 'tuple' object has no attribute 'rsplit'
updated models.py file in users directory from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' when i run command in terminal python manage.py makemigrations i get this: PS C:\Django\django_project> python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Django\django_project\users\models.py", line 5, in <module> class Profile(models.Model): File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 320, in __new__ new_class._prepare() File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 333, in _prepare opts._prepare(cls) File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\options.py", line 285, in _prepare pk_class = self._get_default_pk_class() File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\options.py", line 238, in _get_default_pk_class pk_class = import_string(pk_class_path) File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\module_loading.py", line 13, in import_string … -
Data in Django for loop {% for %} not loading for Modal
I am trying to display information from a django for loop in the HTML. The HTML is as follows: <div class="row"> {% for product in page.object_list %} <div class="col-lg-3"> <img class="thumbnail update-wishlist " style="height: auto" src="{{product.finalimagelink}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <a id="mySizeChart" class="button" style="vertical-align:middle"><span>Prices</span></a> <div id="mySizeChartModal" class="ebcf_modal"> <div class="ebcf_modal-content"> <span class="ebcf_close">&times;</span> <p>{{product.name}} FROM {{product.store}} £{{product.price}}</p> </div> </div> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-wishlist" style="width:50px;"><img class="button-image" src="{% static 'images/add.png' %}"></button> <h4 style="display: inline-block; float: right"><strong>£{{product.price}}</strong></h4> </div> </div> {% endfor %} </div> This works for loading the products in a grid but when clicking on <a id="mySizeChart" class="button" style="vertical-align:middle"><span>Prices</span></a> only the data for the first product is displayed. I am not sure why this is. In addtition to this, I have used JavaScript to display the Modal as a popup: $(".button").click(function() { $("#mySizeChartModal").show(); }); $("#mySizeChartModal .ebcf_close").click(function() { $("#mySizeChartModal").hide(); }); Any ideas on how I can get the data to load for each product when I click on the Modal pop up? -
Django Translation Files - Alternative to .po files
I have a legacy/non-django application where I have translation files that are in a different format from Django/gettext .po files. I would like to use all the strings in my Django application, but I would also like to continue using them in the existing application. The format of the current system is: Every language has it's own file. (ie. en.txt, de.txt, fr.txt) Each line has a string translated in to it's own language When a string is used in application, the line number that matches that string is first found in en.txt and the same line is returned from the target language. So if the string was "hello world" and on line 5 of en.txt, the function would return line 5 of de.txt which would be "hallo welt". What is the best way to use the old translation files within Django? Here are a few ideas I've thought of Create a script to create .po files from the .txt files Create my own template tags to handle translation Override the gettext system in Django to return my own translations -
How can I customize Rest Auth Registration view
I'm working on small project using Django / Rest Framework with rest_auth. and i would like to customize the registration view by asking for other fields like first_name and last_name also i would like to call some function after the registration. how can i customize the rest_auth registration -
Cannot assign "<JobImages: Logo Logo>": "JobImages.job" must be a "Job" instance
Here is my code: class JobImagesCreateView(CreateView): template_name = 'jobs/job_images.html' form_class = JobImageCreateForm success_url = reverse_lazy("dashboard") def form_valid(self, form): job = form.save() images = self.request.FILES.getlist("more_images") for i in images: JobImages.objects.create(job=job, image=i) return super().form_valid(form) -
Form fields are empty when created using instance = instance
I have two models prodcut_prices and WrongPrice. In WrongPrice the user can correct report wrong prices - when the price is reported it should also be updated in product_price. My problem is, even though I instantiate product_price at the very beginning as instance_productprice, all of its required fields returns the "this field has to be filled out" error. How come those field are not set when im using the instance instance_productprice = product_prices.objects.filter(id=pk)[0] ? Note, that all fields in product_prices are always non-empty since they are being pulled from the product_price model, which is handled in another view, thus that is not the issue. def wrong_price(request,pk): #Get the current price object instance_productprice = product_prices.objects.filter(id=pk)[0] #Get different values wrong_link = instance_productprice.link img_url = instance_productprice.image_url wrong_price = instance_productprice.last_price domain = instance_productprice.domain # Create instances instance_wrongprice = WrongPrice( link=wrong_link, correct_price=wrong_price, domain = domain) if request.method == "POST": form_wrong_price = wrong_price_form(request.POST,instance=instance_wrongprice) # Update values in product_prices form_product_price = product_prices_form(request.POST,instance=instance_productprice) form_product_price.instance.start_price = form_wrong_price.instance.correct_price form_product_price.instance.last_price = form_wrong_price.instance.correct_price if form_wrong_price.is_valid() & form_product_price.is_valid(): form_wrong_price.save() form_product_price.save() messages.success(request, "Thanks") return redirect("my_page") else: messages.error(request, form_product_price.errors) # Throws empty-field errors, messages.error(request, form_wrong_price.errors) return redirect("wrong-price", pk=pk) else: form_wrong_price = wrong_price_form(instance=instance_wrongprice) return render(request, "my_app/wrong_price.html",context={"form":form_wrong_price,"info":{"image_url":img_url}}) -
Cannot set a field value in Django form in views
I am making a todo website in which different users can sign in and have their separate todo lists, but when a user signs in and adds a task to the list that task does not get assigned to any user, so despite being present on the database it does not show up on the user's list. I am trying to assign the form object(task_form) a user after the form submission, I think that is the issue but I have no idea what else to try. views.py @login_required(login_url='todo:login') def task_add(request): if(request.method == "POST"): task_form = AddTask(request.POST) if(task_form.is_valid()): task_form.cleaned_data['user'] = request.user #trying to assign a user after all the data has been populated task_form.save() return redirect('todo:index') return render(request,'todo/task_add.html') template(task_add.html) {% block body %} <form method="POST"> {% csrf_token %} <p><label for="title">Title</label> <input type="text" name="title"></p> <p><label for="desc">Description</label> <input type="text" name="desc"></p> <p><label for="start_time">Time</label> <input type="datetime-local" name="start_time"></p> <p><label for="completed">Complete</label> <input type="radio" name="completed"></p> <input type="submit" value="Add" name="submit" class="btn btn-success"> </form> {% endblock %} models.py class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True) title = models.CharField(max_length=50) desc = models.CharField(max_length=100,null=True,blank=True) start_time = models.DateTimeField(auto_now=False,auto_now_add=False,null=True,blank=True) completed = models.BooleanField(default=False) def __str__(self): return self.title forms.py class AddTask(forms.ModelForm): class Meta: model = Task fields = '__all__' -
Create user registration and login authentication with Django CRUD
I have to create a user registration and login authentication without using Django's built-in user model. In creating a new user, the supplied username should not be existing yet and will be redirected to the login page. In logging in, the credentials must be valid to be redirected to home.html. I registered a user but when I try to log in, I get the error "too many values to unpack (expected 2)" views.py from django.shortcuts import render, redirect from .models import * def register(request): if(request.method=="POST"): username = request.POST.get('un') password = request.POST.get('pw') account = Account.objects.filter(username) if username == account.username: Account.objects.create(username=username, password=password) return render(request, 'app1/register.html') else: return render(request, 'app1/register.html') else: return render(request, 'app1/register.html') def login(request): if(request.method=="POST"): username = request.POST.get('un') password = request.POST.get('pw') account = Account.objects.filter(username) if password == account.password: return render(request, 'app1/home.html') else: return render(request, 'app1/login.html') else: return render(request, 'app1/login.html') def view_home(request): return render(request, 'app1/home.html') Is there something wrong with the views.py? -
Cannot find JavaScript script file from HTML file script
In the following Image of code, I am trying to reference the javascript file "doggies.js" that is currently in the basket folder. This happens on the click of a button on my website, but every time it says it cannot find the file. I have tried ../doggies.js as well but this does not work, is there any reason as to why this might be happening? <script type="text/javascript"> $(document).on('click', '.checkout-button', function () { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "doggies.js"; document.getElementsByTagName("head")[0].appendChild(script); return false; console.log("yo") }) </script> Here is the error Not Found: /basket/doggies.js [13/May/2021 18:50:22] "GET /basket/doggies.js HTTP/1.1" 404 3322 -
Is there any proper way to send a POST request through React using fetch()?
I am getting url as None on the API server side and the API is working fine when tested with POSTMAN and other scripts but the problem happens when sending the request in React. const imgLoad = { method: 'POST', headers: { "Content-Type":"application/json" }, body: JSON.stringify({ image_url: imageurl //image url stored in a variable & I tried using a string but the problem is still there }) } fetch("http://127.0.0.1:7000/emotion_detection/detect/", imgLoad) .then(response => response.json()) .then(data => this.setState({emotion: data})); -
Django media URL serving behind the scene through
I understand the difference between MEDAI_URL and MEDIA_ROOT that root is used for upload and URL is used to access it through HTTP but there's one thing that I don't understand as per this answer Django - MEDIA_ROOT and MEDIA_URL the webserver e.g Nginx handles the static files, not python but how does the webserver know the path to the images without python even though that it only sees the e.g 127.0.0.1/images/product11.png and the images actually stores in the path 127.0.0.1/static/images/product1.png -
How to check if geo loocation are in radius?
Help me please, I have 2 cords, cords of my base and base of my car. I have to check if my car is in 50 miles radius of my base. Cords are in lat,lng