Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should I deploy my web server with Django's default database?
I'm a noobie to Django and I'm almost at the stage of deploying a web server. I was just having some doubts with Django's database. Currently I'm using the default sqlite3 database to store all the user models as well as the info models. I'm thinking of using AWS to deploy my web sever. So when I get to that stage, should I continue with sqlite or should I switch to AWS's database or something like Firebase. If I continue with sqlite, where and how exactly will the information be stored? And what if I switch to something like PostgreSQL, where will the information be stored and will it be secure/fast (even if I manage to get thousands of users)? Thanks so much, this question might be really basic but I'm super confused. -
how to call function of views.py using modal <form action=" ">?
I have a login modal in base.html. on clicking login button modal gets open. i want that when form is submitted the action='login' should call the login function of views.py but when i try to submit, it redirect the page to the login page which does not exist ('http://127.0.0.1:8000/login'). i want to know how can i call login function of views from modal , if i'm not wrong then action='' attrb calls the function and not the page. I tried removing path of login from urls.py. base.html <div class="modal fade" id="modalLoginForm"> <div class="modal-dialog" role="document"> <div class="modal-content"> <!-- Default form login --> <form class="text-center border border-light" action="login" method="post" autocomplete="off"> {% csrf_token %} <!-- Email --> <input type="text" name="username" class="form-control mb-4" placeholder="E-mail" required> <!-- Password --> <input type="password" name="password" class="form-control mb-4" placeholder="Password" required> <div class="d-flex justify-content-around"> <div> <!-- Remember me --> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="defaultLoginFormRemember" name="remember_me"> <label class="custom-control-label" for="defaultLoginFormRemember">Remember me</label> </div> </div> <div> <!-- Forgot password --> <a href="">Forgot password?</a> </div> </div> <!-- Sign in button --> <input class="btn btn-info btn-block my-3" type="submit" value="Sign in"> </form> <!-- Default form login --> </div> </div> </div> views.py def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = … -
Attribute Error: 'function' object has no attribute 'randint'
I'm having trouble with using the random module in my Django app. When I open up a path that should display a random number, I get an error that says: 'function' object has no attribute 'randint'. I've looked this error up, and most people say that this error is because there is a stray random.py file floating around somewhere. Proof there's only one random.py file in my computer, and it is definitely the one that came with the python install. I'm 100% certain, because I uninstalled python 3.8.3 and reinstalled it twice. Here's the code in my views.py file that is calling random.randomint. def entry(request, title): entry = util.get_entry(title) randomNum = random.randint(0, 10) return render( request, "encyclopedia/entry.html", {"entry": entry, "randomNum": randomNum}, ) Then I have an HTML file that displays {{ randomNum }}. When that template gets loaded, I get this error screen. I'm banging my head against the wall trying to figure this out, so any help is greatly appreciated! -
In django application dynamic images are missing after restarting server
In my Django app I create a bunch of models at runtime dynamically. The models are created fine and they are registered properly. However, when I restart the server that my app is running on, the images are missing but the text are displaying only images are missing. -
Django deadline alert function
I'm trying to create a function in which if the manu_date deadline is today, the manu_date on the Html template would be highlighted in orange color.I'm follwoing this answer Django tasks with deadline date But my code is not working. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) method = (('SF EXPRESS', 'SF EXPRESS'),('HK POST', 'HK POST'),) shipping_method = models.CharField(max_length = 100, choices = method) box = models.CharField(max_length = 100, choices = box_choices) print_name = models.CharField(max_length=30) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) Diagnosis_note = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) manu_date = models.DateField('Manufacturing') important = models.BooleanField(default=False) def is_manu_date(self): return datetime.now() > self.manu_date order_list.html <tr> <th scope="row">{{ Order.id }}</th> <td><a href="{% url 'accounts:order-history' Order.user.username %}">{{ Order.user }}</a></td> <td>{{ Order.quote}}</td> <td>{{ Order.box }}</td> <td>{{ Order.pill_choice }}</td> <td>{{ Order.shipping_tracking }}</td> <td>{{ Order.memo }}</td> <td>{{ Order.status }}</td> <td>{{ Order.shipping_method}}</td> <td>{{Order.print_name}}</td> <td>{{Order.Diagnosis_note}}</td> <td>{{Order.date_created}}</td> {% if order.is_manu_date %} <td><div style="background-color: orange;">{{Order.manu_date }}</div></td> … -
Not able to install Django on window 10
Python 3.8.3 pip 20.0.2 I installed python and pip and also running react but now i am not able to create project not able to install django. I got some unexpected error which i show you on an image form bellow here. enter image description here -
What is the most efficient way to iterate through a dump category tree to store it using django-mptt?
Basically I want to know the most efficient way to recursively iterate through an API result from Global Selling (Mercado Libre) website. They dump the complete category tree at CBT Categories and they recommend to store it offline and update it on a daily basis (or at least frequently), as seen in here. I am currently trying to add all the records to my own Django Model using django-mptt to make it more efficient. However, I am sure there must be a better way to iterate through all the dump. { "id": "CBT1644", "name": "Air Conditioners", "path_from_root": [ { "id": "CBT5726", "name": "Appliances" }, { "id": "CBT385177", "name": "Air Conditioning" }, { "id": "CBT1644", "name": "Air Conditioners" } ], "children_categories": [], .... } I am thinking on starting using the path_from_root and go through each one of them but I don't know how to do it efficiently. Other option is going through all the "leafs" and go up creating every parent (through the children_categories node). I am sure this is more simple than I think but I can't seem to get it. Any help is greatly appreciated. Also I don't want to create a complete overhead every day I run … -
Run a file.py in django
I have a Django project, in which I have already defined the models. I write a file called my_logic.py, which contains custom logics for my app; for example, it SQL-ly queries the relevant data from the database, formats that data, and sends them to an online ML-model to get prediction. I would like to automatically run this file every hour. Is there any way to achieve this? I think the possible answer is cronjob. Thanks -
How to custom message "You do not have permission to perform this action."
Previously I used DRF (django-rest-framework), and also used locale (django translation). But the problem is, I can't modify the message of "You do not have permission to perform this action." into another language, e.g: id. By the way, the translation language from rest_auth and my own application is worked well. And this is my languange settings.py LANGUAGES = ( ('id', 'Indonesia'), ('en', 'English') ) DEFAULT_LANGUAGE = 1 LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), os.path.join(BASE_DIR, 'locale/rest_auth'), ) LANGUAGE_CODE = 'id' USE_I18N = True USE_L10N = True -
Model forn not rendering
I made a model for downloadable files. I can create then through the admin just fine. However, when I try to load my upload form no fields appear. I believe this is exactly how i render all my other forms. template.html {% load crispy_forms_tags %} <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form|crispy}} {{form.errors}} <button type="submit" class="btn submit-btn mt-3 mr-2"><i class="fa fa-share"></i> Submit</button> </form> forms.py from django import forms from .models import DownloadableFile class DownloadableFileForm(forms.ModelForm): class Meta: model = DownloadableFile fields = '__all__' models.py from django.db import models # Create your models here. class DownloadableFile(models.Model): CHOICES = ( ('MARKETING MATERIAL - (FORMS)', 'MARKETING MATERIAL - (FORMS)'), ('MARKETING MATERIAL - (LOGOS & IMAGES)', 'MARKETING MATERIAL - (LOGOS & IMAGES)'), ('OTHER DOCUMENTS & FORMS', 'OTHER DOCUMENTS & FORMS'), ) title = models.CharField(max_length=255) file_type = models.CharField(max_length=255, choices=CHOICES) description = models.TextField(blank=True, null=True) upload_date = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to='downloads/') class Meta: verbose_name_plural = "Downloadable Files" def __str__(self): return self.title views.py @login_required def create_downloadable_file_view(request): if request.method == 'POST': form = DownloadableFileForm(request.POST, request.FILES) if form.is_valid(): form = form.save() return redirect('main:homepage_view') else: form = DownloadableFileForm context = { 'files': DownloadableFile.objects.all(), } return render(request=request, template_name="dashboard/create-file.html", context=context) def delete_downloadable_file_view(request, pk): obj = get_object_or_404(DownloadableFile, pk=pk) if request.method == 'POST': obj.delete() return redirect('dashboard:dashboard_view') -
Django Variable Used In Model And View
I can find plenty of information on global variables (though I know they should be avoided so am trying to find alternatives) and sharing variables between views, though my case is a little different. At the moment I have the same variable declared in two places, one in a class in models.py (it's fired when a model is created but it's not a model declaration), and it's also passed to a template through a view. What would be my best option for storing this variable? Should it be a global or is there a better alternative? Thank you. -
Using DjangoPaypal for Subscriptions not working
Im have used Django-PayPal for one time payment and its work good. Now i want to convert it into Subscription that will automatically resubscribe the package on same day of next month or next year. This is the code of one time payment which is working fine: paypal_dict = { 'business': mailpaypal, 'amount': request.POST.get('amount'), 'item_name': 'Order {}'.format(pack.packagename), 'invoice': 'Package'+str(request.POST.get("package_id"))+str(genralsetting_views.systemtimezone(request)), 'custom': str(transactionid)+"_Package_"+str(request.POST.get("package_id"))+'_'+str(genralsetting_views.systemtimezone(request))+'_'+str(endtime)+ '_' + str(viddd)+'_'+str(request.session['id'])+'_'+str(request.session['currency']), 'currency_code': GeneralSetting.objects.get(userid__usertype="superadmin").currency, "notify_url": request.build_absolute_uri('/') + 'SubscriptionPaypalIPN', "return": request.build_absolute_uri('/') + 'index', "cancel_return": request.build_absolute_uri('/') + 'RegistrationPackages', } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'Vendor/Packages/RegistrationPackages/paypalpayment.html', {'cur':GeneralSetting.objects.get(userid__usertype="superadmin").currency,"session": request.session, 'form': form,"Data":data}) In the Django-Paypal documentation they showed the way to do subscription,as shown below: paypal_dict = { "cmd": "_xclick-subscriptions", "business": 'receiver_email@example.com', "a3": "9.99", # monthly price "p3": 1, # duration of each unit (depends on unit) "t3": "M", # duration unit ("M for Month") "src": "1", # make payments recur "sra": "1", # reattempt payment on payment error "no_note": "1", # remove extra notes (optional) "item_name": "my cool subscription", "notify_url": "http://www.example.com/your-ipn-location/", "return": "http://www.example.com/your-return-location/", "cancel_return": "http://www.example.com/your-cancel-location/", } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict, button_type="subscribe") # Output the button. form.render() I have write the code same as they said in documentation paypal_dict = { "cmd": "_xclick-subscriptions", "business": mailpaypal, "a3": "9.99", # monthly price … -
delete a user by a customer admin page in Django (not Django Admin page)
I want to make a admin page, and it can manage some user account, I can add some account by this page, delete an account one by one by this page. But I think I got something wrong...? This is my code: models.py class Account(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30, unique=True) #here some other fields def __str__(self): return self.username views.py def deleteuser(request, id): account_object = Account.objects.filter(username = id) user = Account.objects.get(username=username) user_form = UserDeleteForm(instance=user) if user_form.is_valid(): deactivate_user = user_form.save(commit=False) deactivate_user.save() return render(request, "account/profile/profile.html") else: return render(request, "account/profile/profile.html") urls.py path('accounts/delete_account/<id>/', views.deleteuser, name='deleteuser'), profile.html <a href="{% url 'deleteuser' username %}">{% trans "Delete" %}</a> I still can find way to solve it, thanks!! -
AWS elasticbeanstalk with django isn't Working
] I've never used an AWS Beanstalk before, and I get this error, and when I actually get to the address, the "502 badgateway" error is executed how can I solve this problem?(I'm using django) -
Switch languaje button not working with urls that contain slugs on Django
I'm new on Django, this is my first real project with this framework on 2.2 version. I've created a switch language button, and it works fine on every page that doesn't have a slug in the URL involved. I've created models for certain products and add them a slug field which is correctly and automatically translated from the product name. Everything works fine as soon as I'm not on a product detail page and I try to change the language. When I do this I get a 404 error because the URL it's not getting translated. For example, if I'm checking a product in English and its URL is mywebsite.com/products/random-slug-of-product and I try to change to Spanish, the URL is the same and it doesn't exist on Spanish version o my page, which gives me a 404 error. My question is, how can I force to obtain the correct URL? Here are a few pieces of my code in case I'm having an error. My switch button <div class="dropdown"> {% for language in LANGUAGES %} {% if language.0 != LANGUAGE_CODE %} <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input type="hidden" name="language" value="{{ language.0 }}"> {% trans "Language" %} … -
How do I track the number of clicks of certain element in for-loop template tag in Django?
So I have Django application. And in one of my templates, I have a for loop tag that shows a list of elements from my DB. Each element is linked to my articles written in Notion. I want to track the number of clicks of each element in the for loop, but can't figure out how. Here's my code. {% for item in articles %} <div class="row"> <a href="{{item.url}}" class="all-links" id="article#{{forloop.counter}}" target="_blank" rel="noopener noreferrer"> <div class="col"> <span class="title">{{item.title}}</span><br> <span class="subtitle">{{item.subtitle}}</span> </div> </a> </div> {% endfor %} Everyday, one article is added to the DB. (LINK to the article, to be more precise) How do I track the number of clicks? Thank you very much in advance. :) -
How to disable get request for individual model instances (retrieve) in django rest while using ModelViewSet in django rest?
So I'm trying to figure out a way that would allow me to block the get request for individual model instances(retrieve) but not the main get requests(list). I'm working with viewsets.ModelViewSet. Is there a way I can go about doing it? -
Django migration issue with Oracle Database
I am having some trouble migrating my Django database to Oracle. When do the makemigrations, there are no issues. But when I migrate, I get the following error: Operations to perform: Apply all migrations: Products, admin, auth, contenttypes, sessions Running migrations: Applying Products.0001_initial...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\db\migrations\executor.py", line 250, in apply_migration self.recorder.record_applied(migration.app_label, migration.name) File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\db\migrations\recorder.py", line 71, in record_applied self.migration_qs.create(app=app, name=name) File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\db\models\query.py", line 417, in create obj.save(force_insert=True, using=self.db) File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\db\models\base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "C:\Program Files (x86)\Google\Cloud SDK\PiSquareDjangoWebsite\DjangoEnv\lib\site-packages\django\db\models\base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) … -
Unbound Local Error,why? although similar code don't give any error is others pc?
SHOWING: UnboundLocalError at /shop/handlerequest/ local variable 'checksum' referenced before assignment In this code below: plz help @csrf_exempt def handlerequest(request): # paytm will send you post request here form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': print('order successful') else: print('order was not successful because' + response_dict['RESPMSG']) return render(request, 'shop/paymentstatus.html', {'response': response_dict}) -
How to fix "site matching query does'nt exist"
I have a Django project which I have the following INSTALLED_APP configuration in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Everything works perfectly yet. But when I add a new app name in the installed app called "django.contrib.sites" like below: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ] After adding "django.contrib.sites" when i tried to go to admin page with this url "localhost:8000/admin/" I got an error called "site matching query does'nt exist". Please help!!!! :( -
Django: CreateView not saving to database
I'm a Django newbie and have been really struggling with the piece of code that allows a user to register for my site. I have the model, the form displaying correctly on the html page and am not getting any errors, but the data posted by the form is not getting created in the database. I've researched and tried numerous code but the issue persists. I'm praying someone can take pity and help! Thank you in advance! forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'first_name', 'last_name','email', 'password'] views.py class RegisterPage(CreateView): template_name = 'register.html' form_class = UserForm success_url = reverse_lazy('login') def form_valid(self, form): if form.is_valid(): instance = form.save(commit=False) instance.save() return super(RegisterPage, self).form_valid(form) -
Executable may have wrong permissions error while ruuning selenium in cPanel Linux based Terminal
I was trying to execute selenium in cPanel Terminal with Python Language and I run the following codes in the terminal and I got the error "executable may have wrong permissions". What to do please help me. I really need help to upgrade my web app. (AdIS:3.6)[globallo@r041 AdIS]$ python Python 3.6.8 (default, Dec 26 2018, 08:10:13) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.system('ls') #Directories and Files __pycache__ adsc chromedriver chromedriver_linux64.zip db.sqlite3 mainApp manage.py pages passenger_wsgi.py public stderr.log test tmp >>> from selenium import webdriver >>> d=webdriver.Chrome(executable_path='chromedrive') Traceback (most recent call last): File "/home/globallo/virtualenv/apps.webmatrices.com/AdIS/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE)....... ..... selenium.common.exceptions.WebDriverException: Message: 'chromedrive' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home -
Send POST request to views.py from base.html template
I'm using django-notifications-hq to display notifications in the top navbar of the website, which happens to be located in the base template file, base.html. I have a small button in the navbar to set notifications to read but I'm having trouble sending the POST request to the views.py. Is there a way to send this POST request from anywhere on the website to a specific function in views.py? I've read about context processors but that only seems to help in opposite scenarios when you want to send data from views to the base template file. Function in views.py I want to send a POST request to from base.html: def mark_all_as_read(request): request.user.notifications.mark_all_as_read() return redirect('home') #ideally, just refresh the page the user is on but I can't figure that out either base.html form I want to send a request from: <ul class="dropdown-grid-menu" id="notice-link"> <a href="{% url 'messages' %}"> {% live_notify_list %} </a> <li> <form method='POST'> {% csrf_token %} <br /><button class="btn btn-sm btn-primary" href="{% url 'mark_all_as_read' %}" type="submit" role="button">Mark Read</button> </form> </li> </ul> Hoping there is an easy solution. Thanks! -
Django Tutorial Part 3
I am currently working through the Django Tutorial Part 3 (https://docs.djangoproject.com/en/3.0/intro/tutorial03/) on section "Write views that actually do something" and came upon an error: "TemplateSyntaxError at /polls/" "Error during template rendering" "Invalid block tag on line 24: '<span'. Did you forget to register or load this tag?" "http://127.0.0.1:8000/polls/" This is my views.py code: from django.http import HttpResponse from .models import Question from django.template import loader def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request,'polls/index.html',context) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) # Create your views here. This is my template code in polls/templates/polls/index.html <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} -
django detail page is not linking to detail page id
blog.html <a href="/detail/{{ detail.id }}/" class="text-dark">{{ cmccDemo.summary }}</a> url.py path('detail/<int:id>/', cmccDemos.views.detail, name='detail'), views.py def detail(request, id=None): cmccDemo_detail = get_object_or_404(CmccDemo, id=id) return render(request, 'cmccDemos/detail.html', {'cmccDemo': cmccDemo_detail}) But when i click the blog for detail it direct me to url: http://127.0.0.1:8000/detail// When I manually put http://127.0.0.1:8000/detail/1/ it works.